AssetUtil.java 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. /*
  2. * Apache 2.0 License
  3. *
  4. * Copyright (c) Sebastian Katzer 2017
  5. *
  6. * This file contains Original Code and/or Modifications of Original Code
  7. * as defined in and that are subject to the Apache License
  8. * Version 2.0 (the 'License'). You may not use this file except in
  9. * compliance with the License. Please obtain a copy of the License at
  10. * http://opensource.org/licenses/Apache-2.0/ and read it before using this
  11. * file.
  12. *
  13. * The Original Code and all software distributed under the License are
  14. * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
  15. * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
  16. * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
  17. * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
  18. * Please see the License for the specific language governing rights and
  19. * limitations under the License.
  20. */
  21. package de.appplant.cordova.plugin.notification.util;
  22. import android.content.ContentResolver;
  23. import android.content.Context;
  24. import android.content.res.AssetManager;
  25. import android.content.res.Resources;
  26. import android.graphics.Bitmap;
  27. import android.graphics.BitmapFactory;
  28. import android.net.Uri;
  29. import android.os.StrictMode;
  30. import android.util.Log;
  31. import java.io.File;
  32. import java.io.FileNotFoundException;
  33. import java.io.FileOutputStream;
  34. import java.io.IOException;
  35. import java.io.InputStream;
  36. import java.io.OutputStream;
  37. import java.net.HttpURLConnection;
  38. import java.net.MalformedURLException;
  39. import java.net.URL;
  40. import java.util.UUID;
  41. /**
  42. * Util class to map unified asset URIs to native URIs. URIs like file:///
  43. * map to absolute paths while file:// point relatively to the www folder
  44. * within the asset resources. And res:// means a resource from the native
  45. * res folder. Remote assets are accessible via http:// for example.
  46. */
  47. public final class AssetUtil {
  48. // Name of the storage folder
  49. private static final String STORAGE_FOLDER = "/localnotification";
  50. // Ref to the context passed through the constructor to access the
  51. // resources and app directory.
  52. private final Context context;
  53. /**
  54. * Constructor
  55. *
  56. * @param context Application context.
  57. */
  58. private AssetUtil(Context context) {
  59. this.context = context;
  60. }
  61. /**
  62. * Static method to retrieve class instance.
  63. *
  64. * @param context Application context.
  65. */
  66. public static AssetUtil getInstance(Context context) {
  67. return new AssetUtil(context);
  68. }
  69. /**
  70. * The URI for a path.
  71. *
  72. * @param path The given path.
  73. */
  74. public Uri parse (String path) {
  75. if (path == null || path.isEmpty()) {
  76. return Uri.EMPTY;
  77. } else if (path.startsWith("res:")) {
  78. return getUriForResourcePath(path);
  79. } else if (path.startsWith("file:///")) {
  80. return getUriFromPath(path);
  81. } else if (path.startsWith("file://")) {
  82. return getUriFromAsset(path);
  83. } else if (path.startsWith("http")){
  84. return getUriFromRemote(path);
  85. }
  86. return Uri.EMPTY;
  87. }
  88. /**
  89. * URI for a file.
  90. *
  91. * @param path Absolute path like file:///...
  92. *
  93. * @return URI pointing to the given path.
  94. */
  95. private Uri getUriFromPath(String path) {
  96. String absPath = path.replaceFirst("file://", "");
  97. File file = new File(absPath);
  98. if (!file.exists()) {
  99. Log.e("Asset", "File not found: " + file.getAbsolutePath());
  100. return Uri.EMPTY;
  101. }
  102. return Uri.fromFile(file);
  103. }
  104. /**
  105. * URI for an asset.
  106. *
  107. * @param path Asset path like file://...
  108. *
  109. * @return URI pointing to the given path.
  110. */
  111. private Uri getUriFromAsset(String path) {
  112. String resPath = path.replaceFirst("file:/", "www");
  113. String fileName = resPath.substring(resPath.lastIndexOf('/') + 1);
  114. File file = getTmpFile(fileName);
  115. if (file == null) {
  116. Log.e("Asset", "Missing external cache dir");
  117. return Uri.EMPTY;
  118. }
  119. try {
  120. AssetManager assets = context.getAssets();
  121. FileOutputStream outStream = new FileOutputStream(file);
  122. InputStream inputStream = assets.open(resPath);
  123. copyFile(inputStream, outStream);
  124. outStream.flush();
  125. outStream.close();
  126. return Uri.fromFile(file);
  127. } catch (Exception e) {
  128. Log.e("Asset", "File not found: assets/" + resPath);
  129. e.printStackTrace();
  130. }
  131. return Uri.EMPTY;
  132. }
  133. /**
  134. * The URI for a resource.
  135. *
  136. * @param path The given relative path.
  137. *
  138. * @return URI pointing to the given path.
  139. */
  140. private Uri getUriForResourcePath(String path) {
  141. Resources res = context.getResources();
  142. String resPath = path.replaceFirst("res://", "");
  143. int resId = getResId(resPath);
  144. if (resId == 0) {
  145. Log.e("Asset", "File not found: " + resPath);
  146. return Uri.EMPTY;
  147. }
  148. return new Uri.Builder()
  149. .scheme(ContentResolver.SCHEME_ANDROID_RESOURCE)
  150. .authority(res.getResourcePackageName(resId))
  151. .appendPath(res.getResourceTypeName(resId))
  152. .appendPath(res.getResourceEntryName(resId))
  153. .build();
  154. }
  155. /**
  156. * Uri from remote located content.
  157. *
  158. * @param path Remote address.
  159. *
  160. * @return Uri of the downloaded file.
  161. */
  162. private Uri getUriFromRemote(String path) {
  163. File file = getTmpFile();
  164. if (file == null) {
  165. Log.e("Asset", "Missing external cache dir");
  166. return Uri.EMPTY;
  167. }
  168. try {
  169. URL url = new URL(path);
  170. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  171. StrictMode.ThreadPolicy policy =
  172. new StrictMode.ThreadPolicy.Builder().permitAll().build();
  173. StrictMode.setThreadPolicy(policy);
  174. connection.setRequestProperty("Connection", "close");
  175. connection.setConnectTimeout(5000);
  176. connection.connect();
  177. InputStream input = connection.getInputStream();
  178. FileOutputStream outStream = new FileOutputStream(file);
  179. copyFile(input, outStream);
  180. outStream.flush();
  181. outStream.close();
  182. return Uri.fromFile(file);
  183. } catch (MalformedURLException e) {
  184. Log.e("Asset", "Incorrect URL");
  185. e.printStackTrace();
  186. } catch (FileNotFoundException e) {
  187. Log.e("Asset", "Failed to create new File from HTTP Content");
  188. e.printStackTrace();
  189. } catch (IOException e) {
  190. Log.e("Asset", "No Input can be created from http Stream");
  191. e.printStackTrace();
  192. }
  193. return Uri.EMPTY;
  194. }
  195. /**
  196. * Copy content from input stream into output stream.
  197. *
  198. * @param in The input stream.
  199. * @param out The output stream.
  200. */
  201. private void copyFile(InputStream in, OutputStream out) throws IOException {
  202. byte[] buffer = new byte[1024];
  203. int read;
  204. while ((read = in.read(buffer)) != -1) {
  205. out.write(buffer, 0, read);
  206. }
  207. }
  208. /**
  209. * Resource ID for drawable.
  210. *
  211. * @param resPath Resource path as string.
  212. *
  213. * @return The resource ID or 0 if not found.
  214. */
  215. public int getResId(String resPath) {
  216. int resId = getResId(context.getResources(), resPath);
  217. if (resId == 0) {
  218. resId = getResId(Resources.getSystem(), resPath);
  219. }
  220. return resId;
  221. }
  222. /**
  223. * Resource ID for drawable.
  224. *
  225. * @param res The resources where to look for.
  226. * @param resPath The name of the resource.
  227. *
  228. * @return The resource ID or 0 if not found.
  229. */
  230. private int getResId(Resources res, String resPath) {
  231. String pkgName = getPkgName(res);
  232. String resName = getBaseName(resPath);
  233. int resId;
  234. resId = res.getIdentifier(resName, "mipmap", pkgName);
  235. if (resId == 0) {
  236. resId = res.getIdentifier(resName, "drawable", pkgName);
  237. }
  238. return resId;
  239. }
  240. /**
  241. * Convert URI to Bitmap.
  242. *
  243. * @param uri Internal image URI
  244. */
  245. public Bitmap getIconFromUri(Uri uri) throws IOException {
  246. InputStream input = context.getContentResolver().openInputStream(uri);
  247. return BitmapFactory.decodeStream(input);
  248. }
  249. /**
  250. * Extract name of drawable resource from path.
  251. *
  252. * @param resPath Resource path as string.
  253. */
  254. private String getBaseName (String resPath) {
  255. String drawable = resPath;
  256. if (drawable.contains("/")) {
  257. drawable = drawable.substring(drawable.lastIndexOf('/') + 1);
  258. }
  259. if (resPath.contains(".")) {
  260. drawable = drawable.substring(0, drawable.lastIndexOf('.'));
  261. }
  262. return drawable;
  263. }
  264. /**
  265. * Returns a file located under the external cache dir of that app.
  266. *
  267. * @return File with a random UUID name.
  268. */
  269. private File getTmpFile () {
  270. // If random UUID is not be enough see
  271. // https://github.com/LukePulverenti/cordova-plugin-local-notifications/blob/267170db14044cbeff6f4c3c62d9b766b7a1dd62/src/android/notification/AssetUtil.java#L255
  272. return getTmpFile(UUID.randomUUID().toString());
  273. }
  274. /**
  275. * Returns a file located under the external cache dir of that app.
  276. *
  277. * @param name The name of the file.
  278. *
  279. * @return File with the provided name.
  280. */
  281. private File getTmpFile (String name) {
  282. File dir = context.getExternalCacheDir();
  283. if (dir == null) {
  284. Log.e("Asset", "Missing external cache dir");
  285. return null;
  286. }
  287. String storage = dir.toString() + STORAGE_FOLDER;
  288. //noinspection ResultOfMethodCallIgnored
  289. new File(storage).mkdir();
  290. return new File(storage, name);
  291. }
  292. /**
  293. * Package name specified by the resource bundle.
  294. */
  295. private String getPkgName (Resources res) {
  296. return res == Resources.getSystem() ? "android" : context.getPackageName();
  297. }
  298. }