AIEngineHelper.java 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. package com.edufound.reader.util;
  2. import android.content.Context;
  3. import android.os.Environment;
  4. import android.util.Log;
  5. import com.chivox.AIEngine;
  6. import org.json.JSONException;
  7. import org.json.JSONObject;
  8. import java.io.BufferedInputStream;
  9. import java.io.BufferedOutputStream;
  10. import java.io.BufferedReader;
  11. import java.io.File;
  12. import java.io.FileOutputStream;
  13. import java.io.FileReader;
  14. import java.io.FileWriter;
  15. import java.io.IOException;
  16. import java.io.InputStream;
  17. import java.io.OutputStream;
  18. import java.security.MessageDigest;
  19. import java.util.Arrays;
  20. import java.util.zip.ZipEntry;
  21. import java.util.zip.ZipInputStream;
  22. //import org.apache.http.HttpResponse;
  23. //import org.apache.http.NameValuePair;
  24. //import org.apache.http.client.HttpClient;
  25. //import org.apache.http.client.entity.UrlEncodedFormEntity;
  26. //import org.apache.http.client.methods.HttpPost;
  27. //import org.apache.http.impl.client.DefaultHttpClient;
  28. //import org.apache.http.message.BasicNameValuePair;
  29. //import org.apache.http.params.BasicHttpParams;
  30. //import org.apache.http.util.EntityUtils;
  31. public class AIEngineHelper {
  32. private static String TAG = "AIEngineHelper";
  33. private static int BUFFER_SIZE = 4096;
  34. private static String readFileAsString(File file) throws IOException {
  35. String line;
  36. StringBuffer sb = new StringBuffer();
  37. BufferedReader br = new BufferedReader(new FileReader(file));
  38. while ((line = br.readLine()) != null) {
  39. sb.append(line);
  40. }
  41. br.close();
  42. return sb.toString();
  43. }
  44. private static void writeFileAsString(File file, String str) throws IOException {
  45. FileWriter fw = new FileWriter(file);
  46. fw.write(str);
  47. fw.close();
  48. }
  49. private static void writeFileAsBytes(File file, byte [] bytes) throws IOException {
  50. FileOutputStream fstream = new FileOutputStream(file);
  51. BufferedOutputStream stream = new BufferedOutputStream(fstream);
  52. stream.write(bytes);
  53. stream.close();
  54. fstream.close();
  55. }
  56. private static void removeDirectory(File directory) {
  57. if (directory.isDirectory()) {
  58. File[] files = directory.listFiles();
  59. for (int i = 0; i < files.length; i++) {
  60. if (files[i].isDirectory()) {
  61. removeDirectory(files[i]);
  62. }
  63. files[i].delete();
  64. }
  65. directory.delete();
  66. }
  67. }
  68. /**
  69. * extract resource once, the resource should in zip formatting
  70. *
  71. * @param context
  72. * @param name
  73. * @return return resource directory contains resources for native aiengine cores on success, otherwise return null
  74. */
  75. public static String extractResourceOnce(Context context, String name, boolean unzip) {
  76. try {
  77. if (unzip) {
  78. String pureName = name.replaceAll("\\.[^.]*$", "");
  79. File filesDir = getFilesDir(context);
  80. File targetDir = new File(filesDir, pureName);
  81. String md5sum = md5sum(context.getAssets().open(name));
  82. File md5sumFile = new File(targetDir, ".md5sum");
  83. if (targetDir.isDirectory()) {
  84. if (md5sumFile.isFile()) {
  85. String md5sum2 = readFileAsString(md5sumFile);
  86. if (md5sum2.equals(md5sum)) {
  87. return targetDir.getAbsolutePath(); /* already extracted */
  88. }
  89. }
  90. removeDirectory(targetDir); /* remove old dirty resource */
  91. }
  92. unzip(context.getAssets().open(name), targetDir);
  93. writeFileAsString(md5sumFile, md5sum);
  94. return targetDir.getAbsolutePath();
  95. } else {
  96. File targetFile = new File(getFilesDir(context), name);
  97. copyInputStreamToFile(context.getAssets().open(name), targetFile);
  98. return targetFile.getAbsolutePath();
  99. }
  100. } catch (Exception e) {
  101. Log.e(TAG, "failed to extract resource", e);
  102. }
  103. return null;
  104. }
  105. /**
  106. * register device once
  107. * @param appKey
  108. * @param secretKey
  109. * @param userId
  110. * @return return serialNumber on success, otherwise return null
  111. */
  112. public static String registerDeviceOnce(Context context, String appKey, String secretKey, String userId) {
  113. File filesDir = getFilesDir(context);
  114. File serialNumberFile = new File(filesDir, "aiengine.serial");
  115. String serialNumber = "";
  116. String serialNumberInfo = "";
  117. if (serialNumberFile.isFile()) {
  118. try {
  119. serialNumber = readFileAsString(serialNumberFile);
  120. Log.d(TAG, "yes");
  121. return serialNumber;
  122. } catch (IOException e) {
  123. /* ignore */
  124. }
  125. }
  126. String sig = String.format("{\"appKey\":\"%s\",\"secretKey\":\"%s\",\"userId\":\"%s\"}", appKey,secretKey,userId);
  127. JSONObject sig_json = null;
  128. try {
  129. sig_json = new JSONObject(sig);
  130. } catch (JSONException e) {
  131. // TODO Auto-generated catch block
  132. e.printStackTrace();
  133. }
  134. byte cfg_b[] = Arrays.copyOf(sig_json.toString().getBytes(), 1024);
  135. int ret = AIEngine.aiengine_opt(0, 6, cfg_b, 1024);
  136. if (ret > 0) {
  137. serialNumberInfo = new String(cfg_b, 0, ret);
  138. } else {
  139. serialNumberInfo = new String(cfg_b);
  140. }
  141. try {
  142. serialNumber = (new JSONObject(serialNumberInfo)).getString("serialNumber");
  143. } catch (JSONException e1) {
  144. // TODO Auto-generated catch block
  145. e1.printStackTrace();
  146. return "";
  147. }
  148. if(serialNumber.length()==0){
  149. return "";
  150. }
  151. try {
  152. writeFileAsString(serialNumberFile, serialNumber);
  153. } catch (Exception e1) {
  154. /* ignore */
  155. }
  156. return serialNumber;
  157. }
  158. public static File getFilesDir(Context context) {
  159. File targetDir = null;
  160. if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
  161. // targetDir = context.getExternalFilesDir(null); // not support android 2.1
  162. targetDir = new File(Environment.getExternalStorageDirectory(), "Android/data/" + context.getApplicationInfo().packageName + "/files");
  163. if (!targetDir.exists()) {
  164. targetDir.mkdirs();
  165. }
  166. }
  167. if (targetDir == null || !targetDir.exists()) {
  168. targetDir = context.getFilesDir();
  169. }
  170. return targetDir;
  171. }
  172. private static void unzip(InputStream is, File targetDir)
  173. throws IOException {
  174. ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is,
  175. BUFFER_SIZE));
  176. ZipEntry ze;
  177. while ((ze = zis.getNextEntry()) != null) {
  178. if (ze.isDirectory()) {
  179. new File(targetDir, ze.getName()).mkdirs();
  180. } else {
  181. File file = new File(targetDir, ze.getName());
  182. File parentdir = file.getParentFile();
  183. if (parentdir != null && (!parentdir.exists())) {
  184. parentdir.mkdirs();
  185. }
  186. int pos;
  187. byte[] buf = new byte[BUFFER_SIZE];
  188. OutputStream bos = new FileOutputStream(file);
  189. while ((pos = zis.read(buf, 0, BUFFER_SIZE)) > 0) {
  190. bos.write(buf, 0, pos);
  191. }
  192. bos.flush();
  193. bos.close();
  194. Log.d(TAG, file.getAbsolutePath());
  195. }
  196. }
  197. zis.close();
  198. is.close();
  199. }
  200. private static void copyInputStreamToFile(InputStream is, File file)
  201. throws Exception {
  202. int bytes;
  203. byte[] buf = new byte[BUFFER_SIZE];
  204. FileOutputStream fos = new FileOutputStream(file);
  205. while ((bytes = is.read(buf, 0, BUFFER_SIZE)) > 0) {
  206. fos.write(buf, 0, bytes);
  207. }
  208. is.close();
  209. fos.close();
  210. };
  211. private static String sha1(String message) {
  212. try {
  213. MessageDigest md = MessageDigest.getInstance("SHA-1");
  214. md.update(message.getBytes(), 0, message.length());
  215. return bytes2hex(md.digest());
  216. } catch (Exception e) {
  217. /* ignore */
  218. }
  219. return null;
  220. }
  221. private static String bytes2hex(byte[] bytes) {
  222. StringBuffer sb = new StringBuffer(bytes.length * 2);
  223. for (int i = 0; i < bytes.length; i++) {
  224. int v = bytes[i] & 0xff;
  225. if (v < 16) {
  226. sb.append('0');
  227. }
  228. sb.append(Integer.toHexString(v));
  229. }
  230. return sb.toString();
  231. }
  232. private static String md5sum(InputStream is) {
  233. int bytes;
  234. byte buf[] = new byte[BUFFER_SIZE];
  235. try {
  236. MessageDigest md = MessageDigest.getInstance("MD5");
  237. while ((bytes = is.read(buf, 0, BUFFER_SIZE)) > 0) {
  238. md.update(buf, 0, bytes);
  239. }
  240. is.close();
  241. return bytes2hex(md.digest());
  242. } catch (Exception e) {
  243. /* ignore */
  244. }
  245. return null;
  246. }
  247. public static String getProvisionTmpFile(Context context)
  248. {
  249. File filesDir = getFilesDir(context);
  250. String str = filesDir.getAbsolutePath() + "/aiengine.provision.temp";
  251. Log.d(TAG, "provison tmp file path: " + str);
  252. return str;
  253. }
  254. }