summaryrefslogtreecommitdiffstats
path: root/Android/src/com/mcserver/MCServerInstaller.java
blob: 5a865a602abd0dd0059a971750195ee67b8cb804 (plain) (blame)
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
package com.mcserver;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetManager;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;

public class MCServerInstaller {
	private MCServerActivity mContext;
	final private String BaseDirectory = "basedir";
	final private String PluginDirectory = "Plugins";
	
	final public String SHARED_PREFS_NAME = "MCSERVER_PREFS";
	final public String PREF_IS_INSTALLED = "IS_INSTALLED";
	final public String PREF_LAST_VERSION = "LAST_VERSION";
	private SharedPreferences mSettings = null;
	
	int thisVersion;
	
	MCServerInstaller( MCServerActivity activity )
	{
		mContext = activity;
		
		mSettings = mContext.getSharedPreferences( SHARED_PREFS_NAME, 0);
		
		try {
			this.thisVersion = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0).versionCode;
		} catch (NameNotFoundException e) {
			Log.e("MCServer", "Could not read version code from manifest!");
			e.printStackTrace();
			this.thisVersion = -1;
		}
	}

	
	public boolean IsInstalled()
	{
		return mSettings.getBoolean(PREF_IS_INSTALLED, false);
	}
	
	
	public boolean NeedsUpdate()
	{
		Log.i("MCServer", "thisVersion: " + this.thisVersion + " pref: " + mSettings.getInt(PREF_LAST_VERSION, 0));
		return mSettings.getInt(PREF_LAST_VERSION, 0) != this.thisVersion;
	}
	
	
    public ArrayList<String> FindFoldersInPath(String path)
    {
    	ArrayList<String> allFolders = new ArrayList<String>();
		AssetManager am = mContext.getAssets();
		try {
			String[] allPlugins = am.list(path);
			for(String pluginName : allPlugins)
			{
				InputStream istr = null;
				try
				{
					istr = am.open(path + "/" + pluginName);
				} catch( java.io.FileNotFoundException e ) {
					// It seems to be a folder :D
					allFolders.add(pluginName);
					continue;
				}
		        istr.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return allFolders;
    }
    
    
    
    
    public void ExpandAssets( String path )
    {
		AssetManager am = mContext.getAssets();
		try {
			String[] getAssets = am.list(path);
			for(String assetName : getAssets)
			{
				//Log.e("MCServer", path + "/" + imgName);
								
				InputStream istr = null;
				try
				{
					istr = am.open(path + "/" + assetName);
				} catch( java.io.FileNotFoundException e ) {
					//Log.e("MCServer", "Could not open" + path + "/" + imgName );
					ExpandAssets(path + "/" + assetName);
					continue;
				}
				
				String outPath = Environment.getExternalStorageDirectory().getPath() + "/mcserver/" + path + "/" + assetName;
				//Log.e("MCServer", "outPath: " + outPath );
				File f = new File( outPath );
				
				f.getParentFile().mkdirs();
				f.createNewFile();
				OutputStream ostr = new FileOutputStream(f);
				
				byte[] buffer = new byte[1024];
		        int length;
		        while ((length = istr.read(buffer))>0)
		        {
		            ostr.write(buffer, 0, length);
		        }
		        ostr.flush();
		        ostr.close();
		        istr.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
    
    
    void ShowFirstRunDialog()
    {
    	AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
    	//builder.setTitle("blaa");
    	builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
    	builder.setMessage("It seems this is the first time you are running MCServer on your Android device or it has been updated! This app comes with a couple of pre-packaged plugins, please take a moment to select the plugins you would like to install.");
    	builder.setCancelable(false);
    	AlertDialog dialog = builder.create();
    	dialog.show();
    	
    	dialog.setOnDismissListener( new DialogInterface.OnDismissListener(){
			public void onDismiss(DialogInterface dialog) {
				ShowPluginInstallDialog(false);
			}
    	});
    }
    
    
    public void ShowPluginInstallDialog(boolean bCancelable)
    {
    	final ArrayList<String> allPlugins = FindFoldersInPath( BaseDirectory + "/" + PluginDirectory );
    	final CharSequence[] items = allPlugins.toArray(new CharSequence[allPlugins.size()]);
    	final boolean[] selected = new boolean[items.length];
    	for( int i = 0; i < items.length; ++i )
    	{
    		if( items[i].toString().contains("Core") )
    		{	// Select the core plugin by default
    			selected[i] = true;
    			items[i] = items[i] + " (Recommended)";
    		}
    	}
    	
		AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
    	builder.setTitle("Plugins to install");
    	builder.setCancelable(bCancelable);
    	builder.setMultiChoiceItems(items, selected, new DialogInterface.OnMultiChoiceClickListener() {
			public void onClick(DialogInterface dialog, int which, boolean isChecked) {
				selected[which] = isChecked;
			}
    	});
    	builder.setPositiveButton("Install", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				ArrayList<String> toInstall = new ArrayList<String>();
				for( int i = 0; i < selected.length; ++i )
				{
					if( selected[i] )
					{
						toInstall.add(allPlugins.get(i));
					}
				}
				InstallPlugins(toInstall);
			}
		});
    	
    	AlertDialog dialog2 = builder.create();
    	dialog2.show();
    }
    
    
    void InstallPlugins( final ArrayList<String> plugins )
    {
    	new AsyncTask<Void, Integer, Boolean>()
        {
            ProgressDialog progressDialog;

            @Override
            protected void onPreExecute()
            {
                /*
                 * This is executed on UI thread before doInBackground(). It is
                 * the perfect place to show the progress dialog.
                 */
                progressDialog = ProgressDialog.show(mContext, "", "Installing...");
                
            }

            @Override
            protected Boolean doInBackground(Void... params)
            {
                if (params == null)
                {
                    return false;
                }
                try
                {
                    /*
                     * This is run on a background thread, so we can sleep here
                     * or do whatever we want without blocking UI thread. A more
                     * advanced use would download chunks of fixed size and call
                     * publishProgress();
                     */
                	for( int i = 0; i < plugins.size(); ++i )
                	{
                		this.publishProgress((int)(i / (float)plugins.size() * 100), i);
                		InstallSinglePlugin(PluginDirectory + "/" + plugins.get(i));
                	}
                	
                	this.publishProgress( 100, -1 );
                	InstallExampleSettings();
                	
                	this.publishProgress( 100, -2 );
                	InstallWebAdmin();
                	
                }
                catch (Exception e)
                {
                    Log.e("tag", e.getMessage());
                    /*
                     * The task failed
                     */
                    return false;
                }

                /*
                 * The task succeeded
                 */
                return true;
            }
            
            protected void onProgressUpdate(Integer... progress) 
            {
            	progressDialog.setProgress(progress[0]);
            	if( progress[1] > -1 )
            	{
            		progressDialog.setMessage("Installing " + plugins.get(progress[1]) + "..." );
            	}
            	else if( progress[1] == -1 )
            	{
            		progressDialog.setMessage("Installing default settings...");
            	}
            	else if( progress[1] == -2 )
            	{
            		progressDialog.setMessage("Installing WebAdmin...");
            	}
            }

            @Override
            protected void onPostExecute(Boolean result)
            {
                progressDialog.dismiss();
                /*
                 * Update here your view objects with content from download. It
                 * is save to dismiss dialogs, update views, etc., since we are
                 * working on UI thread.
                 */
                AlertDialog.Builder b = new AlertDialog.Builder(mContext);
                b.setTitle(android.R.string.dialog_alert_title);
                if (result)
                {
                    b.setMessage("Install succeeded");
                    
    				SharedPreferences.Editor editor = mSettings.edit();
    				editor.putBoolean(PREF_IS_INSTALLED, true);
    				editor.putInt(PREF_LAST_VERSION, thisVersion);
    				editor.commit();
                }
                else
                {
                    b.setMessage("Install failed");
                }
                b.setPositiveButton(android.R.string.ok,
                        new DialogInterface.OnClickListener()
                        {
							public void onClick(DialogInterface dialog, int which) 
							{
								dialog.dismiss();
							}
                        });
                b.create().show();
            }
        }.execute();
    }
    
    
    void InstallExampleSettings()
    {
		AssetManager am = mContext.getAssets();
		try {
			String[] allFiles = am.list(BaseDirectory);
			for(String fileName : allFiles)
			{
				InputStream istr = null;
				try
				{
					istr = am.open(BaseDirectory + "/" + fileName);
				} catch( java.io.FileNotFoundException e ) {
					// Must be a folder :D
					continue;
				}
				
				String outPath = Environment.getExternalStorageDirectory().getPath() + "/mcserver/" + fileName;
				Log.i("MCServer", "outPath: " + outPath );
				File f = new File( outPath );
				
				f.getParentFile().mkdirs();
				f.createNewFile();
				OutputStream ostr = new FileOutputStream(f);
				
				byte[] buffer = new byte[1024];
		        int length;
		        while ((length = istr.read(buffer))>0)
		        {
		            ostr.write(buffer, 0, length);
		        }
		        ostr.flush();
		        ostr.close();
		        istr.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
    
    
    void InstallWebAdmin()
    {
		AssetManager am = mContext.getAssets();
		try {
			String[] allFiles = am.list(BaseDirectory + "/webadmin");
			for(String fileName : allFiles)
			{
				InputStream istr = null;
				try
				{
					istr = am.open(BaseDirectory + "/webadmin/" + fileName);
				} catch( java.io.FileNotFoundException e ) {
					// Must be a folder :D
					continue;
				}
				
				String outPath = Environment.getExternalStorageDirectory().getPath() + "/mcserver/webadmin/" + fileName;
				Log.i("MCServer", "outPath: " + outPath );
				File f = new File( outPath );
				
				f.getParentFile().mkdirs();
				f.createNewFile();
				OutputStream ostr = new FileOutputStream(f);
				
				byte[] buffer = new byte[1024];
		        int length;
		        while ((length = istr.read(buffer))>0)
		        {
		            ostr.write(buffer, 0, length);
		        }
		        ostr.flush();
		        ostr.close();
		        istr.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
    
    
    void InstallSinglePlugin( String path )
    {
		AssetManager am = mContext.getAssets();
		try {
			String[] getImages = am.list(BaseDirectory + "/" + path);
			for(String imgName : getImages)
			{
				Log.i("MCServer", path + "/" + imgName);
								
				InputStream istr = null;
				try
				{
					istr = am.open(BaseDirectory + "/" + path + "/" + imgName);
				} catch( java.io.FileNotFoundException e ) {
					Log.i("MCServer", "Could not open" + path + "/" + imgName );
					InstallSinglePlugin(path + "/" + imgName);
					continue;
				}
				
				String outPath = Environment.getExternalStorageDirectory().getPath() + "/mcserver/" + path + "/" + imgName;
				Log.i("MCServer", "outPath: " + outPath );
				File f = new File( outPath );
				
				f.getParentFile().mkdirs();
				f.createNewFile();
				OutputStream ostr = new FileOutputStream(f);
				
				byte[] buffer = new byte[1024];
		        int length;
		        while ((length = istr.read(buffer))>0)
		        {
		            ostr.write(buffer, 0, length);
		        }
		        ostr.flush();
		        ostr.close();
		        istr.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
}