-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathTaskerPlugin.java
More file actions
1010 lines (846 loc) · 41.5 KB
/
TaskerPlugin.java
File metadata and controls
1010 lines (846 loc) · 41.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//package com.yourcompany.yourcondition;
//package com.yourcompany.yoursetting;
package net.dinglisch.android.tasker;
// Constants and functions for Tasker *extensions* to the plugin protocol
// See Also: http://tasker.dinglisch.net/plugins.html
// Release Notes
// v1.1 20140202
// added function variableNameValid()
// fixed some javadoc entries (thanks to David Stone)
// v1.2 20140211
// added ACTION_EDIT_EVENT
// v1.3 20140227
// added REQUESTED_TIMEOUT_MS_NONE, REQUESTED_TIMEOUT_MS_MAX and REQUESTED_TIMEOUT_MS_NEVER
// requestTimeoutMS(): added range check
// v1.4 20140516
// support for data pass through in REQUEST_QUERY intent
// some javadoc entries fixed (thanks again David :-))
// v1.5 20141120
// added RESULT_CODE_FAILED_PLUGIN_FIRST
// added Setting.VARNAME_ERROR_MESSAGE
// v1.6 20150213
// added Setting.getHintTimeoutMS()
// added Host.addHintTimeoutMS()
// v1.7 20160619
// null check for getCallingActivity() in hostSupportsOnFireVariableReplacement( Activity editActivity )
// v1.8 20161002
// added hostSupportsKeyEncoding(), setKeyEncoding() and Host.getKeysWithEncoding()
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.util.Log;
import java.net.URISyntaxException;
import java.security.SecureRandom;
import java.util.regex.Pattern;
public class TaskerPlugin {
public final static String VARIABLE_PREFIX = "%";
/**
* @see Setting#hostSupportsVariableReturn(Bundle)
*/
public final static int EXTRA_HOST_CAPABILITY_SETTING_RETURN_VARIABLES = 2;
/**
* @see Condition#hostSupportsVariableReturn(Bundle)
*/
public final static int EXTRA_HOST_CAPABILITY_CONDITION_RETURN_VARIABLES = 4;
/**
* @see Setting#hostSupportsOnFireVariableReplacement(Bundle)
*/
public final static int EXTRA_HOST_CAPABILITY_SETTING_FIRE_VARIABLE_REPLACEMENT = 8;
public final static int EXTRA_HOST_CAPABILITY_SETTING_SYNCHRONOUS_EXECUTION = 32;
public final static int EXTRA_HOST_CAPABILITY_REQUEST_QUERY_DATA_PASS_THROUGH = 64;
public final static int EXTRA_HOST_CAPABILITY_ENCODING_JSON = 128;
private final static String TAG = "TaskerPlugin";
private final static String BASE_KEY = "net.dinglisch.android.tasker";
/**
* Action that the EditActivity for an event plugin should be launched by
*/
public final static String ACTION_EDIT_EVENT = BASE_KEY + ".ACTION_EDIT_EVENT";
private final static String EXTRAS_PREFIX = BASE_KEY + ".extras.";
private final static int FIRST_ON_FIRE_VARIABLES_TASKER_VERSION = 80;
// when generating non-repeating integers, look this far back for repeats
// see getPositiveNonRepeatingRandomInteger()
private final static int RANDOM_HISTORY_SIZE = 100;
private final static String VARIABLE_NAME_START_EXPRESSION = "[\\w&&[^_]]";
private final static String VARIABLE_NAME_MID_EXPRESSION = "[\\w0-9]+";
private final static String VARIABLE_NAME_END_EXPRESSION = "[\\w0-9&&[^_]]";
public final static String VARIABLE_NAME_MAIN_PART_MATCH_EXPRESSION =
VARIABLE_NAME_START_EXPRESSION + VARIABLE_NAME_MID_EXPRESSION + VARIABLE_NAME_END_EXPRESSION;
public final static String VARIABLE_NAME_MATCH_EXPRESSION =
VARIABLE_PREFIX + "+" +
VARIABLE_NAME_MAIN_PART_MATCH_EXPRESSION;
/**
* @see #addVariableBundle(Bundle, Bundle)
* @see Host#getVariablesBundle(Bundle)
*/
private final static String EXTRA_VARIABLES_BUNDLE = EXTRAS_PREFIX + "VARIABLES";
/**
* Host capabilities, passed to plugin with edit intents
*/
private final static String EXTRA_HOST_CAPABILITIES = EXTRAS_PREFIX + "HOST_CAPABILITIES";
/**
* @see Setting#hostSupportsVariableReturn(Bundle)
*/
private final static int EXTRA_HOST_CAPABILITY_RELEVANT_VARIABLES = 16;
public final static int EXTRA_HOST_CAPABILITY_ALL =
EXTRA_HOST_CAPABILITY_SETTING_RETURN_VARIABLES |
EXTRA_HOST_CAPABILITY_CONDITION_RETURN_VARIABLES |
EXTRA_HOST_CAPABILITY_SETTING_FIRE_VARIABLE_REPLACEMENT |
EXTRA_HOST_CAPABILITY_RELEVANT_VARIABLES |
EXTRA_HOST_CAPABILITY_SETTING_SYNCHRONOUS_EXECUTION |
EXTRA_HOST_CAPABILITY_REQUEST_QUERY_DATA_PASS_THROUGH |
EXTRA_HOST_CAPABILITY_ENCODING_JSON;
private final static String BUNDLE_KEY_ENCODING_JSON_KEYS = BASE_KEY + ".JSON_ENCODED_KEYS";
/**
* Miscellaneous operational hints going one way or the other
*
* @see Setting#hostSupportsVariableReturn(Bundle)
*/
private final static String EXTRA_HINTS_BUNDLE = EXTRAS_PREFIX + "HINTS";
;
private final static String BUNDLE_KEY_HINT_PREFIX = ".hints.";
private final static String BUNDLE_KEY_HINT_TIMEOUT_MS = BUNDLE_KEY_HINT_PREFIX + "TIMEOUT";
/**
* @see #hostSupportsRelevantVariables(Bundle)
* @see #addRelevantVariableList(Intent, String[])
* @see #getRelevantVariableList(Bundle)
*/
private final static String BUNDLE_KEY_RELEVANT_VARIABLES = BASE_KEY + ".RELEVANT_VARIABLES";
private static Pattern VARIABLE_NAME_MATCH_PATTERN = null;
// state tracking for random number sequence
private static int[] lastRandomsSeen = null;
private static int randomInsertPointer = 0;
private static SecureRandom sr = null;
public static boolean hostSupportsKeyEncoding(Bundle extrasFromHost, Encoding encoding) {
switch (encoding) {
case JSON:
return hostSupports(extrasFromHost, EXTRA_HOST_CAPABILITY_ENCODING_JSON);
default:
return false;
}
}
public static boolean hostSupportsRelevantVariables(Bundle extrasFromHost) {
return hostSupports(extrasFromHost, EXTRA_HOST_CAPABILITY_RELEVANT_VARIABLES);
}
/**
* Specifies to host which variables might be used by the plugin.
* <p>
* Used in EditActivity, before setResult().
*
* @param intentToHost the intent being returned to the host
* @param variableNames array of relevant variable names
*/
public static void addRelevantVariableList(Intent intentToHost, String[] variableNames) {
intentToHost.putExtra(BUNDLE_KEY_RELEVANT_VARIABLES, variableNames);
}
/**
* Validate a variable name.
* <p>
* The basic requirement for variables from a plugin is that they must be all lower-case.
*
* @param varName name to check
*/
public static boolean variableNameValid(String varName) {
boolean validFlag = false;
if (varName == null)
Log.d(TAG, "variableNameValid: null name");
else {
if (VARIABLE_NAME_MATCH_PATTERN == null)
VARIABLE_NAME_MATCH_PATTERN = Pattern.compile(VARIABLE_NAME_MATCH_EXPRESSION, 0);
if (VARIABLE_NAME_MATCH_PATTERN.matcher(varName).matches()) {
if (variableNameIsLocal(varName))
validFlag = true;
else
Log.d(TAG, "variableNameValid: name not local: " + varName);
} else
Log.d(TAG, "variableNameValid: invalid name: " + varName);
}
return validFlag;
}
/**
* Allows the plugin/host to indicate to each other a set of variables which they are referencing.
* The host may use this to e.g. show a variable selection list in it's UI.
* The host should use this if it previously indicated to the plugin that it supports relevant vars
*
* @param fromHostIntentExtras usually from getIntent().getExtras()
* @return variableNames an array of relevant variable names
*/
public static String[] getRelevantVariableList(Bundle fromHostIntentExtras) {
String[] relevantVars = (String[]) getBundleValueSafe(fromHostIntentExtras, BUNDLE_KEY_RELEVANT_VARIABLES, String[].class, "getRelevantVariableList");
if (relevantVars == null)
relevantVars = new String[0];
return relevantVars;
}
// ----------------------------- SETTING PLUGIN ONLY --------------------------------- //
/**
* Used by: plugin QueryReceiver, FireReceiver
* <p>
* Add a bundle of variable name/value pairs.
* <p>
* Names must be valid Tasker local variable names.
* Values must be String, String [] or ArrayList<String>
* Null values cause deletion of possible already-existing variables
* A null value where the variable does not already exist results in attempted deletion
* of any existing array indices (%arr1, %arr2 etc)
*
* @param resultExtras the result extras from the receiver onReceive (from a call to getResultExtras())
* @param variables the variables to send
* @see Setting#hostSupportsVariableReturn(Bundle)
* @see #variableNameValid(String)
*/
public static void addVariableBundle(Bundle resultExtras, Bundle variables) {
resultExtras.putBundle(EXTRA_VARIABLES_BUNDLE, variables);
}
// ----------------------------- CONDITION/EVENT PLUGIN ONLY --------------------------------- //
/**
* Used by: plugin EditActivity
* <p>
* Specify the encoding for a set of bundle keys.
* <p>
* This is completely optional and currently only necessary if using Setting#setVariableReplaceKeys
* where the corresponding values of some of the keys specified are JSON encoded.
*
* @param resultBundleToHost the bundle being returned to the host
* @param keys the keys being returned to the host which are encoded in some way
* @param encoding the encoding of the values corresponding to the specified keys
* @see #setVariableReplaceKeys(Bundle, String[])
* @see #hostSupportsKeyEncoding(Bundle, Encoding)
*/
public static void setKeyEncoding(Bundle resultBundleToHost, String[] keys, Encoding encoding) {
if (Encoding.JSON.equals(encoding))
addStringArrayToBundleAsString(
keys, resultBundleToHost, BUNDLE_KEY_ENCODING_JSON_KEYS, "setValueEncoding"
);
else
Log.e(TAG, "unknown encoding: " + encoding);
}
// ----------------------------- EVENT PLUGIN ONLY --------------------------------- //
private static Object getBundleValueSafe(Bundle b, String key, Class<?> expectedClass, String funcName) {
Object value = null;
if (b != null) {
if (b.containsKey(key)) {
Object obj = b.get(key);
if (obj == null)
Log.w(TAG, funcName + ": " + key + ": null value");
else if (obj.getClass() != expectedClass)
Log.w(TAG, funcName + ": " + key + ": expected " + expectedClass.getClass().getName() + ", got " + obj.getClass().getName());
else
value = obj;
}
}
return value;
}
// ---------------------------------- HOST ----------------------------------------- //
private static Object getExtraValueSafe(Intent i, String key, Class<?> expectedClass, String funcName) {
return (i.hasExtra(key)) ?
getBundleValueSafe(i.getExtras(), key, expectedClass, funcName) :
null;
}
// ---------------------------------- HELPER FUNCTIONS -------------------------------- //
private static boolean hostSupports(Bundle extrasFromHost, int capabilityFlag) {
Integer flags = (Integer) getBundleValueSafe(extrasFromHost, EXTRA_HOST_CAPABILITIES, Integer.class, "hostSupports");
return
(flags != null) &&
((flags & capabilityFlag) > 0)
;
}
public static int getPackageVersionCode(PackageManager pm, String packageName) {
int code = -1;
if (pm != null) {
try {
PackageInfo pi = pm.getPackageInfo(packageName, 0);
if (pi != null)
code = pi.versionCode;
} catch (Exception e) {
Log.e(TAG, "getPackageVersionCode: exception getting package info");
}
}
return code;
}
private static boolean variableNameIsLocal(String varName) {
int digitCount = 0;
int length = varName.length();
for (int x = 0; x < length; x++) {
char ch = varName.charAt(x);
if (Character.isUpperCase(ch))
return false;
else if (Character.isDigit(ch))
digitCount++;
}
if (digitCount == (varName.length() - 1))
return false;
return true;
}
private static String[] getStringArrayFromBundleString(Bundle bundle, String key, String funcName) {
String spec = (String) getBundleValueSafe(bundle, key, String.class, funcName);
String[] toReturn = null;
if (spec != null)
toReturn = spec.split(" ");
return toReturn;
}
private static void addStringArrayToBundleAsString(String[] toAdd, Bundle bundle, String key, String callerName) {
StringBuilder builder = new StringBuilder();
if (toAdd != null) {
for (String keyName : toAdd) {
if (keyName.contains(" "))
Log.w(TAG, callerName + ": ignoring bad keyName containing space: " + keyName);
else {
if (builder.length() > 0)
builder.append(' ');
builder.append(keyName);
}
if (builder.length() > 0)
bundle.putString(key, builder.toString());
}
}
}
/**
* Generate a sequence of secure random positive integers which is guaranteed not to repeat
* in the last 100 calls to this function.
*
* @return a random positive integer
*/
public static int getPositiveNonRepeatingRandomInteger() {
// initialize on first call
if (sr == null) {
sr = new SecureRandom();
lastRandomsSeen = new int[RANDOM_HISTORY_SIZE];
for (int x = 0; x < lastRandomsSeen.length; x++)
lastRandomsSeen[x] = -1;
}
int toReturn;
do {
// pick a number
toReturn = sr.nextInt(Integer.MAX_VALUE);
// check we havn't see it recently
for (int seen : lastRandomsSeen) {
if (seen == toReturn) {
toReturn = -1;
break;
}
}
}
while (toReturn == -1);
// update history
lastRandomsSeen[randomInsertPointer] = toReturn;
randomInsertPointer = (randomInsertPointer + 1) % lastRandomsSeen.length;
return toReturn;
}
/**
* Possible encodings of text in bundle values
*
* @see #setKeyEncoding(Bundle, String[], Encoding)
*/
public enum Encoding {
JSON
}
public static class Setting {
/**
* Variable name into which a description of any error that occurred can be placed
* for the user to process.
* <p>
* Should *only* be set when the BroadcastReceiver result code indicates a failure.
* <p>
* Note that the user needs to have configured the task to continue after failure of the plugin
* action otherwise they will not be able to make use of the error message.
* <p>
* For use with #addRelevantVariableList(Intent, String[]) and #addVariableBundle(Bundle, Bundle)
*/
public final static String VARNAME_ERROR_MESSAGE = VARIABLE_PREFIX + "errmsg";
/**
* @see #requestTimeoutMS(android.content.Intent, int)
*/
public final static int REQUESTED_TIMEOUT_MS_NONE = 0;
/**
* @see #requestTimeoutMS(android.content.Intent, int)
*/
public final static int REQUESTED_TIMEOUT_MS_MAX = 3599000;
/**
* @see #requestTimeoutMS(android.content.Intent, int)
*/
public final static int REQUESTED_TIMEOUT_MS_NEVER = REQUESTED_TIMEOUT_MS_MAX + 1000;
/**
* @see #signalFinish(Context, Intent, int, Bundle)
* @see Host#getSettingResultCode(Intent)
*/
public final static String EXTRA_RESULT_CODE = EXTRAS_PREFIX + "RESULT_CODE";
/**
* @see #signalFinish(Context, Intent, int, Bundle)
* @see Host#getSettingResultCode(Intent)
*/
public final static int RESULT_CODE_OK = Activity.RESULT_OK;
public final static int RESULT_CODE_OK_MINOR_FAILURES = Activity.RESULT_FIRST_USER;
public final static int RESULT_CODE_FAILED = Activity.RESULT_FIRST_USER + 1;
public final static int RESULT_CODE_PENDING = Activity.RESULT_FIRST_USER + 2;
public final static int RESULT_CODE_UNKNOWN = Activity.RESULT_FIRST_USER + 3;
/**
* If a plugin wants to define it's own error codes, start numbering them here.
* The code will be placed in an error variable (%err in the case of Tasker) for
* the user to process after the plugin action.
*/
public final static int RESULT_CODE_FAILED_PLUGIN_FIRST = Activity.RESULT_FIRST_USER + 9;
public final static String EXTRA_CALL_SERVICE_PACKAGE = TaskerIntent.TASKER_PACKAGE + ".EXTRA_CALL_SERVICE_PACKAGE";
public final static String EXTRA_CALL_SERVICE = TaskerIntent.TASKER_PACKAGE + ".EXTRA_CALL_SERVICE";
public final static String EXTRA_CALL_SERVICE_FOREGROUND = TaskerIntent.TASKER_PACKAGE + ".EXTRA_CALL_SERVICE_FOREGROUND";
public final static String EXTRA_RESULT_CALL_URI = BASE_KEY + ".EXTRA_RESULT_CALL_URI";
/**
* @see #setVariableReplaceKeys(Bundle, String[])
*/
private final static String BUNDLE_KEY_VARIABLE_REPLACE_STRINGS = EXTRAS_PREFIX + "VARIABLE_REPLACE_KEYS";
/**
* @see #requestTimeoutMS(android.content.Intent, int)
*/
private final static String EXTRA_REQUESTED_TIMEOUT = EXTRAS_PREFIX + "REQUESTED_TIMEOUT";
/**
* @see #signalFinish(Context, Intent, int, Bundle)
* @see Host#addCompletionIntent(Intent, Intent, boolean)
*/
private final static String EXTRA_PLUGIN_COMPLETION_INTENT = EXTRAS_PREFIX + "COMPLETION_INTENT";
/**
* Used by: plugin EditActivity.
* <p>
* Indicates to plugin that host will replace variables in specified bundle keys.
* <p>
* Replacement takes place every time the setting is fired, before the bundle is
* passed to the plugin FireReceiver.
*
* @param extrasFromHost intent extras from the intent received by the edit activity
* @see #setVariableReplaceKeys(Bundle, String[])
*/
public static boolean hostSupportsOnFireVariableReplacement(Bundle extrasFromHost) {
return hostSupports(extrasFromHost, EXTRA_HOST_CAPABILITY_SETTING_FIRE_VARIABLE_REPLACEMENT);
}
/**
* Used by: plugin EditActivity.
* <p>
* Description as above.
* <p>
* This version also includes backwards compatibility with pre 4.2 Tasker versions.
* At some point this function will be deprecated.
*
* @param editActivity the plugin edit activity, needed to test calling Tasker version
* @see #setVariableReplaceKeys(Bundle, String[])
*/
public static boolean hostSupportsOnFireVariableReplacement(Activity editActivity) {
boolean supportedFlag = hostSupportsOnFireVariableReplacement(editActivity.getIntent().getExtras());
if (!supportedFlag) {
ComponentName callingActivity = editActivity.getCallingActivity();
if (callingActivity == null)
Log.w(TAG, "hostSupportsOnFireVariableReplacement: null callingActivity, defaulting to false");
else {
String callerPackage = callingActivity.getPackageName();
// Tasker only supporteed this from 1.0.10
supportedFlag =
(callerPackage.startsWith(BASE_KEY)) &&
(getPackageVersionCode(editActivity.getPackageManager(), callerPackage) > FIRST_ON_FIRE_VARIABLES_TASKER_VERSION)
;
}
}
return supportedFlag;
}
public static boolean hostSupportsSynchronousExecution(Bundle extrasFromHost) {
return hostSupports(extrasFromHost, EXTRA_HOST_CAPABILITY_SETTING_SYNCHRONOUS_EXECUTION);
}
/**
* Request the host to wait the specified number of milliseconds before continuing.
* Note that the host may choose to ignore the request.
* <p>
* Maximum value is REQUESTED_TIMEOUT_MS_MAX.
* Also available are REQUESTED_TIMEOUT_MS_NONE (continue immediately without waiting
* for the plugin to finish) and REQUESTED_TIMEOUT_MS_NEVER (wait forever for
* a result).
* <p>
* Used in EditActivity, before setResult().
*
* @param intentToHost the intent being returned to the host
* @param timeoutMS
*/
public static void requestTimeoutMS(Intent intentToHost, int timeoutMS) {
if (timeoutMS < 0)
Log.w(TAG, "requestTimeoutMS: ignoring negative timeout (" + timeoutMS + ")");
else {
if (
(timeoutMS > REQUESTED_TIMEOUT_MS_MAX) &&
(timeoutMS != REQUESTED_TIMEOUT_MS_NEVER)
) {
Log.w(TAG, "requestTimeoutMS: requested timeout " + timeoutMS + " exceeds maximum, setting to max (" + REQUESTED_TIMEOUT_MS_MAX + ")");
timeoutMS = REQUESTED_TIMEOUT_MS_MAX;
}
intentToHost.putExtra(EXTRA_REQUESTED_TIMEOUT, timeoutMS);
}
}
/**
* Used by: plugin EditActivity
* <p>
* Indicates to host which bundle keys should be replaced.
*
* @param resultBundleToHost the bundle being returned to the host
* @param listOfKeyNames which bundle keys to replace variables in when setting fires
* @see #hostSupportsOnFireVariableReplacement(Bundle)
* @see #setKeyEncoding(Bundle, String[], Encoding)
*/
public static void setVariableReplaceKeys(Bundle resultBundleToHost, String[] listOfKeyNames) {
addStringArrayToBundleAsString(
listOfKeyNames, resultBundleToHost, BUNDLE_KEY_VARIABLE_REPLACE_STRINGS,
"setVariableReplaceKeys"
);
}
/**
* Used by: plugin FireReceiver
* <p>
* Indicates to plugin whether the host will process variables which it passes back
*
* @param extrasFromHost intent extras from the intent received by the FireReceiver
* @see #signalFinish(Context, Intent, int, Bundle)
*/
public static boolean hostSupportsVariableReturn(Bundle extrasFromHost) {
return hostSupports(extrasFromHost, EXTRA_HOST_CAPABILITY_SETTING_RETURN_VARIABLES);
}
public static boolean signalFinish( Context context, Intent originalFireIntent, int resultCode, Bundle vars ) {
return signalFinish(context, originalFireIntent, resultCode, vars,null);
}
/**
* Used by: plugin FireReceiver
*
* Tell the host that the plugin has finished execution.
*
* This should only be used if RESULT_CODE_PENDING was returned by FireReceiver.onReceive().
*
* @param originalFireIntent the intent received from the host (via onReceive())
* @param resultCode level of success in performing the settings
* @param vars any variables that the plugin wants to set in the host
* @see #hostSupportsSynchronousExecution(Bundle)
*/
public static boolean signalFinish( Context context, Intent originalFireIntent, int resultCode, Bundle vars, Uri callbackUri ) {
String errorPrefix = "signalFinish: ";
boolean okFlag = false;
String completionIntentString = (String) getExtraValueSafe(originalFireIntent, Setting.EXTRA_PLUGIN_COMPLETION_INTENT, String.class, "signalFinish");
if (completionIntentString != null) {
Uri completionIntentUri = null;
try {
completionIntentUri = Uri.parse(completionIntentString);
}
// should only throw NullPointer but don't particularly trust it
catch (Exception e) {
Log.w(TAG, errorPrefix + "couldn't parse " + completionIntentString);
}
if (completionIntentUri != null) {
try {
Intent completionIntentSource = Intent.parseUri(completionIntentString, Intent.URI_INTENT_SCHEME);
// Create a new intent with manual copying to comply with the unsafe intent detection
Intent completionIntent = new Intent(completionIntentSource.getAction(), completionIntentSource.getData());
completionIntent.setComponent(completionIntentSource.getComponent());
completionIntentSource.putExtras(completionIntentSource.getExtras());
completionIntent.putExtra(EXTRA_RESULT_CODE, resultCode);
if (vars != null)
completionIntent.putExtra(EXTRA_VARIABLES_BUNDLE, vars);
if(callbackUri != null){
completionIntent.putExtra(EXTRA_RESULT_CALL_URI, callbackUri);
}
String callServicePackage = (String) getExtraValueSafe(completionIntent, Setting.EXTRA_CALL_SERVICE_PACKAGE, String.class, "signalFinish");
String callService = (String) getExtraValueSafe(completionIntent, Setting.EXTRA_CALL_SERVICE, String.class, "signalFinish");
Boolean foreground = (Boolean) getExtraValueSafe(completionIntent, Setting.EXTRA_CALL_SERVICE_FOREGROUND, Boolean.class, "signalFinish");
if (callServicePackage != null && callService != null && foreground != null) {
completionIntent.setComponent(new ComponentName(callServicePackage, callService));
if (foreground && android.os.Build.VERSION.SDK_INT >= 26) {
context.startForegroundService(completionIntent);
} else {
context.startService(completionIntent);
}
} else {
context.sendBroadcast(completionIntent);
}
okFlag = true;
} catch (URISyntaxException e) {
Log.w(TAG, errorPrefix + "bad URI: " + completionIntentUri);
} catch (IllegalStateException e) {
Log.w(TAG, errorPrefix + "host was not in foreground: " + completionIntentUri,e);
}
}
}
return okFlag;
}
/**
* Check for a hint on the timeout value the host is using.
* Used by: plugin FireReceiver.
* Requires Tasker 4.7+
*
* @param extrasFromHost intent extras from the intent received by the FireReceiver
* @return timeoutMS the hosts timeout setting for the action or -1 if no hint is available.
* @see #REQUESTED_TIMEOUT_MS_NONE, REQUESTED_TIMEOUT_MS_MAX, REQUESTED_TIMEOUT_MS_NEVER
*/
public static int getHintTimeoutMS(Bundle extrasFromHost) {
int timeoutMS = -1;
Bundle hintsBundle = (Bundle) TaskerPlugin.getBundleValueSafe(extrasFromHost, EXTRA_HINTS_BUNDLE, Bundle.class, "getHintTimeoutMS");
if (hintsBundle != null) {
Integer val = (Integer) getBundleValueSafe(hintsBundle, BUNDLE_KEY_HINT_TIMEOUT_MS, Integer.class, "getHintTimeoutMS");
if (val != null)
timeoutMS = val;
}
return timeoutMS;
}
}
public static class Condition {
/**
* @see #getResultReceiver(Intent)
*/
public final static String EXTRA_RESULT_RECEIVER = TaskerIntent.TASKER_PACKAGE + ".EXTRA_RESULT_RECEIVER";
/**
* Used by: plugin QueryReceiver
* <p>
* Indicates to plugin whether the host will process variables which it passes back
*
* @param extrasFromHost intent extras from the intent received by the QueryReceiver
* @see #addVariableBundle(Bundle, Bundle)
*/
public static boolean hostSupportsVariableReturn(Bundle extrasFromHost) {
return hostSupports(extrasFromHost, EXTRA_HOST_CAPABILITY_CONDITION_RETURN_VARIABLES);
}
public static ResultReceiver getResultReceiver(Intent intentFromHost) {
if (intentFromHost == null) {
return null;
}
return (ResultReceiver) getExtraValueSafe(intentFromHost, EXTRA_RESULT_RECEIVER, ResultReceiver.class, "getResultReceiver");
}
}
public static class Event {
public final static String PASS_THROUGH_BUNDLE_MESSAGE_ID_KEY = BASE_KEY + ".MESSAGE_ID";
private final static String EXTRA_REQUEST_QUERY_PASS_THROUGH_DATA = EXTRAS_PREFIX + "PASS_THROUGH_DATA";
/**
* @param extrasFromHost intent extras from the intent received by the QueryReceiver
* @see #addPassThroughData(Intent, Bundle)
*/
public static boolean hostSupportsRequestQueryDataPassThrough(Bundle extrasFromHost) {
return hostSupports(extrasFromHost, EXTRA_HOST_CAPABILITY_REQUEST_QUERY_DATA_PASS_THROUGH);
}
/**
* Specify a bundle of data (probably representing whatever change happened in the condition)
* which will be included in the QUERY_CONDITION broadcast sent by the host for each
* event instance of the plugin.
* <p>
* The minimal purpose is to enable the plugin to associate a QUERY_CONDITION to the
* with the REQUEST_QUERY that caused it.
* <p>
* Note that for security reasons it is advisable to also store a message ID with the bundle
* which can be compared to known IDs on receipt. The host cannot validate the source of
* REQUEST_QUERY intents so fake data may be passed. Replay attacks are also possible.
* addPassThroughMesssageID() can be used to add an ID if the plugin doesn't wish to add it's
* own ID to the pass through bundle.
* <p>
* Note also that there are several situations where REQUEST_QUERY will not result in a
* QUERY_CONDITION intent (e.g. event throttling by the host), so plugin-local data
* indexed with a message ID needs to be timestamped and eventually timed-out.
* <p>
* This function can be called multiple times, each time all keys in data will be added to
* that of previous calls.
*
* @param requestQueryIntent intent being sent to the host
* @param data the data to be passed-through
* @see #hostSupportsRequestQueryDataPassThrough(Bundle)
* @see #retrievePassThroughData(Intent)
* @see #addPassThroughMessageID
*/
public static void addPassThroughData(Intent requestQueryIntent, Bundle data) {
Bundle passThroughBundle = retrieveOrCreatePassThroughBundle(requestQueryIntent);
passThroughBundle.putAll(data);
}
/**
* Retrieve the pass through data from a QUERY_REQUEST from the host which was generated
* by a REQUEST_QUERY from the plugin.
* <p>
* Note that if addPassThroughMessageID() was previously called, the data will contain an extra
* key TaskerPlugin.Event.PASS_THOUGH_BUNDLE_MESSAGE_ID_KEY.
*
* @param queryConditionIntent QUERY_REQUEST sent from host
* @return data previously added to the REQUEST_QUERY intent
* @see #hostSupportsRequestQueryDataPassThrough(Bundle)
* @see #addPassThroughData(Intent, Bundle)
*/
public static Bundle retrievePassThroughData(Intent queryConditionIntent) {
return (Bundle) getExtraValueSafe(
queryConditionIntent,
EXTRA_REQUEST_QUERY_PASS_THROUGH_DATA,
Bundle.class,
"retrievePassThroughData"
);
}
/**
* Add a message ID to a REQUEST_QUERY intent which will then be included in the corresponding
* QUERY_CONDITION broadcast sent by the host for each event instance of the plugin.
* <p>
* The minimal purpose is to enable the plugin to associate a QUERY_CONDITION to the
* with the REQUEST_QUERY that caused it. It also allows the message to be verified
* by the plugin to prevent e.g. replay attacks
*
* @param requestQueryIntent intent being sent to the host
* @return an ID for the bundle so it can be identified and the caller verified when it is again received by the plugin
* @see #hostSupportsRequestQueryDataPassThrough(Bundle)
* @see #retrievePassThroughData(Intent)
*/
public static int addPassThroughMessageID(Intent requestQueryIntent) {
Bundle passThroughBundle = retrieveOrCreatePassThroughBundle(requestQueryIntent);
int id = getPositiveNonRepeatingRandomInteger();
passThroughBundle.putInt(PASS_THROUGH_BUNDLE_MESSAGE_ID_KEY, id);
return id;
}
/*
* Retrieve the pass through data from a QUERY_REQUEST from the host which was generated
* by a REQUEST_QUERY from the plugin.
*
* @param queryConditionIntent QUERY_REQUEST sent from host
* @return the ID which was passed through by the host, or -1 if no ID was found
* @see #hostSupportsRequestQueryDataPassThrough(Bundle)
* @see #addPassThroughData(Intent,Bundle)
*/
public static int retrievePassThroughMessageID(Intent queryConditionIntent) {
int toReturn = -1;
Bundle passThroughData = Event.retrievePassThroughData(queryConditionIntent);
if (passThroughData != null) {
Integer id = (Integer) getBundleValueSafe(
passThroughData,
PASS_THROUGH_BUNDLE_MESSAGE_ID_KEY,
Integer.class,
"retrievePassThroughMessageID"
);
if (id != null)
toReturn = id;
}
return toReturn;
}
// internal use
private static Bundle retrieveOrCreatePassThroughBundle(Intent requestQueryIntent) {
Bundle passThroughBundle;
if (requestQueryIntent.hasExtra(EXTRA_REQUEST_QUERY_PASS_THROUGH_DATA))
passThroughBundle = requestQueryIntent.getBundleExtra(EXTRA_REQUEST_QUERY_PASS_THROUGH_DATA);
else {
passThroughBundle = new Bundle();
requestQueryIntent.putExtra(EXTRA_REQUEST_QUERY_PASS_THROUGH_DATA, passThroughBundle);
}
return passThroughBundle;
}
}
public static class Host {
/**
* Tell the plugin what capabilities the host support. This should be called when sending
* intents to any EditActivity, FireReceiver or QueryReceiver.
*
* @param toPlugin the intent we're sending
* @return capabilities one or more of the EXTRA_HOST_CAPABILITY_XXX flags
*/
public static Intent addCapabilities(Intent toPlugin, int capabilities) {
return toPlugin.putExtra(EXTRA_HOST_CAPABILITIES, capabilities);
}
/**
* Add an intent to the fire intent before it goes to the plugin FireReceiver, which the plugin
* can use to signal when it is finished. Only use if @code{pluginWantsSychronousExecution} is true.
*
* @param fireIntent fire intent going to the plugin
* @param completionIntent intent which will signal the host that the plugin is finished.
* Implementation is host-dependent.
*/
public static void addCompletionIntent(Intent fireIntent, Intent completionIntent, ComponentName callService) {
if (callService != null) {
completionIntent.putExtra(Setting.EXTRA_CALL_SERVICE_PACKAGE, callService.getPackageName());
completionIntent.putExtra(Setting.EXTRA_CALL_SERVICE, callService.getClassName());
completionIntent.putExtra(Setting.EXTRA_CALL_SERVICE_FOREGROUND, android.os.Build.VERSION.SDK_INT >= 26);
}
fireIntent.putExtra(
Setting.EXTRA_PLUGIN_COMPLETION_INTENT,
completionIntent.toUri(Intent.URI_INTENT_SCHEME)
);
}
/**
* When a setting plugin is finished, it sends the host the intent which was passed to it
* via @code{addCompletionIntent}.
*
* @param completionIntent intent returned from the plugin when it finished.
* @return resultCode measure of plugin success, defaults to UNKNOWN
*/
public static int getSettingResultCode(Intent completionIntent) {
Integer val = (Integer) getExtraValueSafe(completionIntent, Setting.EXTRA_RESULT_CODE, Integer.class, "getSettingResultCode");
return (val == null) ? Setting.RESULT_CODE_UNKNOWN : val;
}
/**
* Extract a bundle of variables from an intent received from the FireReceiver. This
* should be called if the host previously indicated to the plugin
* that it supports setting variable return.
*
* @param resultExtras getResultExtras() from BroadcastReceiver:onReceive()
* @return variables a bundle of variable name/value pairs
* @see #addCapabilities(Intent, int)
*/
public static Bundle getVariablesBundle(Bundle resultExtras) {
return (Bundle) getBundleValueSafe(
resultExtras, EXTRA_VARIABLES_BUNDLE, Bundle.class, "getVariablesBundle"
);
}
/**
* Inform a setting plugin of the timeout value the host is using.
*
* @param toPlugin the intent we're sending
* @param timeoutMS the hosts timeout setting for the action. Note that this may differ from
* that which the plugin requests.
* @see #REQUESTED_TIMEOUT_MS_NONE, REQUESTED_TIMEOUT_MS_MAX, REQUESTED_TIMEOUT_MS_NEVER
*/
public static void addHintTimeoutMS(Intent toPlugin, int timeoutMS) {
getHintsBundle(toPlugin, "addHintTimeoutMS").putInt(BUNDLE_KEY_HINT_TIMEOUT_MS, timeoutMS);
}
private static Bundle getHintsBundle(Intent intent, String funcName) {
Bundle hintsBundle = (Bundle) getExtraValueSafe(intent, EXTRA_HINTS_BUNDLE, Bundle.class, funcName);
if (hintsBundle == null) {
hintsBundle = new Bundle();
intent.putExtra(EXTRA_HINTS_BUNDLE, hintsBundle);
}
return hintsBundle;
}
public static boolean haveRequestedTimeout(Bundle extrasFromPluginEditActivity) {
return extrasFromPluginEditActivity.containsKey(Setting.EXTRA_REQUESTED_TIMEOUT);
}
public static int getRequestedTimeoutMS(Bundle extrasFromPluginEditActivity) {
return
(Integer) getBundleValueSafe(
extrasFromPluginEditActivity, Setting.EXTRA_REQUESTED_TIMEOUT, Integer.class, "getRequestedTimeout"
)
;
}
public static String[] getSettingVariableReplaceKeys(Bundle fromPluginEditActivity) {
return getStringArrayFromBundleString(
fromPluginEditActivity, Setting.BUNDLE_KEY_VARIABLE_REPLACE_STRINGS,
"getSettingVariableReplaceKeys"
);
}
public static String[] getKeysWithEncoding(Bundle fromPluginEditActivity, Encoding encoding) {
String[] toReturn = null;
if (Encoding.JSON.equals(encoding))
toReturn = getStringArrayFromBundleString(
fromPluginEditActivity, TaskerPlugin.BUNDLE_KEY_ENCODING_JSON_KEYS,
"getKeyEncoding:JSON"
);
else
Log.w(TAG, "Host.getKeyEncoding: unknown encoding " + encoding);
return toReturn;
}
public static boolean haveRelevantVariables(Bundle b) {
return b.containsKey(BUNDLE_KEY_RELEVANT_VARIABLES);
}
public static void cleanRelevantVariables(Bundle b) {
b.remove(BUNDLE_KEY_RELEVANT_VARIABLES);
}
public static void cleanHints(Bundle extras) {
extras.remove(TaskerPlugin.EXTRA_HINTS_BUNDLE);
}