浏览代码

增加上传下载RN插件

wuyong3 5 年之前
父节点
当前提交
4dca8cbf68

+ 11 - 0
ipu-plugin-basic/pom.xml

@ -28,6 +28,7 @@
28 28
	<properties>
29 29
		<scan-code>1.0</scan-code>
30 30
		<android-lite-http>1.0</android-lite-http>
31
		<react-native>0.52.2</react-native>
31 32
	</properties>
32 33
33 34
	<dependencies>
@ -77,5 +78,15 @@
77 78
			<artifactId>ipu-mobile-basic</artifactId>
78 79
			<version>${ipu}</version>
79 80
		</dependency>
81
		<dependency>
82
			<groupId>com.facebook.react</groupId>
83
			<artifactId>react-native-jar</artifactId>
84
			<version>${react-native}</version>
85
		</dependency>
86
		<dependency>
87
			<groupId>com.ai.ipu.mobile</groupId>
88
			<artifactId>ipu-mobile-rn</artifactId>
89
			<version>${ipu}</version>
90
		</dependency>
80 91
	</dependencies>
81 92
</project>

+ 473 - 0
ipu-plugin-basic/src/main/java/com/ai/ipu/mobile/commonfunc/MobileCameraFunc.java

@ -0,0 +1,473 @@
1
package com.ai.ipu.mobile.commonfunc;
2
3
import java.io.BufferedOutputStream;
4
import java.io.File;
5
import java.io.FileNotFoundException;
6
import java.io.FileOutputStream;
7
import java.io.IOException;
8
import java.text.SimpleDateFormat;
9
import java.util.Date;
10
11
12
import com.ai.ipu.basic.file.FileUtil;
13
import com.ai.ipu.basic.string.StringUtil;
14
import com.ai.ipu.mobile.app.IpuAppInfo;
15
import com.ai.ipu.mobile.frame.plugin.ComFunc;
16
import com.ai.ipu.mobile.frame.plugin.Plugin;
17
import com.ai.ipu.mobile.ui.HintUtil;
18
import com.ai.ipu.mobile.ui.image.MobileGraphics;
19
import com.ai.ipu.mobile.util.DirectionUtil;
20
import com.ai.ipu.mobile.util.IpuMobileUtility;
21
import com.ailk.common.data.IData;
22
import com.ailk.common.data.impl.DataMap;
23
24
import android.app.Activity;
25
import android.content.Intent;
26
import android.database.Cursor;
27
import android.graphics.Bitmap;
28
import android.graphics.BitmapFactory;
29
import android.graphics.Canvas;
30
import android.graphics.Color;
31
import android.graphics.Paint;
32
import android.graphics.Path;
33
import android.graphics.Rect;
34
import android.net.Uri;
35
import android.os.Bundle;
36
import android.provider.MediaStore;
37
import android.util.Log;
38
39
public class MobileCameraFunc extends ComFunc{
40
	
41
	private String TAG = getClass().getSimpleName();
42
43
	public MobileCameraFunc(Activity context, Plugin plugin, Object rnPlugin) {
44
		super(context, plugin, rnPlugin);
45
	}
46
	
47
	private static final int DEFAULT_COLOR = 0xffdcdcdc;
48
49
	public enum TYPE {
50
		BASE64_AND_PATH(2), //Base64编码和文件路径
51
		PATH(1), //文件路径
52
		BASE64(0);	//Base64编码
53
		private int type;
54
		private TYPE(int type) {
55
			this.type = type;
56
		}
57
		public int getType() {
58
			return this.type;
59
		}
60
	}
61
	
62
	
63
	private int quality = 80; // 压缩率,如果是0,表示不压缩
64
65
	private SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd-hhmmss");
66
	private String photoFullPath;
67
68
	private Function func;
69
	private enum Function {
70
		getPhoto, // 照相
71
		getPicture, // 获取相片
72
		scanQrCode, // 二维码
73
		createQrCode // 生成二维码
74
	}
75
76
	/**
77
	 * 从媒体库获取图片
78
	 * 类型0为Base64字符串,类型1为文件路径
79
	 */
80
	public void getPicture(int type) {
81
		this.func = Function.getPicture;
82
		/* 使用相册打开 */
83
		Intent intent = new Intent(Intent.ACTION_PICK,
84
				android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
85
86
		int requestType = type;
87
		startActivityForResult(intent, requestType);
88
	}
89
90
	/**
91
	 * 获拍得的照片
92
	 * 类型0时返回Base64字符串和文件路径
93
	 */
94
	public void getPhoto(int type) throws Exception {
95
		this.func = Function.getPhoto;
96
97
		String appName = IpuAppInfo.getAppPath();
98
		String photoName = appName + "-" + format.format(new Date()) + ".jpg";// 生成照片名称
99
		DirectionUtil util = DirectionUtil.getInstance(context);
100
		String photoDir = util.getImageDirection(true);
101
		File photoDirFile = new File(photoDir);
102
		if (!photoDirFile.exists()) {
103
			photoDirFile.mkdirs();
104
		}
105
		File photoFile = new File(FileUtil.connectFilePath(photoDir, photoName));
106
		photoFullPath = photoFile.getAbsolutePath();
107
		
108
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
109
		intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
110
		
111
		int requestType = type;
112
		startActivityForResult(intent, requestType);
113
	}
114
	
115
	public void transImageToBase64(String imagePath){
116
		Bitmap bitmap = null; 
117
		try {
118
			bitmap = getBitmapByImage(imagePath);
119
		} catch (Exception e) {
120
			HintUtil.alert(context, e.getMessage());
121
			return;
122
		}
123
		
124
		Bitmap base64Bitmap = MobileGraphics.compressImage(bitmap, 10, 30);
125
		String out = MobileGraphics.bitmapToString(base64Bitmap); //base64处理
126
		base64Bitmap.recycle();
127
		
128
		callback(out);
129
	}
130
	
131
	/**
132
	 * 精准压缩图片
133
	 * @param imagePath:图片路径;fileSize:图片大写;quality:图片质量
134
	 */
135
	public void compressImage(String imagePath,int fileSize,int quality){
136
		Bitmap bitmap = null; 
137
		try {
138
			bitmap = getBitmapByImage(imagePath);
139
		} catch (Exception e) {
140
			HintUtil.alert(context, e.getMessage());
141
			return;
142
		}
143
		
144
		Bitmap base64Bitmap = MobileGraphics.compressImage(bitmap, fileSize, quality);
145
		String out = MobileGraphics.bitmapToString(base64Bitmap); //base64处理
146
		base64Bitmap.recycle();
147
		
148
		callback(out);
149
	}
150
151
	public BitmapFactory.Options getBitmapOptions() {
152
		BitmapFactory.Options opts = new BitmapFactory.Options();
153
		opts.inJustDecodeBounds = true;// decodeFile并不分配空间
154
		opts.inTempStorage = new byte[32 * 1024];// 临时存储,将载入的资源载入到临时空间中
155
		return opts;
156
	}
157
	
158
	public Bitmap getBitmapByImage(String imagePath){
159
		BitmapFactory.Options opts = getBitmapOptions();
160
		BitmapFactory.decodeFile(imagePath, opts);
161
		opts.inSampleSize = MobileGraphics.computeSampleSize(opts, -1, 800 * 480);
162
		opts.inJustDecodeBounds = false;// 还原
163
		Bitmap bitmap = null;
164
		try {
165
			bitmap = BitmapFactory.decodeFile(imagePath, opts);
166
		} catch (OutOfMemoryError e) {
167
			IpuMobileUtility.error("文件过大,无法加载", e);
168
		}
169
		return bitmap;
170
	}
171
172
	/**
173
	 * 通过uri获取图片绝对路径
174
	 */
175
	@SuppressWarnings("deprecation")
176
	private String getPath(Uri uri) {
177
		String[] projection = {MediaStore.Images.Media.DATA};
178
		Cursor cursor = this.context.managedQuery(uri, projection, null, null, null);
179
		this.context.startManagingCursor(cursor);
180
		int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
181
		cursor.moveToFirst();
182
		String path = cursor.getString(column_index);
183
		//cursor.close(); //关闭会报错
184
		return path;
185
	}
186
187
188
	public void addImageWaterMarkForImage(String picPath,String mark,String p) throws Exception {
189
		if (p== null || !StringUtil.isDataMap(p)) {
190
			throw new IllegalArgumentException("没有DataMap参数");
191
		}
192
		DataMap dataMap = new DataMap(p);
193
	    double x = dataMap.getDouble("markX");
194
	    double y = dataMap.getDouble("markY");
195
		double width = dataMap.getDouble("width", 0.2);
196
		String resultPath = addWaterMark(picPath, mark, x, y, width);
197
	    	    
198
	    callback(resultPath);
199
	}
200
201
	public void addTextWaterMarkForImage(String picPath,String text,String p) throws Exception {
202
		String res = null;
203
		if (p== null || !StringUtil.isDataMap(p)) {
204
			throw new IllegalArgumentException("没有DataMap参数");
205
		}
206
		DataMap dataMap = new DataMap(p);
207
		double textSize = dataMap.getDouble("textSize", 0.05);
208
		String textColor = dataMap.getString("textColor");
209
		double angle = dataMap.getDouble("angle");
210
		double rowSpaceRatio, colSpaceRatio, markXRatio, markYRatio;
211
		boolean isRepeat = dataMap.getBoolean("isRepeat");
212
		if (isRepeat) {
213
			rowSpaceRatio = dataMap.getDouble("rowSpace", 0.2);
214
			colSpaceRatio = dataMap.getDouble("colSpace", 0.2);
215
			res = addText(picPath, text, textSize, textColor, angle, rowSpaceRatio, colSpaceRatio);
216
		} else {
217
			markXRatio = dataMap.getDouble("markX");
218
			markYRatio = dataMap.getDouble("markY");
219
			res = addText(picPath, text, markXRatio, markYRatio, textSize, textColor, angle);
220
		}
221
222
		callback(res);
223
	}
224
225
	/**
226
	 * 在指定位置添加一行文字水印
227
	 * @param picPath
228
	 * @param text
229
	 * @param markXRatio
230
	 * @param markYRatio
231
	 * @param textSizeRatio
232
	 * @param textColor
233
	 * @param angle
234
	 * @return
235
	 */
236
	private String addText(String picPath, String text, double markXRatio, double markYRatio, double textSizeRatio, String textColor, double angle) {
237
		String result;
238
		Bitmap bitmap = BitmapFactory.decodeFile(picPath);
239
		bitmap = bitmap.copy(bitmap.getConfig(), true);
240
		int picWidth = bitmap.getWidth();
241
		Canvas canvas = new Canvas(bitmap);
242
		Paint paint = new Paint();
243
		paint.setColor(textColor == null ? 0xffdcdcdc : Color.parseColor(textColor)); //默认灰色
244
		int textSize = (int) (picWidth * textSizeRatio);
245
		int x = (int) (markXRatio * picWidth);
246
		int y = (int) (markYRatio * bitmap.getHeight());
247
		paint.setTextSize(textSize); //图片宽度的20分之一作为字体大小
248
249
		// 用path确定文字位置和方向
250
		Path path = new Path();
251
		double radians = Math.toRadians(angle);
252
		x -= textSize * Math.sin(radians);
253
		y += textSize * Math.cos(radians);
254
		path.moveTo(x, y);
255
		int textLength = (int) paint.measureText(text);
256
		x += textLength;
257
		y += textLength * Math.tan(radians);
258
		path.lineTo(x, y);
259
260
		canvas.drawTextOnPath(text, path, 0, 0, paint);
261
		result = saveBmpFile(bitmap);
262
		return result;
263
	}
264
265
	/**
266
	 * 平铺模式添加文字水印
267
	 * @param picPath
268
	 * @param text
269
	 * @param textSizeRatio
270
	 * @param textColor
271
	 * @param angle
272
	 * @param rowSpaceRatio
273
	 * @param colSpaceRatio
274
	 * @return
275
	 */
276
	private String addText(String picPath, String text, double textSizeRatio, String textColor, double angle, double rowSpaceRatio, double colSpaceRatio) {
277
		String result;
278
		Bitmap bitmap = BitmapFactory.decodeFile(picPath);
279
		bitmap = bitmap.copy(bitmap.getConfig(), true);
280
		int picWidth = bitmap.getWidth();
281
		int picHeight = bitmap.getHeight();
282
		Canvas canvas = new Canvas(bitmap);
283
		Paint paint = new Paint();
284
		paint.setColor(textColor == null ? DEFAULT_COLOR : Color.parseColor(textColor)); //默认灰色
285
		int textSize = (int) (textSizeRatio * picWidth);
286
		paint.setTextSize(textSize);
287
		canvas.translate(picWidth / 2, picHeight / 2);
288
		canvas.rotate((float) angle);
289
290
		int textWidth = (int) paint.measureText(text);
291
		int l = Math.max(picHeight, picWidth) * 3 / 2;
292
		int colSpace = (int) (rowSpaceRatio * picWidth);
293
		int rowSpace = (int) (colSpaceRatio * picHeight);
294
		for (int x = -l/2; x<l/2; x+=colSpace+textWidth) {
295
			for(int y=-l/2;y<l/2;y+=rowSpace) {
296
				canvas.drawText(text, x, y, paint);
297
			}
298
		}
299
		result = saveBmpFile(bitmap);
300
		return result;
301
	}
302
303
	/**
304
    * @param path 原图片路径
305
    * @param waterPath 水印图片路径
306
    * @param x 水印图片左边位置,值为占整个图片的宽的比例
307
    * @param y 水印图片上边位置,值为占整个图片的高的比例
308
    * @param width 水印图片宽度,值为占整个图片的宽的比例
309
    * @return 加了水印的图片路径
310
    */
311
   private String addWaterMark(String path, String waterPath, double x, double y, double width) throws Exception {
312
       Bitmap bitmap1 = BitmapFactory.decodeFile(path);
313
       Bitmap bitmap2 = BitmapFactory.decodeFile(waterPath);
314
       bitmap1 = bitmap1.copy(bitmap1.getConfig(), true);
315
       Canvas canvas = new Canvas(bitmap1);
316
317
       Rect rect = buildRect(bitmap1, bitmap2, x, y, width);
318
       canvas.drawBitmap(bitmap2, null, rect, null);
319
320
       String res = saveBmpFile(bitmap1);
321
322
       return res;
323
   }
324
325
	/**
326
	 * 将bitmap保存到ipu应用的image目录,命名为“日期-mark.png”
327
	 * @param bitmap
328
	 * @return 文件路径,失败返回null
329
	 */
330
	String saveBmpFile(Bitmap bitmap) {
331
	   String fileName = format.format(new Date()) + "-mark.png";
332
	   File f = new File(DirectionUtil.getInstance(context).getImageDirection(true), fileName);
333
	   if (!f.getParentFile().exists()) {
334
		   f.getParentFile().mkdirs();
335
	   }
336
	   String res = f.getAbsolutePath();
337
	   BufferedOutputStream bos = null;
338
		FileOutputStream outputStream = null;
339
	   try {
340
		   outputStream = new FileOutputStream(f);
341
		   bos = new BufferedOutputStream(outputStream);
342
		   bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
343
	   } catch (FileNotFoundException e) {
344
		   Log.e(TAG, "addWaterMark: ", e);
345
		   res = null;
346
	   } finally {
347
		   if (bos != null) {
348
			   try {
349
				   bos.close();
350
			   } catch (IOException e) {
351
				   Log.e(TAG, "addWaterMark: ", e);
352
			   }
353
		   }
354
		   if (outputStream != null) {
355
			   try {
356
				   outputStream.close();
357
			   } catch (IOException e) {
358
				   Log.e(TAG, "addWaterMark: ", e);
359
			   }
360
		   }
361
	   }
362
363
	   return res;
364
   }
365
366
   private Rect buildRect(Bitmap pic, Bitmap mark, double xPercent, double yPercent, double wPercent) throws Exception {
367
       xPercent = fixIn1(xPercent);
368
       yPercent = fixIn1(yPercent);
369
       wPercent = fixIn1(wPercent);
370
       int w = pic.getWidth();
371
       int h = pic.getHeight();
372
       int l = (int) (w * xPercent);
373
       int t = (int) (h * yPercent);
374
       int r = (int) (w * wPercent + l);
375
       int b = (int) (w * wPercent * mark.getHeight() / mark.getWidth() + t);
376
377
       Rect rect = new Rect(l, t, r, b);
378
       return rect;
379
   }
380
381
   private double fixIn1(double v) {
382
       if (v > 1) v = 1;
383
       if (v < 0) v = 0;
384
       return v;
385
   }
386
387
	@Override
388
	public void callbackActivityResult(int requestCode, int resultCode, Intent intent) {
389
		if (func == Function.scanQrCode) {
390
			if (resultCode == Activity.RESULT_OK) {
391
				Bundle bundle = intent.getExtras();
392
				String scanResult = bundle.getString("CALLBACK_RESULT");
393
				callback(scanResult);
394
			}
395
		} else if (func.equals(Function.getPhoto)) {
396
			// 照相功能
397
			if (resultCode == Activity.RESULT_OK) {
398
				Bitmap bitmap = null; 
399
				try {
400
					bitmap = getBitmapByImage(photoFullPath); //核实照片文件是否已经生成???????
401
				} catch (Exception e) {
402
					HintUtil.alert(context, e.getMessage());
403
					return;
404
				}
405
				
406
				if (requestCode == TYPE.PATH.getType()) {
407
					//MobileGraphics.savePicToLocal(bitmap, photoFullPath); //保存压缩文件
408
					callback(photoFullPath);
409
				}else if(requestCode == TYPE.BASE64.getType()){
410
					bitmap = MobileGraphics.compressImage(bitmap, 50, quality);	//压缩到50k
411
					Bitmap base64Bitmap = MobileGraphics.compressImage(bitmap, 10, 30);	//quality=30?
412
					String out = MobileGraphics.bitmapToString(base64Bitmap); //base64缩略图
413
					base64Bitmap.recycle();
414
					callback(out);
415
				}else{
416
					//MobileGraphics.savePicToLocal(bitmap, photoFullPath); //保存压缩文件
417
					bitmap = MobileGraphics.compressImage(bitmap, 50, quality);	//压缩到50k
418
					Bitmap base64Bitmap = MobileGraphics.compressImage(bitmap, 10, 30);	//quality=30?
419
					String out = MobileGraphics.bitmapToString(base64Bitmap); //base64处理
420
					base64Bitmap.recycle();
421
					IData result = new DataMap();
422
					result.put("thumbnail", out); //缩略图
423
					result.put("path", photoFullPath); //路径
424
					callback(result.toString());
425
				}
426
				bitmap.recycle();
427
				photoFullPath = null;
428
			}
429
		} else if (func.equals(Function.getPicture)) {// 从媒体库中获取
430
			if (resultCode == Activity.RESULT_OK) {
431
				Uri uri = intent.getData();
432
				String picturePath = null;
433
				if (uri.toString().startsWith("file:")) {
434
					picturePath = uri.getPath();
435
				} else if (uri.toString().startsWith("content:")) {
436
					picturePath = getPath(uri);
437
				} else {
438
					HintUtil.alert(context,"请选择相册或者文件浏览器");
439
					return;
440
				}
441
442
				Bitmap bitmap = null; 
443
				try {
444
					bitmap = getBitmapByImage(picturePath);
445
				} catch (Exception e) {
446
					HintUtil.alert(context, e.getMessage());
447
					return;
448
				}
449
				
450
				if (requestCode == TYPE.PATH.getType()) {
451
					callback(picturePath);
452
				}else if(requestCode == TYPE.BASE64.getType()){
453
					bitmap = MobileGraphics.compressImage(bitmap, 50, quality);	//压缩到50k
454
					Bitmap base64Bitmap = MobileGraphics.compressImage(bitmap, 10, 30);
455
					String out = MobileGraphics.bitmapToString(base64Bitmap);//base64缩略图
456
					base64Bitmap.recycle();
457
					callback(out);
458
				}else{
459
					bitmap = MobileGraphics.compressImage(bitmap, 50, quality);	//压缩到50k
460
					Bitmap base64Bitmap = MobileGraphics.compressImage(bitmap, 10, 30);	//quality=30?
461
					String out = MobileGraphics.bitmapToString(base64Bitmap); //base64处理
462
					base64Bitmap.recycle();
463
					IData result = new DataMap();
464
					result.put("thumbnail", out); //缩略图
465
					result.put("path", picturePath); //路径
466
					callback(result.toString());
467
				}
468
				bitmap.recycle();
469
			}
470
		}
471
	}
472
473
}

+ 412 - 0
ipu-plugin-basic/src/main/java/com/ai/ipu/mobile/commonfunc/MobileNetworkFunc.java

@ -0,0 +1,412 @@
1
package com.ai.ipu.mobile.commonfunc;
2
3
import java.io.File;
4
import java.io.InputStream;
5
import java.util.HashMap;
6
import java.util.HashSet;
7
import java.util.Map;
8
9
import org.json.JSONArray;
10
11
import com.ai.ipu.basic.file.FileUtil;
12
import com.ai.ipu.basic.net.http.HttpTool;
13
import com.ai.ipu.basic.string.StringUtil;
14
import com.ai.ipu.basic.thread.IpuThread;
15
import com.ai.ipu.mobile.common.sms.listener.OnSmsReceiveListener;
16
import com.ai.ipu.mobile.common.sms.util.SmsTool;
17
import com.ai.ipu.mobile.frame.config.MobileConfig;
18
import com.ai.ipu.mobile.frame.config.ServerDataConfig;
19
import com.ai.ipu.mobile.frame.plugin.ComFunc;
20
import com.ai.ipu.mobile.frame.plugin.Plugin;
21
import com.ai.ipu.mobile.safe.MobileSecurity;
22
import com.ai.ipu.mobile.util.BizManager;
23
import com.ai.ipu.mobile.util.BusinessCache;
24
import com.ai.ipu.mobile.util.Constant;
25
import com.ai.ipu.mobile.util.DirectionUtil;
26
import com.ai.ipu.mobile.util.FuncConstant;
27
import com.ai.ipu.mobile.util.IpuMobileUtility;
28
import com.ai.ipu.mobile.util.Messages;
29
import com.ai.ipu.mobile.util.http.UnirestUtil;
30
import com.ailk.common.data.IData;
31
import com.ailk.common.data.impl.DataMap;
32
import com.litesuits.http.LiteHttpClient;
33
import com.litesuits.http.request.Request;
34
import com.litesuits.http.response.Response;
35
36
import android.app.Activity;
37
import android.content.Intent;
38
import android.net.Uri;
39
import android.os.AsyncTask;
40
41
public class MobileNetworkFunc extends ComFunc{
42
	private DirectionUtil directionUtil;
43
	private boolean hasSetSmsListener;
44
45
	public MobileNetworkFunc(Activity context, Plugin plugin, Object rnPlugin) {
46
		super(context, plugin, rnPlugin);
47
		directionUtil = DirectionUtil.getInstance(context);
48
	}
49
	
50
	public void setSmsListener(String telString) throws Exception {
51
		HashSet<String> telSet = null;
52
		if(!isNull(telString)){
53
			telSet = new HashSet<String>();
54
			if(StringUtil.isJSONArray(telString)) {
55
				JSONArray teles = new JSONArray(telString);
56
				for(int i=0; i <teles.length() ; i++){
57
					telSet.add(teles.getString(i));
58
				}
59
			} else {
60
				telSet.add(telString);
61
			}
62
		}
63
		
64
		final HashSet<String> _telSet = telSet;
65
		if (!hasSetSmsListener) {
66
			SmsTool.setSmsListener(context, new OnSmsReceiveListener() {
67
				@Override
68
				public boolean onSmsReceive(String content, String sender, long time) {
69
					if (_telSet == null || _telSet.contains(sender)) {// 没有滤号码或者存在过滤号码均处理
70
						IData resultData = new DataMap();
71
						resultData.put(FuncConstant.CONTENT, content);
72
						resultData.put(FuncConstant.SENDER, sender);
73
						resultData.put(FuncConstant.TIME, time);
74
						String result = resultData.toString();
75
						callback(result);
76
						hasSetSmsListener = false;
77
						return true;
78
					} else {
79
						return false;
80
					}
81
				}
82
			});
83
			hasSetSmsListener = true;
84
		}
85
	}
86
	
87
	public void httpRequest(String requestUrl, String encode) throws Exception {
88
		if (isNull(encode)) {
89
			encode = MobileConfig.getInstance().getEncode();
90
		}
91
		String result;
92
		try {
93
			result = httpRequest1(requestUrl, encode);
94
		} catch (Exception e) {
95
			result = "{\"X_RESULTCODE\":\"-1\",\"X_RESULTINFO\":\"" + e.getMessage() + "\"}";
96
		}
97
		callback(result);
98
	}
99
100
	public String httpRequest1(String requestUrl, String encode) throws Exception {
101
		MobileConfig config = MobileConfig.getInstance();
102
		// 预处理
103
		if (!requestUrl.startsWith(Constant.HTTP)) {
104
			if (!requestUrl.startsWith("/"))
105
				requestUrl = "/" + requestUrl;
106
			requestUrl = config.getRequestHost() + requestUrl;
107
		}
108
109
		requestUrl = HttpTool.urlEncode(requestUrl, encode);
110
		return HttpTool.httpRequest(requestUrl, null, Constant.HTTP_POST, encode);
111
	}
112
	
113
	public void httpGet(String requestUrl, String encode){
114
		if (isNull(encode)) {
115
			encode = MobileConfig.getInstance().getEncode();// UTF-8
116
		}
117
		String result;
118
119
		try {
120
			/* 方式1 */
121
			/*result = httpGet(requestUrl,encode);*/
122
			/* 方式2 */
123
			LiteHttpClient client = LiteHttpClient.getInstance(context);
124
			Response res = client.execute(new Request(requestUrl));
125
			result = res.getString();
126
		} catch (Exception e) {
127
			result = e.getMessage();
128
		}
129
		callback(result);
130
	}
131
132
	public String httpGet1(String requestUrl, String encode) throws Exception{
133
		MobileConfig config = MobileConfig.getInstance();
134
		/* 预处理 */
135
		if (!requestUrl.startsWith(Constant.HTTP)) {
136
			if (!requestUrl.startsWith("/"))
137
				requestUrl = "/" + requestUrl;
138
			requestUrl = config.getRequestHost() + requestUrl;
139
		}
140
141
		requestUrl = HttpTool.urlEncode(requestUrl, encode);
142
		return HttpTool.httpRequest(requestUrl, null, Constant.HTTP_GET, encode);
143
	}
144
	
145
	public void dataRequest(String dataAction,String data,String headers) throws Exception {
146
		String result = isNull(headers) ? dataRequest(dataAction, isNull(data) ? null : new DataMap(data)) :
147
			 dataRequest(dataAction, isNull(data) ? null : new DataMap(data),new DataMap(headers));
148
		callback(result);
149
	}
150
	
151
	public void dataRequestAsync(final String dataAction,final String data,final String headers) throws Exception {
152
        
153
        new Thread(new Runnable() {
154
            
155
            @Override
156
            public void run() {
157
                String result = null;
158
                try {
159
                    result = isNull(headers) ? dataRequest(dataAction, isNull(data) ? null : new DataMap(data)) :
160
                        dataRequest(dataAction, isNull(data) ? null : new DataMap(data),new DataMap(headers));
161
                } catch (Exception e) {
162
                    error(e.getMessage());
163
                }
164
               callback(result);
165
            }
166
        }).start();
167
	}
168
	
169
	public void dataRequestWithHost(String requestUrl,String dataAction,String data,String headers) throws Exception {
170
        String result = isNull(headers) ? dataRequestWithHost(requestUrl, dataAction, isNull(data) ? null : new DataMap(data)) :
171
        	dataRequestWithHost(requestUrl, dataAction, isNull(data) ? null : new DataMap(data), new DataMap(headers));
172
        callback(result);
173
    }
174
	
175
	/**
176
	 * @param dataAction
177
	 * @param param
178
	 * @param isMustEncrypt
179
	 *            是否一定加密传输
180
	 * @return
181
	 * @throws Exception
182
	 */
183
	public String dataRequest(String dataAction, IData param) throws Exception {
184
		return dataRequest(dataAction, param, null);
185
	}
186
	
187
	/**
188
	 * @param dataAction
189
	 * @param param
190
	 * @param isMustEncrypt
191
	 *            是否一定加密传输
192
	 * @return
193
	 * @throws Exception
194
	 */
195
	public String dataRequest(String dataAction, IData param,IData headers) throws Exception {
196
//		synchronized (dataAction) {
197
			String result = (String) BusinessCache.getInstance().get(dataAction);
198
			if (result != null) {
199
				BusinessCache.getInstance().remove(dataAction);
200
			} else {
201
				try {
202
				    result = (null == headers) ? requestBizData(dataAction, param) : requestBizData(dataAction, param, headers);
203
				} catch (Exception e) {
204
				    DataMap data = new DataMap();
205
                    data.put("X_RESULTCODE", -1);
206
                    data.put("X_RESULTINFO", e.getMessage());
207
                    result = data.toString();
208
                }
209
			}
210
			return result;
211
//		}
212
	}
213
	
214
	public String dataRequestWithHost(String requestUrl, String dataAction, IData param) throws Exception {
215
        return dataRequestWithHost(requestUrl, dataAction, param, null);
216
    }
217
	
218
	public String dataRequestWithHost(String requestUrl, String dataAction, IData param,IData headers) throws Exception {
219
//      synchronized (dataAction) {
220
          String result = (String) BusinessCache.getInstance().get(dataAction);
221
          if (result != null) {
222
              BusinessCache.getInstance().remove(dataAction);
223
          } else {
224
              try {
225
                  result = (null == headers) ? requestBizDataWithHost(requestUrl, dataAction, param) :
226
                  	requestBizDataWithHost(requestUrl, dataAction, param, headers);
227
              } catch (Exception e) {
228
                  DataMap data = new DataMap();
229
                  data.put("X_RESULTCODE", -1);
230
                  data.put("X_RESULTINFO", e.getMessage());
231
                  result = data.toString();
232
              }
233
          }
234
          return result;
235
//      }
236
	}
237
	
238
	/**
239
	 * 新增头字段参数
240
	 */
241
	private String requestBizData(String dataAction, IData param,IData headers) throws Exception {
242
		Map<String,String> postData = transPostData(dataAction, param);
243
		String dataUrl = HttpTool.toQueryStringWithEncode(postData);
244
		BizManager.recordReqUrl(MobileConfig.getInstance().getRequestUrl());
245
		String result = (null == headers) ? HttpTool.httpRequest(MobileConfig.getInstance().getRequestUrl(),
246
				dataUrl, Constant.HTTP_POST) : HttpTool.httpRequest(MobileConfig.getInstance().getRequestUrl(),
247
						dataUrl, Constant.HTTP_POST,headers);
248
		if (ServerDataConfig.isEncrypt(dataAction)) {
249
			result = MobileSecurity.responseDecrypt(result);
250
		}
251
		return result;
252
	}
253
	
254
	private String requestBizData(String dataAction, IData param) throws Exception {
255
		return requestBizData(dataAction, param, null);
256
	}
257
	
258
	private String requestBizDataWithHost(String requestUrl, String dataAction, IData param) throws Exception {
259
        return requestBizDataWithHost(requestUrl, dataAction, param, null);
260
    }
261
	
262
	private String requestBizDataWithHost(String requestUrl, String dataAction, IData param,IData headers) throws Exception{
263
        Map<String,String> postData = transPostData(dataAction, param);
264
        String dataUrl = HttpTool.toQueryStringWithEncode(postData);
265
        String result = (null == headers) ? HttpTool.httpRequest(requestUrl, dataUrl, Constant.HTTP_POST) : 
266
        	HttpTool.httpRequest(requestUrl, dataUrl, Constant.HTTP_POST, headers);
267
        if (ServerDataConfig.isEncrypt(dataAction)) {
268
            result = MobileSecurity.responseDecrypt(result);
269
        }
270
        return result;
271
	}
272
	
273
	public Map<String, String> transPostData(String dataAction, IData dataParam) throws Exception {
274
		Map<String, String> postData = new HashMap<String, String>();
275
		postData.put(Constant.Server.ACTION, dataAction);
276
		if (ServerDataConfig.isEncrypt(dataAction)) {
277
			MobileSecurity.init();
278
			/* 参数加密处理 */
279
			String key = MobileSecurity.getDesKey();
280
			postData.put(Constant.Server.KEY, key);
281
			
282
			if(dataParam!=null){
283
				String encryptData = MobileSecurity.requestEncrypt(dataParam.toString());
284
				postData.put(Constant.Server.DATA, encryptData);
285
			}
286
		} else {
287
			if (dataParam != null) {
288
				postData.put(Constant.Server.DATA, dataParam.toString());
289
			}
290
		}
291
		return postData;
292
	}
293
294
	public void storageDataByThread(final String dataAction, final IData param,
295
			final boolean isEncrypt, long waitoutTime) throws Exception {
296
		waitoutTime = (waitoutTime < 3 || waitoutTime > 10) ? 5 : waitoutTime;// 修正waitoutTime,确保在一定范围
297
		new IpuThread(dataAction, waitoutTime) {
298
			@Override
299
			protected void execute() throws Exception {
300
				String result = requestBizData(dataAction, param);
301
//				synchronized (dataAction) {
302
					BusinessCache.getInstance().put(dataAction, result);
303
//				}
304
			}
305
		}.start();
306
	}
307
	
308
	/**
309
	 * 打开浏览器
310
	 */
311
	public void openBrowser(String url) {
312
		Uri uri = Uri.parse(url);
313
		Intent intent = new Intent(Intent.ACTION_VIEW, uri);
314
		context.startActivity(intent);
315
	}
316
	
317
	@SuppressWarnings("unchecked")
318
	public void uploadWithServlet(final JSONArray filePaths, final String dataAction, IData dataParam) throws Exception {
319
		Map<String, String> postData = transPostData(dataAction, dataParam);
320
		new AsyncTask<Map<String, String>, Integer, String>() {
321
			@Override
322
			protected String doInBackground(Map<String, String>... args) {
323
				Map<String, String> postData = args[0];
324
				Map<String, Object> fileData = new HashMap<String, Object>();
325
				String result = null;
326
				try{
327
					String filePath = null;
328
					File file;
329
					for(int i=0;i<filePaths.length();i++){
330
						filePath = filePaths.getString(i);
331
						file = new File(filePath);
332
						if(!file.exists()){
333
							IpuMobileUtility.error(Messages.FILE_NOT_EXIST+":"+filePath);
334
						}
335
						fileData.put("UPLOAD_FILE"+i, file);//装载文件
336
					}
337
					fileData.put("UPLOAD_FILE_COUNT", filePaths.length());//装载文件数量
338
					
339
					String encode = MobileConfig.getInstance().getEncode();
340
					String dataUrl = HttpTool.urlEncode(HttpTool.toQueryString(postData), encode);
341
					String url = MobileConfig.getInstance().getRequestUrl() + "?" + dataUrl;
342
					result = UnirestUtil.uploadByPost(HttpTool.urlEscape(url).toString(), fileData);
343
					if (ServerDataConfig.isEncrypt(dataAction)) {
344
						result = MobileSecurity.responseDecrypt(result);
345
					}
346
				}catch(Exception e){
347
					error(e.getMessage());// 报错回调
348
					IpuMobileUtility.error(e);
349
				}
350
				return result;
351
			}
352
			
353
			@Override
354
			protected void onPostExecute(String result) {
355
				super.onPostExecute(result);
356
				if (result != null) {
357
					callback(result);// 正常回调
358
				}
359
			}
360
		}.execute(postData);
361
	}
362
	
363
	public void downloadWithServlet(final String _savePath, String dataAction, IData dataParam) throws Exception {
364
		Map<String, String> tempPostData = transPostData(dataAction, dataParam);
365
		final Map<String, Object> postData = new HashMap<String, Object>();
366
		postData.putAll(tempPostData);
367
		new AsyncTask<String, Integer, String>() {
368
			@Override
369
			protected String doInBackground(String... arg0) {
370
				String savePath = _savePath;
371
				try {
372
					InputStream in = UnirestUtil.downloadByPost(MobileConfig.getInstance().getRequestUrl(), postData);
373
					if (!savePath.startsWith(File.separator)) {
374
						savePath = directionUtil.getDirection(savePath, true);
375
					}
376
					File file = new File(savePath).getParentFile();
377
					if (!file.exists() && !file.mkdirs()) {
378
						IpuMobileUtility.error("创建下载文件夹失败!");
379
					}
380
381
					FileUtil.writeFile(in, savePath);
382
				} catch (Exception e) {
383
					error("[" + savePath + "]异常:" + e.getMessage());// 报错回调
384
				}
385
				return savePath;
386
			}
387
			
388
			@Override
389
			protected void onPostExecute(String savePath) {
390
				super.onPostExecute(savePath);
391
				if (savePath != null) {
392
					callback(savePath);// 正常回调
393
				}
394
			}
395
		}.execute();
396
	}
397
398
	public void uploadFile(String path) throws Exception {
399
		
400
	}
401
	
402
	@Override
403
	public void callbackActivityResult(int arg0, int arg1, Intent arg2) {
404
		
405
	}
406
	
407
	protected boolean isNull(String value)
408
	  {
409
	    return (value == null) || ("null".equals(value)) || ("".equals(value));
410
	  }
411
412
}

+ 33 - 0
ipu-plugin-basic/src/main/java/com/ai/ipu/mobile/rn/MobileRnCamera.java

@ -0,0 +1,33 @@
1
package com.ai.ipu.mobile.rn;
2
3
import com.ai.ipu.mobile.commonfunc.MobileCameraFunc;
4
import com.ai.ipu.mobile.rn.plugin.RnPlugin;
5
import com.facebook.react.bridge.ReactApplicationContext;
6
import com.facebook.react.bridge.ReadableArray;
7
8
import android.content.Intent;
9
10
public class MobileRnCamera extends RnPlugin{
11
	
12
	private MobileCameraFunc func;
13
14
	public MobileRnCamera(ReactApplicationContext reactContext) {
15
		super(reactContext);
16
		func = new MobileCameraFunc(getRnContext(), null, this);
17
	}
18
	
19
	/**
20
	 * 从媒体库获取图片
21
	 * 类型0为Base64字符串,类型1为文件路径
22
	 */
23
	public void getPicture(ReadableArray param){
24
		int type = param.getInt(0);
25
		func.getPicture(type);
26
	}
27
	
28
	@Override
29
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
30
		func.callbackActivityResult(requestCode, resultCode, intent);
31
	}
32
33
}

+ 42 - 0
ipu-plugin-basic/src/main/java/com/ai/ipu/mobile/rn/MobileRnNetWork.java

@ -0,0 +1,42 @@
1
package com.ai.ipu.mobile.rn;
2
3
import org.json.JSONArray;
4
5
import com.ai.ipu.mobile.commonfunc.MobileNetworkFunc;
6
import com.ai.ipu.mobile.rn.plugin.RnPlugin;
7
import com.ailk.common.data.IData;
8
import com.ailk.common.data.impl.DataMap;
9
import com.facebook.react.bridge.ReactApplicationContext;
10
import com.facebook.react.bridge.ReadableArray;
11
12
13
public class MobileRnNetWork extends RnPlugin{
14
	
15
	private MobileNetworkFunc func;
16
17
	public MobileRnNetWork(ReactApplicationContext reactContext) {
18
		super(reactContext);
19
		func = new MobileNetworkFunc(getRnContext(), null, this);
20
	}
21
	
22
	public void uploadWithServlet(ReadableArray param) throws Exception {
23
		ReadableArray filePaths = param.getArray(0);
24
		JSONArray array = new JSONArray(filePaths.toArrayList());
25
		String dataAction = param.getString(1);
26
		IData dataParam = isNull(param.getString(2))?new DataMap():new DataMap(param.getString(2));
27
		func.uploadWithServlet(array, dataAction, dataParam);
28
	}
29
	
30
	public void downloadWithServlet(ReadableArray param) throws Exception {
31
		String savePath = param.getString(0);
32
		String dataAction = param.getString(1);
33
		IData dataParam = param.getString(2) == null ? new DataMap() : new DataMap(param.getString(2));
34
		func.downloadWithServlet(savePath, dataAction, dataParam);
35
	}
36
	
37
	public void uploadFile(ReadableArray param) throws Exception {
38
		String path = param.getString(0);
39
		func.uploadFile(path);
40
	}
41
42
}