/
Splash.java.in
704 lines (627 loc) · 19.5 KB
/
Splash.java.in
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
package @APP_PACKAGE@;
import static android.content.pm.PackageManager.FEATURE_LEANBACK;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.IOException;
import java.lang.System;
import java.util.Enumeration;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class Splash extends Activity
{
private static final int Uninitialized = 0;
private static final int InError = 1;
private static final int Checking = 2;
private static final int ChecksDone = 3;
private static final int Clearing = 4;
private static final int Caching = 5;
private static final int CachingDone = 6;
private static final int WaitingStorageChecked = 7;
private static final int StorageChecked = 8;
private static final int CheckingPermissions = 9;
private static final int CheckingPermissionsDone = 10;
private static final int CheckingPermissionsInfo = 11;
private static final int CheckExternalStorage = 12;
private static final int RecordAudioPermission = 13;
private static final int StartingXBMC = 99;
private static final String TAG = "@APP_NAME@";
private static final int RECORDAUDIO_RESULT_CODE = 8946;
private static final int PERMISSION_RESULT_CODE = 8947;
private String mErrorMsg = "";
private ProgressBar mProgress = null;
private TextView mTextView = null;
private int mState = Uninitialized;
public AlertDialog myAlertDialog;
private String sPackagePath = "";
private String sXbmcHome = "";
private File fPackagePath = null;
private File fXbmcHome = null;
private BroadcastReceiver mExternalStorageReceiver = null;
private boolean mExternalStorageChecked = false;
private boolean mCachingDone = false;
private boolean mPermissionOK = false;
private class StateMachine extends Handler
{
private final Splash mSplash;
StateMachine(Splash a)
{
super(Looper.myLooper());
this.mSplash = a;
}
@Override
public void handleMessage(Message msg)
{
mSplash.mState = msg.what;
switch (mSplash.mState)
{
case InError:
showErrorDialog(mSplash, "Error", mErrorMsg);
break;
case CheckingPermissionsInfo:
AlertDialog dialog = new AlertDialog.Builder(mSplash).create();
dialog.setCancelable(false);
dialog.setTitle("Info");
dialog.setMessage("@APP_NAME@ requires access to your device media and files to function. Please allow this via the following dialogue box or @APP_NAME@ will exit.");
dialog.setButton(DialogInterface.BUTTON_NEUTRAL, "continue",
(dialog1, which) -> mStateMachine.sendEmptyMessage(RecordAudioPermission));
dialog.show();
break;
case RecordAudioPermission:
mSplash.mTextView.setText("Asking for permissions...");
mSplash.mProgress.setVisibility(View.INVISIBLE);
requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO},
RECORDAUDIO_RESULT_CODE);
break;
case CheckingPermissions:
if (Build.VERSION.SDK_INT >= 33 || (Build.VERSION.SDK_INT >= 30 && !isAndroidTV()))
{
try
{
Intent intent = new Intent();
intent.setAction(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
intent.setData(Uri.parse(String.format("package:%s", getPackageName())));
startActivityForResult(intent, PERMISSION_RESULT_CODE);
}
catch (Exception e)
{
Log.d(TAG, "Exception asking for permissions: " + e.getMessage());
}
}
else
{
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
PERMISSION_RESULT_CODE);
}
break;
case CheckingPermissionsDone:
if (mPermissionOK)
sendEmptyMessage(CheckExternalStorage);
else
{
mErrorMsg = "Permission denied!! Exiting...";
sendEmptyMessage(InError);
break;
}
break;
case Checking:
break;
case Clearing:
mSplash.mTextView.setText("Clearing cache...");
mSplash.mProgress.setVisibility(View.INVISIBLE);
break;
case Caching:
if (!mCachingDone)
new FillCache(mSplash).execute();
else
mStateMachine.sendEmptyMessage(CachingDone);
break;
case CachingDone:
mSplash.mCachingDone = true;
sendEmptyMessage(StartingXBMC);
break;
case CheckExternalStorage:
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))
{
mExternalStorageChecked = true;
sendEmptyMessage(StorageChecked);
}
else
{
startWatchingExternalStorage();
sendEmptyMessage(WaitingStorageChecked);
}
break;
case WaitingStorageChecked:
mSplash.mTextView.setText("Waiting for external storage...");
mSplash.mProgress.setVisibility(View.INVISIBLE);
break;
case StorageChecked:
mSplash.mTextView.setText("External storage OK...");
mExternalStorageChecked = true;
mSplash.stopWatchingExternalStorage();
if (mSplash.mCachingDone)
sendEmptyMessage(StartingXBMC);
else
{
SetupEnvironment();
if (mState == InError)
{
sendEmptyMessage(InError);
}
if (fXbmcHome.exists() && fXbmcHome.lastModified() >= fPackagePath.lastModified())
{
mState = CachingDone;
mCachingDone = true;
sendEmptyMessage(StartingXBMC);
}
else
{
new FillCache(mSplash).execute();
}
}
break;
case StartingXBMC:
mSplash.mTextView.setText("Starting @APP_NAME@...");
mSplash.mProgress.setVisibility(View.INVISIBLE);
mSplash.startXBMC();
break;
default:
break;
}
}
}
private final StateMachine mStateMachine = new StateMachine(this);
private class FillCache
{
private final Splash mSplash;
private int mProgressStatus = 0;
private final ExecutorService executor;
private final Handler handler;
public FillCache(Splash splash)
{
mSplash = splash;
executor = Executors.newSingleThreadExecutor();
handler = new Handler(Looper.getMainLooper());
}
public void execute()
{
executor.execute(() -> {
Integer result = doInBackground();
handler.post(() -> onPostExecute(result));
});
}
protected void publishProgress(Integer value)
{
handler.post(() -> onProgressUpdate(value));
}
void DeleteRecursive(File fileOrDirectory)
{
if (fileOrDirectory.isDirectory()) {
File[] files = fileOrDirectory.listFiles();
if (files != null)
for (File child : files)
DeleteRecursive(child);
}
fileOrDirectory.delete();
}
protected Integer doInBackground()
{
if (fXbmcHome.exists())
{
// Remove existing files
mStateMachine.sendEmptyMessage(Clearing);
Log.d(TAG, "Removing existing " + fXbmcHome.toString());
DeleteRecursive(fXbmcHome);
}
fXbmcHome.mkdirs();
Log.d(TAG, "apk: " + sPackagePath);
Log.d(TAG, "output: " + sXbmcHome);
ZipFile zip;
byte[] buf = new byte[4096];
int n;
try
{
zip = new ZipFile(sPackagePath);
Enumeration<? extends ZipEntry> entries = zip.entries();
mProgress.setProgress(0);
mProgress.setMax(zip.size());
mState = Caching;
publishProgress(mProgressStatus);
String cXbmcHome = fXbmcHome.getCanonicalPath();
Log.d(TAG, "output: " + cXbmcHome);
while (entries.hasMoreElements())
{
// Update the progress bar
publishProgress(++mProgressStatus);
ZipEntry e = entries.nextElement();
String sName = e.getName();
if (!sName.startsWith("assets/"))
continue;
String sFullPath = sXbmcHome + "/" + sName;
File fFullPath = new File(sFullPath);
// Zip Path Traversal vulnerability
String cFullPath = fFullPath.getCanonicalPath();
if (!cFullPath.startsWith(cXbmcHome)) {
Log.w(TAG, "Unsafe unzipping pattern: " + cFullPath);
continue;
}
if (e.isDirectory())
{
fFullPath.mkdirs();
continue;
}
File parent = fFullPath.getParentFile();
if (parent != null && !parent.exists())
parent.mkdirs();
try
{
InputStream in = zip.getInputStream(e);
FileOutputStream out = new FileOutputStream(sFullPath);
while ((n = in.read(buf)) > 0)
out.write(buf, 0, n);
in.close();
out.close();
}
catch (IOException e1)
{
Log.e(TAG, "Exception: " + e1.getMessage());
}
}
zip.close();
fXbmcHome.setLastModified(fPackagePath.lastModified());
}
catch (FileNotFoundException e1)
{
Log.e(TAG, "Exception: " + e1.getMessage());
mErrorMsg = "Cannot find package.";
return -1;
}
catch (IOException e)
{
Log.e(TAG, "Exception: " + e.getMessage());
mErrorMsg = "Cannot read package.";
File obb = new File(sPackagePath);
obb.delete();
return -1;
}
mState = CachingDone;
publishProgress(0);
return 0;
}
protected void onProgressUpdate(Integer value)
{
switch (mState)
{
case Caching:
mSplash.mTextView.setText("Preparing for first run. Please wait...");
mSplash.mProgress.setVisibility(View.VISIBLE);
mSplash.mProgress.setProgress(value);
break;
case CachingDone:
mSplash.mProgress.setVisibility(View.INVISIBLE);
break;
}
}
protected void onPostExecute(Integer result)
{
if (result < 0)
{
mState = InError;
}
mStateMachine.sendEmptyMessage(mState);
}
}
public void showErrorDialog(final Activity act, final String title, final String message)
{
if (myAlertDialog != null && myAlertDialog.isShowing())
return;
AlertDialog.Builder builder = new AlertDialog.Builder(act);
builder.setTitle(title);
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setMessage(Html.fromHtml(message, Html.FROM_HTML_MODE_LEGACY));
builder.setPositiveButton("Exit", (dialog, arg1) -> {
dialog.dismiss();
act.finish();
});
builder.setCancelable(false);
myAlertDialog = builder.create();
myAlertDialog.show();
// Make links actually clickable
((TextView) myAlertDialog.findViewById(android.R.id.message))
.setMovementMethod(LinkMovementMethod.getInstance());
}
private void SetupEnvironment()
{
sXbmcHome = XBMCProperties.getStringProperty("xbmc.home", "");
if (!sXbmcHome.isEmpty())
{
fXbmcHome = new File(sXbmcHome);
int loop = 20;
while (!fXbmcHome.exists() && loop > 0)
{
// Wait a while in case of non-primary sdcard
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
continue;
}
loop--;
}
if (!fXbmcHome.exists())
{
System.setProperty("xbmc.home", "");
sXbmcHome = "";
}
}
File fCacheDir = getCacheDir();
if (sXbmcHome.isEmpty())
{
sXbmcHome = fCacheDir.getAbsolutePath() + "/apk";
fXbmcHome = new File(sXbmcHome);
}
File fLibCache = new File(fCacheDir.getAbsolutePath() + "/lib");
fLibCache.mkdirs();
final String sXbmcdata = XBMCProperties.getStringProperty("xbmc.data", "");
if (!sXbmcdata.isEmpty())
{
File fXbmcData = new File(sXbmcdata);
int loop = 20;
while (!fXbmcData.exists() && loop > 0)
{
// Wait a while in case of non-primary sdcard
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
continue;
}
loop--;
}
if (!fXbmcData.exists())
{
System.setProperty("xbmc.data", "");
}
}
final String sXbmcTemp = XBMCProperties.getStringProperty("xbmc.temp", "");
if (!sXbmcTemp.isEmpty())
{
File fXbmcTemp = new File(sXbmcTemp);
int loop = 20;
while (!fXbmcTemp.exists() && loop > 0)
{
// Wait a while in case of non-primary sdcard
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
continue;
}
loop--;
}
if (!fXbmcTemp.exists())
{
System.setProperty("xbmc.temp", "");
}
}
sPackagePath = getPackageResourcePath();
fPackagePath = new File(sPackagePath);
}
private boolean CheckPermissions()
{
boolean retVal = false;
if (Build.VERSION.SDK_INT >= 33 || (Build.VERSION.SDK_INT >= 30 && !isAndroidTV()))
{
if (Environment.isExternalStorageManager())
{
retVal = true;
}
}
else
{
int permissionCheck;
permissionCheck = checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permissionCheck == PERMISSION_GRANTED)
retVal = true;
}
return retVal;
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
{
switch (requestCode)
{
case PERMISSION_RESULT_CODE:
{
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PERMISSION_GRANTED)
{
mPermissionOK = true;
}
mStateMachine.sendEmptyMessage(CheckingPermissionsDone);
break;
}
case RECORDAUDIO_RESULT_CODE:
{
mStateMachine.sendEmptyMessage(CheckingPermissions);
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PERMISSION_RESULT_CODE)
{
if (Environment.isExternalStorageManager())
{
mPermissionOK = true;
}
mStateMachine.sendEmptyMessage(CheckingPermissionsDone);
}
}
void updateExternalStorageState()
{
String state = Environment.getExternalStorageState();
Log.d(TAG, "External storage = " + Environment.getExternalStorageDirectory().getAbsolutePath() + "; state = " + state);
if (Environment.MEDIA_MOUNTED.equals(state))
{
mStateMachine.sendEmptyMessage(StorageChecked);
}
else
{
mExternalStorageChecked = false;
}
}
void startWatchingExternalStorage()
{
mExternalStorageReceiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
Log.i(TAG, "Storage: " + intent.getData());
updateExternalStorageState();
}
};
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
filter.addAction(Intent.ACTION_MEDIA_REMOVED);
filter.addAction(Intent.ACTION_MEDIA_SHARED);
filter.addAction(Intent.ACTION_MEDIA_UNMOUNTABLE);
filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
filter.addDataScheme("file");
registerReceiver(mExternalStorageReceiver, filter);
}
void stopWatchingExternalStorage()
{
if (mExternalStorageReceiver != null)
unregisterReceiver(mExternalStorageReceiver);
}
protected void startXBMC()
{
// Run @APP_NAME@
Intent intent = getIntent();
intent.setClass(this, @APP_PACKAGE@.Main.class);
intent.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
startActivity(intent);
finish();
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Be sure properties are initialized for native
XBMCProperties.initializeProperties();
// Check if @APP_NAME@ is not already running
ActivityManager activityManager = (ActivityManager) getBaseContext()
.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> tasks = activityManager
.getRunningTasks(Integer.MAX_VALUE);
for (RunningTaskInfo task : tasks)
if (task.topActivity != null && task.topActivity.toString().equalsIgnoreCase(
"ComponentInfo{@APP_PACKAGE@/@APP_PACKAGE@.Main}"))
{
// @APP_NAME@ already running; just activate it
startXBMC();
return;
}
mStateMachine.sendEmptyMessage(Checking);
Log.d(TAG, "External storage = " + Environment.getExternalStorageDirectory().getAbsolutePath() + "; state = " + Environment.getExternalStorageState());
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))
mExternalStorageChecked = true;
mPermissionOK = CheckPermissions();
if (!mPermissionOK)
{
mState = CheckingPermissionsInfo;
}
else
{
if (mState != InError && mExternalStorageChecked)
{
mState = ChecksDone;
SetupEnvironment();
if (mState != InError && fXbmcHome.exists() && fXbmcHome.lastModified() >= fPackagePath.lastModified())
{
mState = CachingDone;
mCachingDone = true;
}
}
}
if (mState != InError && mCachingDone && mExternalStorageChecked && mPermissionOK)
{
startXBMC();
return;
}
setContentView(R.layout.activity_splash);
mProgress = findViewById(R.id.progressBar1);
mTextView = findViewById(R.id.textView1);
if (mState == InError || mState == CheckingPermissionsInfo)
{
mStateMachine.sendEmptyMessage(mState);
return;
}
if (!mExternalStorageChecked)
{
startWatchingExternalStorage();
mStateMachine.sendEmptyMessage(WaitingStorageChecked);
}
else
{
if (!mCachingDone)
new FillCache(this).execute();
else
mStateMachine.sendEmptyMessage(CachingDone);
}
}
private boolean isAndroidTV()
{
if (getPackageManager().hasSystemFeature(FEATURE_LEANBACK))
{
Log.d(TAG, "Running on an Android TV Device");
return true;
}
else
{
Log.d(TAG, "Running on a non Android TV Device");
return false;
}
}
}