summaryrefslogtreecommitdiff
path: root/src/com/lc8n/blauploader/FileShare.java
blob: f03e37f16fe1ec3611bf80870ec134d1210c759f (plain)
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
package com.lc8n.blauploader;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Point;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class FileShare extends Activity {
	private EditText text;
	private float fileSize;
	private Handler pbHandle = null;
	private ProgressDialog progressDialog;
	private ProgressDialog preparing;
	private String fileName; 
	private Thread thread;
	private AlertDialog alert;
	private File file;
	private File blaFile;
	private ImageView thumbView;
	private int imgRotate = 0;

	public void onCreate(Bundle savedInstanceState)
	{
		
        super.onCreate(savedInstanceState);
        setContentView(R.layout.share);
        
        //Temp files are stored in this folder
        final File blaDirectory = new File("/sdcard/blaupload");
        blaDirectory.mkdirs();
        
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        String action = intent.getAction();
        
        //Set up filename input text box
        text = (EditText) findViewById(R.id.filename);
        text.requestFocus();
        ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE))  
        .showSoftInput(text, 0);  

        //Set up alert box for any FTP error messages
        alert = new AlertDialog.Builder(this).create();
        alert.setTitle("FTP Response");
        alert.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					alert.dismiss();
					
				}
			});
 
        //Set up progress dialog which will show upload progress
        progressDialog = new ProgressDialog(this);
		
		progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		progressDialog.setMessage("Blauploading...");
		progressDialog.setCancelable(true);
		progressDialog.setProgress(0);
		
		
		progressDialog.setButton(AlertDialog.BUTTON_NEGATIVE, getText(R.string.cancel), new DialogInterface.OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
				// Cancel the upload!
				progressDialog.dismiss();
				thread.interrupt();
				
				
			}
		});

		//Set up preparing dialog which will be shown when connecting to FTP
		preparing = new ProgressDialog(this);
		preparing.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		preparing.setMessage("Preparing to Blaupload...");
		preparing.setCancelable(true);
		preparing.setButton(AlertDialog.BUTTON_NEGATIVE, getText(R.string.cancel), new DialogInterface.OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
				// Cancel the upload!
				progressDialog.dismiss();
				thread.interrupt();

			}
		});
		

		//Handles responses from the FTP thread
		pbHandle = new Handler(){
		
        @Override					
		public void handleMessage(Message msg) {
		
        	//Get the current progress (file size completed in bytes)
			long progress = msg.getData().getLong("progress_update");
			float percent = (progress/fileSize)*100.0f;
			Integer intProgress = Math.round(percent);
			
			int kB = Math.round(progress / 1024);
			
			//TODO: Make this not terrible
			//Checks for filesize - 10kB because that's the last guaranteed response
			//But there might be more, which would result in multiple SMSs
			//Need a nicer way of cleaning up when it's done
			if(intProgress==100 || progress>(fileSize-10240)) {
				SmsManager sms = SmsManager.getDefault();
				sms.sendTextMessage("07927278978", null, "New image blauploaded: http://www.blaupload.co.uk/"+fileName,null, null);
				blaFile.delete();
				progressDialog.dismiss();
			}
			else {
				//Really not sure why this is in an else
				//Close the prepare dialog and start the progress dialog 
				preparing.dismiss();
				progressDialog.show();
				progressDialog.setProgress(kB);
			}
			
			int code = msg.getData().getInt("response");
			
			//Handle FTP response codes
			switch (code) {
			case 0:
			break;
			case 600:
				alert.setMessage("File Already Exists! Please Rename");
				alert.show();
				progressDialog.dismiss();
				thread.interrupt();
				break;
			case 226:
				//This is the response code for complete,  but we usually don't receive it
				//TODO: Make sure we receive it
				//SmsManager sms = SmsManager.getDefault();
				//sms.sendTextMessage("07927278978", null, "New image blauploaded: http://www.blaupload.co.uk/"+fileName,null, null);
				progressDialog.dismiss();
				break;
			case 800:
				alert.setMessage("Unable To Connect To Server!");
				alert.show();
				progressDialog.dismiss();
				break;
			case 801:
				alert.setMessage("Unable To Log In!");
				alert.show();
				progressDialog.dismiss();
				break;
			case 804:
				alert.setMessage("Unable To Get File List!");
				alert.show();
				progressDialog.dismiss();
				break;
			case 805:
				alert.setMessage("Unable To Get Upload File!");
				alert.show();
				progressDialog.dismiss();
				break;
			case 806:
				alert.setMessage("FTP Server Did Not Respond!");
				alert.show();
				progressDialog.dismiss();
				break;
			case 807:
				alert.setMessage("Unable To Log Out!");
				alert.show();
				progressDialog.dismiss();
				break;
			default:
				alert.setMessage("Response Code: "+code);
				alert.show();
				progressDialog.dismiss();
				break;
				
			}
		}
		};
        
		//Handler for "Upload" button
		//This is where the magic happens
        final Button button = (Button) findViewById(R.id.uploadfile);
        button.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {

				//Show the preparing dialog while this is all happening
				//TODO: There is lag between pressing upload and this happening. Why?
        		preparing.show();
				
        		//Check box for resizing/reducing quality of image
        		CheckBox checkBox = (CheckBox)findViewById(R.id.resize);

        		boolean resizeImage = checkBox.isChecked();
				fileName = text.getText().toString();
				
				blaFile = new File(blaDirectory+"/"+fileName);
				
				//Perform any image manipulation now (currently rotate and quality)
	        	if (imgRotate != 0 || resizeImage) {

	        		try {
						rotateBitmap(file, blaFile, imgRotate, 80);

					} catch (FileNotFoundException e) {
						Log.e("blauploader", "File not found when rotating");
						e.printStackTrace();
					} catch (IOException e) {
						Log.e("blauploader", "IOException when rotating");
						e.printStackTrace();
					}
	        	} else {
	        		try {
	        			//Copy the file to our temp dir so we don't break the gallery by renaming
	        			//Only do this if we're not using the rotate function, as that does it anyway
	        			//TODO: Find a better way to handle this, allow renaming of existing file
						copyFile(file, blaFile);
					} catch (IOException e) {
						Log.e("blauploader", "IOException when copying");
						e.printStackTrace();
					}
	        	}
				
	        	//Set the filesize again in case it was changed above
				fileSize = blaFile.length();
				
				//Start the upload
                FileUpload uploader = new FileUpload(blaFile, pbHandle);
        		thread = new Thread(uploader);
        		thread.start();
        		progressDialog.setMax(Math.round(fileSize/1024));


			}
		});
        
        //Rotate button handlers
        final Button rLeft = (Button) findViewById(R.id.rotateleft);
        rLeft.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				
				//Rotate the thumbnail on the screen
				RotateAnimation rotateAnimation = new RotateAnimation(imgRotate, imgRotate-90,
						Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
				rotateAnimation.setInterpolator(new LinearInterpolator());
				rotateAnimation.setDuration(100);
				rotateAnimation.setFillAfter(true);
				thumbView.startAnimation(rotateAnimation);
				
				//Just keep track of the total rotate, we'll do the rotating of the actual image later
				if(imgRotate == -270) {
					imgRotate = 0;
				} else {
					imgRotate -= 90;
				}

			}
        });
        
        final Button rRight = (Button) findViewById(R.id.rotateright);
        rRight.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {

				//Rotate the thumbnail on the screen
				RotateAnimation rotateAnimation = new RotateAnimation(imgRotate, imgRotate + 90,
						Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
				rotateAnimation.setInterpolator(new LinearInterpolator());
				rotateAnimation.setDuration(100);
				rotateAnimation.setFillAfter(true);
				thumbView.startAnimation(rotateAnimation);
				
				//Just keep track of the total rotate, we'll do the rotating of the actual image later
				if (imgRotate == 270) {
					imgRotate = 0;
				} else {
					imgRotate += 90;
				}

			}});
        
        // if this is from the share menu
        //TODO: Actually we want to do this for any image regardless of where it came from
        if (Intent.ACTION_SEND.equals(action))
        {
            if (extras.containsKey(Intent.EXTRA_STREAM))
            {
                try
                {
                    // Get resource path from intent callee
                    Uri uri = (Uri) extras.getParcelable(Intent.EXTRA_STREAM);
                    // Query gallery for camera picture via
                    // Android ContentResolver interface
                    ContentResolver cr = getContentResolver();
                    
                    String[] projection = { MediaStore.MediaColumns.DISPLAY_NAME, MediaStore.MediaColumns.MIME_TYPE, MediaStore.MediaColumns.SIZE, MediaStore.MediaColumns.DATA, MediaStore.MediaColumns.WIDTH, MediaStore.MediaColumns.HEIGHT};
                    Cursor cur = cr.query(uri, projection, null, null, null);
                    cur.moveToFirst();
                    
                	fileName = cur.getString(3);
                	fileSize = cur.getLong(2);
                	int srcWidth = cur.getInt(4);
                	int srcHeight = cur.getInt(5);

                    cur.close();
                    String[] fileParts = fileName.split("/");
                    for (int i = 0; i < fileParts.length; i++) {
                    	System.out.println(fileParts[i]);
                    }
                    text.setText(fileParts[fileParts.length-1]);
                    text.setSelection(0,fileParts[fileParts.length-1].indexOf("."));
                    file = new File(fileName);
                    
                    //Get the screen size, so we can scale the thumbnail
                    Display display = getWindowManager().getDefaultDisplay();
                    int dspWidth = 0;
                    int dspHeight = 0;
                    
                    //getWidth/Height are deprecated in 13, getSize is not supported pre-13
                    if(android.os.Build.VERSION.SDK_INT >= 13) {
                    	Point size = new Point();
                    	display.getSize(size);
                    	dspWidth = size.x - 20;
                    	dspHeight = size.y - 20;
                    } else {
                    	dspWidth = display.getWidth();
                    	dspHeight = display.getHeight();
                    }
                    
                    float ratio = 0;
                    
                    //Scale the thumbnail so neither dimension is bigger than the screen width
                    if(srcWidth > srcHeight) {
                    	ratio =  (float)dspWidth / (float)srcWidth;
                    	dspHeight = Math.round(srcHeight * ratio);
                    } else {
                    	ratio = (float)dspWidth / (float)srcHeight;
                    	dspHeight = dspWidth;
                    	dspWidth = Math.round(srcWidth * ratio);
                    }
                    
                    //Get the thumbnail from the ether
                    Bitmap sourceImage= BitmapFactory.decodeFile(fileName);
                    Bitmap thumbnail = ThumbnailUtils.extractThumbnail(sourceImage, dspWidth, dspHeight);

                    thumbView = (ImageView)findViewById(R.id.thumbnail);
                    thumbView.setImageBitmap(thumbnail);

                    return;
                } catch (Exception e)
                {
                        Log.e(this.getClass().getName(), e.toString());
                }

            //TODO: I guess this was supposed to be some way to handle sharing text
            //That should probably be in the texting screen which I lost
            } else if (extras.containsKey(Intent.EXTRA_TEXT))
            {
                    return;
            }
        }
	}
	
	//Code from http://bricolsoftconsulting.com/2012/12/07/handling-large-images-on-android
	private boolean rotateBitmap(File inFile, File outFile, int angle, int quality)
			throws FileNotFoundException, IOException
	{
		

	    //TODO: Faster way for ICS+, uses OpenGL
		//See package com.android.gallery3d.photoeditor.RendererUtils from AOSP/CM gallery to create a GL texture
		/*if(android.os.Build.VERSION.SDK_INT >= 14) {
			Bitmap bitmap = BitmapFactory.decodeFile(inFile.getAbsolutePath());

			Texture texture = RendererUtils.
		    EffectContext context = EffectContext.createWithCurrentGlContext();
			Effect rotate = context.getFactory().createEffect(EffectFactory.EFFECT_ROTATE);
	        rotate.setParameter("angle", (int) imgRotate);
		}*/
		
	    // Declare
	    FileInputStream inStream = null;
	    FileOutputStream outStream = null;

	    // Create options
	    BitmapFactory.Options options = new BitmapFactory.Options();

	    // Create transform matrix
	    Matrix matrix = new Matrix();
	    matrix.postRotate(angle);

	    // Increment inSampleSize progressively to reduce image resolution and size. If
	    // the program is properly managing memory, and you don't have other large images
	    // loaded in memory, this loop will generally not need to go through more than 3
	    // iterations. To be safe though, we stop looping after a certain amount of tries
	    // to avoid infinite loops
	    for (options.inSampleSize = 1; options.inSampleSize <= 32; options.inSampleSize++)
	    {
	        try
	        {
	            // Load the bitmap from file
	            inStream = new FileInputStream(inFile);
	            Bitmap originalBitmap = BitmapFactory.decodeStream(inStream, null, options);

	            // Rotate the bitmap
	            Bitmap rotatedBitmap = Bitmap.createBitmap(originalBitmap, 0, 0, originalBitmap.getWidth(), originalBitmap.getHeight(), matrix, true);

	            // Save the rotated bitmap
	            outStream = new FileOutputStream(outFile);

	            rotatedBitmap.compress(CompressFormat.JPEG, quality, outStream);
	            outStream.close();

	            // Recycle the bitmaps to immediately free memory
	            originalBitmap.recycle();
	            originalBitmap = null;
	            rotatedBitmap.recycle();
	            rotatedBitmap = null;

	            // Return
	            return true;
	        }
	        catch (OutOfMemoryError e)
	        {
	            // If an OutOfMemoryError occurred, we continue with for loop and next inSampleSize value
	        }
	        finally
	        {
	            // Clean-up if we failed on save
	            if (outStream != null)
	            {
	                try
	                {
	                    outStream.close();
	                }
	                catch (IOException e)
	                {
	                }
	            }
	        }
	    }
	    
	    

	    // Failed
	    return false;
	}
	
	//Copies a file from the source to dhe destination
	//Currently used to create a temporary copy to upload
    public static void copyFile(File source, File destination) throws IOException {
    	FileInputStream input = new FileInputStream(source);
        OutputStream output = null;
        
        //Read the input file into a buffer, and write it out to the new file
        try {
            output = new FileOutputStream(destination);
            byte[] buffer = new byte[1024];
            int bytesRead = input.read(buffer);
            while (bytesRead >= 0) {
                output.write(buffer, 0, bytesRead);
                bytesRead = input.read(buffer);
            }
        } catch (Exception e) {
            Log.e("blauploader", "Exception in copyFile");
            e.printStackTrace();
        } finally {
            input.close();
            output.close();
        }
        input = null;
        output = null;
    }
	

}