ImageDeepDetector.java 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103
  1. package com.datarecovery.master.utils;
  2. import static android.content.Context.POWER_SERVICE;
  3. import android.content.Context;
  4. import android.net.Uri;
  5. import android.os.CancellationSignal;
  6. import android.os.PowerManager;
  7. import android.text.TextUtils;
  8. import com.atmob.common.crypto.CryptoUtils;
  9. import com.datarecovery.master.utils.xfile.XFile;
  10. import com.datarecovery.master.utils.xfile.XFileSearch;
  11. import com.datarecovery.master.utils.xfile.XPathFile;
  12. import org.reactivestreams.Publisher;
  13. import org.reactivestreams.Subscriber;
  14. import java.io.Closeable;
  15. import java.io.File;
  16. import java.io.FileOutputStream;
  17. import java.io.IOException;
  18. import java.io.InputStream;
  19. import java.io.OutputStream;
  20. import java.io.RandomAccessFile;
  21. import java.nio.ByteOrder;
  22. import java.nio.MappedByteBuffer;
  23. import java.nio.channels.FileChannel;
  24. import java.util.ArrayList;
  25. import java.util.List;
  26. import java.util.UUID;
  27. import java.util.concurrent.TimeUnit;
  28. import java.util.zip.Adler32;
  29. import atmob.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
  30. import atmob.reactivex.rxjava3.annotations.NonNull;
  31. import atmob.reactivex.rxjava3.core.BackpressureStrategy;
  32. import atmob.reactivex.rxjava3.core.Flowable;
  33. import atmob.reactivex.rxjava3.core.FlowableOnSubscribe;
  34. import atmob.reactivex.rxjava3.functions.Function;
  35. import atmob.reactivex.rxjava3.schedulers.Schedulers;
  36. public class ImageDeepDetector {
  37. private static final int IMAGE_SUFFIX = 1;
  38. private static final int WECHAT_CACHE = 2;
  39. private static final int GALLERY_CACHE = 3;
  40. private static final int JPG_MAGIC = 4;
  41. private static final int OPPO_GALLERY_CACHE = 5;
  42. private static final int VIVO_GALLERY_CACHE = 6;
  43. private static final int XIAOMI_GALLERY_CACHE = 7;
  44. private static final int MEIZU_GALLERY_CACHE = 8;
  45. public static Flowable<List<ImageFile>> detect(Context context) {
  46. return Flowable.create((FlowableOnSubscribe<XFile>) emitter -> {
  47. try {
  48. CancellationSignal cancellationSignal = XFileSearch.searchExternalStorageAsync(context,
  49. new XFileSearch.FileFilter() {
  50. @Override
  51. public boolean acceptFile(XFile file) {
  52. return isAcceptFile(file);
  53. }
  54. @Override
  55. public boolean acceptDirectory(XFile file) {
  56. return isAcceptDirectory(file);
  57. }
  58. },
  59. new XFileSearch.FileSearchCallback() {
  60. @Override
  61. public void onStart() {
  62. }
  63. @Override
  64. public void onEachFile(XFile file) {
  65. emitter.onNext(file);
  66. }
  67. @Override
  68. public void onFinish() {
  69. emitter.onComplete();
  70. }
  71. });
  72. emitter.setCancellable(cancellationSignal::cancel);
  73. } catch (Exception e) {
  74. emitter.onError(e);
  75. }
  76. }, BackpressureStrategy.BUFFER)
  77. .filter(xFile -> xFile.getTag() != null)
  78. .flatMap((Function<XFile, Publisher<ImageFile>>) xFile -> {
  79. int tag = (int) xFile.getTag();
  80. switch (tag) {
  81. case JPG_MAGIC:
  82. case IMAGE_SUFFIX:
  83. return Flowable.just(new ImageFile(xFile));
  84. case XIAOMI_GALLERY_CACHE:
  85. return Flowable.just(new ImageFile(xFile, ImageFile.CATEGORY_GALLERY));
  86. case WECHAT_CACHE:
  87. return detectWechatCache(context, xFile);
  88. case GALLERY_CACHE:
  89. return detectGalleryCache(context, xFile);
  90. case OPPO_GALLERY_CACHE:
  91. return detectOppoGalleryCache(context, xFile);
  92. case VIVO_GALLERY_CACHE:
  93. return detectVivoGalleryCache(context, xFile);
  94. case MEIZU_GALLERY_CACHE:
  95. return detectMeizuGalleryCache(context, xFile);
  96. default:
  97. return Flowable.empty();
  98. }
  99. })
  100. .buffer(200, TimeUnit.MILLISECONDS)
  101. .filter(imageFiles -> imageFiles != null && imageFiles.size() > 0)
  102. .observeOn(AndroidSchedulers.mainThread())
  103. .doOnSubscribe(subscription -> {
  104. subscription.request(Long.MAX_VALUE);
  105. acquireWakeLock(context);
  106. })
  107. .doOnCancel(() -> releaseWakeLock(context))
  108. .doOnTerminate(() -> releaseWakeLock(context));
  109. }
  110. private static void releaseWakeLock(Context context) {
  111. PowerManager powerManager = (PowerManager) context.getSystemService(POWER_SERVICE);
  112. PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
  113. "ImageDeepDetector::detect");
  114. if (wakeLock.isHeld()) {
  115. wakeLock.release();
  116. }
  117. }
  118. private static void acquireWakeLock(Context context) {
  119. PowerManager powerManager = (PowerManager) context.getSystemService(POWER_SERVICE);
  120. PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
  121. "ImageDeepDetector::detect");
  122. wakeLock.acquire(10 * 60 * 1000L /*10 minutes*/);
  123. }
  124. private static Flowable<ImageFile> detectMeizuGalleryCache(Context context, XFile xFile) {
  125. return new GenericImgCollectionDetector(context, xFile, ImageFile.CATEGORY_GALLERY)
  126. .subscribeOn(Schedulers.io())
  127. .onErrorComplete();
  128. }
  129. private static Flowable<ImageFile> detectVivoGalleryCache(Context context, XFile xFile) {
  130. return new GenericImgCollectionDetector(context, xFile, ImageFile.CATEGORY_GALLERY)
  131. .subscribeOn(Schedulers.io())
  132. .onErrorComplete();
  133. }
  134. private static Flowable<ImageFile> detectOppoGalleryCache(Context context, XFile xFile) {
  135. return new GenericImgCollectionDetector(context, xFile, ImageFile.CATEGORY_GALLERY)
  136. .subscribeOn(Schedulers.io())
  137. .onErrorComplete();
  138. }
  139. private static Flowable<ImageFile> detectGalleryCache(Context context, XFile xFile) {
  140. return new GalleryCacheDetector(context, xFile)
  141. .subscribeOn(Schedulers.io())
  142. .onErrorComplete();
  143. }
  144. private static Flowable<ImageFile> detectWechatCache(Context context, XFile xFile) {
  145. return new WechatCacheDetector(context, xFile)
  146. .subscribeOn(Schedulers.io())
  147. .onErrorComplete();
  148. }
  149. private static boolean isAcceptDirectory(XFile file) {
  150. try {
  151. String path = file.getPath();
  152. if (isGalleryCacheDirectory(path)) {
  153. file.setTag(GALLERY_CACHE);
  154. return true;
  155. }
  156. } catch (Exception ignore) {
  157. }
  158. return false;
  159. }
  160. private static boolean isAcceptFile(XFile file) {
  161. try {
  162. if (file.length() == 0) {
  163. return false;
  164. }
  165. } catch (Exception ignore) {
  166. }
  167. try {
  168. String name = file.getName();
  169. if (isImageSuffix(name)) {
  170. file.setTag(IMAGE_SUFFIX);
  171. return true;
  172. }
  173. } catch (Exception ignore) {
  174. }
  175. try {
  176. String path = file.getPath();
  177. if (isWechatCacheFile(path)) {
  178. file.setTag(WECHAT_CACHE);
  179. return true;
  180. }
  181. if (isOppoGalleryCacheFile(path)) {
  182. file.setTag(OPPO_GALLERY_CACHE);
  183. return true;
  184. }
  185. if (isVivoGalleryCacheFile(path)) {
  186. file.setTag(VIVO_GALLERY_CACHE);
  187. return true;
  188. }
  189. if (isXiaomiGalleryCacheFile(path)) {
  190. file.setTag(XIAOMI_GALLERY_CACHE);
  191. return true;
  192. }
  193. if (isMeizuGalleryCacheFile(path)) {
  194. file.setTag(MEIZU_GALLERY_CACHE);
  195. return true;
  196. }
  197. } catch (Exception ignore) {
  198. }
  199. if (hasJpgMagic(file)) {
  200. file.setTag(JPG_MAGIC);
  201. return true;
  202. }
  203. return false;
  204. }
  205. private static boolean hasJpgMagic(XFile file) {
  206. try (InputStream inputStream = file.newInputStream()) {
  207. if (inputStream.available() < 4) {
  208. return false;
  209. }
  210. byte[] bytes = new byte[2];
  211. if (inputStream.read(bytes) != 2) {
  212. return false;
  213. }
  214. boolean hasHeaderMagic = bytes[0] == (byte) 0xFF && bytes[1] == (byte) 0xD8;
  215. if (!hasHeaderMagic) {
  216. return false;
  217. }
  218. long skip = inputStream.available() - 2;
  219. if (inputStream.skip(skip) != skip) {
  220. return false;
  221. }
  222. if (inputStream.read(bytes) != 2) {
  223. return false;
  224. }
  225. return bytes[0] == (byte) 0xFF && bytes[1] == (byte) 0xD9;
  226. } catch (Exception ignore) {
  227. }
  228. return false;
  229. }
  230. private static boolean isGalleryCacheDirectory(String path) {
  231. if (TextUtils.isEmpty(path)) {
  232. return false;
  233. }
  234. return path.contains("com.android.gallery3d%2Fcache") ||
  235. path.contains("com.android.gallery3d/cache");
  236. }
  237. private static boolean isWechatCacheFile(String name) {
  238. if (TextUtils.isEmpty(name)) {
  239. return false;
  240. }
  241. return name.contains("com.tencent.mm%2Fcache%2Fimgcache%2Fcache.data") ||
  242. name.contains("com.tencent.mm/cache/imgcache/cache.data");
  243. }
  244. private static boolean isOppoGalleryCacheFile(String path) {
  245. if (TextUtils.isEmpty(path)) {
  246. return false;
  247. }
  248. if (!path.contains("com.coloros.gallery3d%2Fcache") &&
  249. !path.contains("com.coloros.gallery3d/cache")) {
  250. return false;
  251. }
  252. return path.contains("imgcache") || path.contains("screennailcache")
  253. || path.contains("tilecache");
  254. }
  255. private static boolean isVivoGalleryCacheFile(String path) {
  256. if (TextUtils.isEmpty(path)) {
  257. return false;
  258. }
  259. if (!path.contains("com.vivo.gallery%2Fcache") &&
  260. !path.contains("com.vivo.gallery/cache")) {
  261. return false;
  262. }
  263. return path.contains("imgcache") || path.contains("trackthumbnail_cache");
  264. }
  265. private static boolean isXiaomiGalleryCacheFile(String path) {
  266. if (TextUtils.isEmpty(path)) {
  267. return false;
  268. }
  269. if (!path.contains("com.miui.gallery%2Ffiles%2Fgallery_disk_cache") &&
  270. !path.contains("com.miui.gallery/files/gallery_disk_cache")) {
  271. return false;
  272. }
  273. return path.contains("full_size") || path.contains("small_size");
  274. }
  275. private static boolean isMeizuGalleryCacheFile(String path) {
  276. if (TextUtils.isEmpty(path)) {
  277. return false;
  278. }
  279. if (!path.contains("com.meizu.media.gallery%2Fcache") &&
  280. !path.contains("com.meizu.media.gallery/cache")) {
  281. return false;
  282. }
  283. return path.contains("bestPhotoCache") || path.contains("face_thumbnails")
  284. || path.contains("uri_thumbnail_cache");
  285. }
  286. private static boolean isImageSuffix(String name) {
  287. if (TextUtils.isEmpty(name)) {
  288. return false;
  289. }
  290. return name.endsWith(".jpg") || name.endsWith(".jpeg") || name.endsWith(".png")
  291. || name.endsWith(".gif") || name.endsWith(".bmp") || name.endsWith(".webp")
  292. || name.endsWith(".tiff") || name.endsWith(".psd") || name.endsWith(".svg")
  293. || name.endsWith(".raw") || name.endsWith(".heif") || name.endsWith(".indd");
  294. }
  295. private static boolean bytes2File(byte[] bytes, File file) {
  296. try (FileOutputStream fileOutputStream = new FileOutputStream(file)) {
  297. fileOutputStream.write(bytes);
  298. fileOutputStream.flush();
  299. return true;
  300. } catch (Exception e) {
  301. e.printStackTrace();
  302. }
  303. return false;
  304. }
  305. private static boolean bytes2File(List<Byte> bytes, File file) {
  306. try (FileOutputStream fileOutputStream = new FileOutputStream(file)) {
  307. for (Byte aByte : bytes) {
  308. fileOutputStream.write(aByte);
  309. }
  310. fileOutputStream.flush();
  311. return true;
  312. } catch (Exception e) {
  313. e.printStackTrace();
  314. }
  315. return false;
  316. }
  317. private static File getDetectedCacheDir(Context context, String domain) {
  318. File cacheDir = context.getCacheDir();
  319. File detectedCacheDir = new File(cacheDir, CryptoUtils.HASH.md5(domain));
  320. if (!detectedCacheDir.exists()) {
  321. detectedCacheDir.mkdirs();
  322. }
  323. return detectedCacheDir;
  324. }
  325. private static void clearDetectedCache(Context context, String domain) {
  326. File detectedCacheDir = getDetectedCacheDir(context, domain);
  327. try {
  328. clearDir(detectedCacheDir);
  329. } catch (Exception e) {
  330. e.printStackTrace();
  331. }
  332. }
  333. private static void clearDir(File dir) {
  334. if (dir == null || !dir.exists()) {
  335. return;
  336. }
  337. File[] files = dir.listFiles();
  338. if (files == null || files.length == 0) {
  339. dir.delete();
  340. return;
  341. }
  342. for (File file : files) {
  343. if (file.isDirectory()) {
  344. clearDir(file);
  345. } else {
  346. file.delete();
  347. }
  348. }
  349. dir.delete();
  350. }
  351. public static class ImageFile {
  352. public static int CATEGORY_UNKNOWN = -1;
  353. public static int CATEGORY_OTHER = 0;
  354. public static int CATEGORY_QQ = 1;
  355. public static int CATEGORY_WECHAT = 2;
  356. public static int CATEGORY_GALLERY = 3;
  357. private final XFile xFile;
  358. private String name;
  359. private long size;
  360. private Uri uri;
  361. private String path;
  362. private int category;
  363. public ImageFile(XFile xFile) {
  364. this(xFile, CATEGORY_UNKNOWN);
  365. }
  366. public ImageFile(XFile xFile, int category) {
  367. this.category = category;
  368. this.xFile = xFile;
  369. try {
  370. this.name = xFile.getName();
  371. } catch (Exception ignore) {
  372. }
  373. try {
  374. this.size = xFile.length();
  375. } catch (Exception ignore) {
  376. }
  377. try {
  378. this.uri = xFile.getUri();
  379. } catch (Exception ignore) {
  380. }
  381. try {
  382. this.path = xFile.getPath();
  383. } catch (Exception ignore) {
  384. }
  385. }
  386. public String getName() {
  387. return name;
  388. }
  389. public long getSize() {
  390. return size;
  391. }
  392. public Uri getUri() {
  393. return uri;
  394. }
  395. public InputStream newInputStream() throws Exception {
  396. return xFile.newInputStream();
  397. }
  398. public boolean delete() throws Exception {
  399. return xFile.delete();
  400. }
  401. public int getCategory() {
  402. if (category != CATEGORY_UNKNOWN) {
  403. return category;
  404. }
  405. if (isGallery()) {
  406. return CATEGORY_GALLERY;
  407. } else if (isWechat()) {
  408. return CATEGORY_WECHAT;
  409. } else if (isQQ()) {
  410. return CATEGORY_QQ;
  411. } else {
  412. return CATEGORY_OTHER;
  413. }
  414. }
  415. private boolean isQQ() {
  416. if (TextUtils.isEmpty(path)) {
  417. return false;
  418. }
  419. return path.contains("com.tencent.mobileqq") || path.contains("com.tencent.tim");
  420. }
  421. private boolean isWechat() {
  422. if (!TextUtils.isEmpty(path) && path.contains("com.tencent.mm")) {
  423. return true;
  424. }
  425. return false;
  426. }
  427. private boolean isGallery() {
  428. if (!TextUtils.isEmpty(path) && (
  429. path.contains("com.android.gallery3d") ||
  430. path.contains("com.coloros.gallery3d") ||
  431. path.contains("com.vivo.gallery") ||
  432. path.contains("com.miui.gallery") ||
  433. path.contains("com.meizu.media.gallery") ||
  434. path.contains("com.oppo.gallery3d") ||
  435. path.contains("com.android.gallery") ||
  436. path.contains("DCIM")
  437. )) {
  438. return true;
  439. }
  440. return false;
  441. }
  442. }
  443. private static class WechatCacheDetector extends Flowable<ImageFile> {
  444. private static final String CACHE_DOMAIN = "wechat_cache_detector";
  445. private final XFile xFile;
  446. private final Context context;
  447. public WechatCacheDetector(Context context, XFile xFile) {
  448. this.context = context;
  449. this.xFile = xFile;
  450. }
  451. @Override
  452. protected void subscribeActual(@NonNull Subscriber<? super ImageFile> subscriber) {
  453. long lastModified;
  454. try {
  455. lastModified = xFile.lastModified();
  456. } catch (Exception e) {
  457. subscriber.onError(e);
  458. return;
  459. }
  460. if (checkDetectedCache(context, lastModified, subscriber)) {
  461. subscriber.onComplete();
  462. return;
  463. } else {
  464. clearDetectedCache(context, CACHE_DOMAIN);
  465. }
  466. File detectedCacheDir = getDetectedCacheDir(context, CACHE_DOMAIN);
  467. detectedCacheDir = new File(detectedCacheDir, CryptoUtils.HASH.md5(String.valueOf(lastModified)));
  468. if (!detectedCacheDir.exists()) {
  469. detectedCacheDir.mkdirs();
  470. }
  471. try (InputStream inputStream = xFile.newInputStream()) {
  472. ArrayList<Byte> imageBytes = new ArrayList<>();
  473. byte[] buffer = new byte[2048];
  474. int read;
  475. while ((read = inputStream.read(buffer)) != -1) {
  476. for (int i = 0; i < read; i++) {
  477. byte b = buffer[i];
  478. imageBytes.add(b);
  479. if (imageBytes.size() < 2) {
  480. continue;
  481. }
  482. if (imageBytes.size() == 2) {
  483. if (imageBytes.get(0) != (byte) 0xFF || imageBytes.get(1) != (byte) 0xD8) {
  484. imageBytes.remove(0);
  485. }
  486. continue;
  487. }
  488. if (i == read - 1 && inputStream.available() == 0) {
  489. if (imageBytes.get(imageBytes.size() - 2) == (byte) 0xFF && imageBytes.get(imageBytes.size() - 1) == (byte) 0xD9) {
  490. File cache = new File(detectedCacheDir, UUID.randomUUID() + ".jpg");
  491. if (cache.createNewFile() && bytes2File(imageBytes, cache)) {
  492. subscriber.onNext(new ImageFile(new XPathFile(context, cache), ImageFile.CATEGORY_WECHAT));
  493. }
  494. }
  495. imageBytes.clear();
  496. } else if (imageBytes.size() >= 6) {
  497. if (imageBytes.get(imageBytes.size() - 1) == (byte) 0xD8
  498. && imageBytes.get(imageBytes.size() - 2) == (byte) 0xFF
  499. && imageBytes.get(imageBytes.size() - 3) == (byte) 0xD9
  500. && imageBytes.get(imageBytes.size() - 4) == (byte) 0xFF
  501. ) {
  502. imageBytes.remove(imageBytes.size() - 1);
  503. imageBytes.remove(imageBytes.size() - 1);
  504. File cache = new File(detectedCacheDir, UUID.randomUUID() + ".jpg");
  505. if (cache.createNewFile() && bytes2File(imageBytes, cache)) {
  506. subscriber.onNext(new ImageFile(new XPathFile(context, cache), ImageFile.CATEGORY_WECHAT));
  507. }
  508. imageBytes.clear();
  509. imageBytes.add((byte) 0xFF);
  510. imageBytes.add((byte) 0xD8);
  511. }
  512. }
  513. }
  514. }
  515. subscriber.onComplete();
  516. } catch (Exception e) {
  517. subscriber.onError(e);
  518. }
  519. }
  520. private boolean checkDetectedCache(Context context, long lastModified, Subscriber<? super ImageFile> subscriber) {
  521. File detectedCacheDir = getDetectedCacheDir(context, CACHE_DOMAIN);
  522. File targetCaches = new File(detectedCacheDir, CryptoUtils.HASH.md5(String.valueOf(lastModified)));
  523. File[] files = targetCaches.exists() && targetCaches.isDirectory() ? targetCaches.listFiles() : null;
  524. if (files != null && files.length > 0) {
  525. for (File file : files) {
  526. subscriber.onNext(new ImageFile(new XPathFile(this.context, file), ImageFile.CATEGORY_WECHAT));
  527. }
  528. return true;
  529. }
  530. return false;
  531. }
  532. }
  533. private static class GalleryCacheDetector extends Flowable<ImageFile> {
  534. private static final String CACHE_DOMAIN = "gallery_cache_detector";
  535. private static final int MAGIC_INDEX_FILE = 0xB3273030;
  536. private static final int MAGIC_DATA_FILE = 0xBD248510;
  537. // index header offset
  538. private static final int IH_MAGIC = 0;
  539. private static final int IH_MAX_ENTRIES = 4;
  540. private static final int IH_MAX_BYTES = 8;
  541. private static final int IH_ACTIVE_REGION = 12;
  542. private static final int IH_ACTIVE_ENTRIES = 16;
  543. private static final int IH_ACTIVE_BYTES = 20;
  544. private static final int IH_CHECKSUM = 28;
  545. private static final int INDEX_HEADER_SIZE = 32;
  546. private static final int DATA_HEADER_SIZE = 4;
  547. // blob header offset
  548. private static final int BH_KEY = 0;
  549. private static final int BH_CHECKSUM = 8;
  550. private static final int BH_OFFSET = 12;
  551. private static final int BH_LENGTH = 16;
  552. private static final int BLOB_HEADER_SIZE = 20;
  553. private final XFile galleryCacheDir;
  554. private final byte[] indexHeader;
  555. private final byte[] blobHeader;
  556. private final Adler32 mAdler32 = new Adler32();
  557. private final Context context;
  558. private int mMaxEntries;
  559. private int mMaxBytes;
  560. private int mActiveRegion;
  561. private int mActiveBytes;
  562. private FileChannel mIndexChannel;
  563. private MappedByteBuffer mIndexBuffer;
  564. private RandomAccessFile mIndexFile;
  565. private RandomAccessFile mDataFile0;
  566. private RandomAccessFile mDataFile1;
  567. private RandomAccessFile mActiveDataFile;
  568. private int mActiveHashStart;
  569. public GalleryCacheDetector(Context context, XFile galleryCacheDir) {
  570. this.context = context;
  571. this.galleryCacheDir = galleryCacheDir;
  572. this.indexHeader = new byte[INDEX_HEADER_SIZE];
  573. this.blobHeader = new byte[BLOB_HEADER_SIZE];
  574. }
  575. @Override
  576. protected void subscribeActual(@NonNull Subscriber<? super ImageFile> subscriber) {
  577. XFile[] xFiles;
  578. try {
  579. xFiles = galleryCacheDir.listFiles();
  580. } catch (Exception e) {
  581. subscriber.onError(e);
  582. return;
  583. }
  584. if (xFiles == null || xFiles.length == 0) {
  585. subscriber.onComplete();
  586. return;
  587. }
  588. XFile indexFile = null;
  589. XFile dataFile0 = null;
  590. XFile dataFile1 = null;
  591. for (XFile xFile : xFiles) {
  592. try {
  593. String name = xFile.getName();
  594. if (name.endsWith(".idx")) {
  595. indexFile = xFile;
  596. } else if (name.endsWith(".0")) {
  597. dataFile0 = xFile;
  598. } else if (name.endsWith(".1")) {
  599. dataFile1 = xFile;
  600. }
  601. } catch (Exception e) {
  602. subscriber.onError(e);
  603. }
  604. }
  605. if (indexFile == null || dataFile0 == null || dataFile1 == null) {
  606. subscriber.onComplete();
  607. return;
  608. }
  609. doDetect(indexFile, dataFile0, dataFile1, subscriber);
  610. }
  611. private void doDetect(XFile indexFile, XFile dataFile0, XFile dataFile1, Subscriber<? super ImageFile> subscriber) {
  612. try {
  613. long lastModified;
  614. try {
  615. lastModified = indexFile.lastModified();
  616. } catch (Exception e) {
  617. subscriber.onError(e);
  618. return;
  619. }
  620. if (checkDetectedCache(context, lastModified, subscriber)) {
  621. subscriber.onComplete();
  622. return;
  623. } else {
  624. clearDetectedCache(context, CACHE_DOMAIN);
  625. }
  626. File detectedCacheDir = getDetectedCacheDir(context, CACHE_DOMAIN);
  627. detectedCacheDir = new File(detectedCacheDir, CryptoUtils.HASH.md5(String.valueOf(lastModified)));
  628. if (!detectedCacheDir.exists()) {
  629. detectedCacheDir.mkdirs();
  630. }
  631. loadIndex(indexFile, dataFile0, dataFile1);
  632. for (int i = 0; i < mMaxEntries; i++) {
  633. int offset = mActiveHashStart + i * 12;
  634. long candidateKey = mIndexBuffer.getLong(offset);
  635. try {
  636. LookupRequest lookupRequest = new LookupRequest(candidateKey);
  637. if (!lookup(lookupRequest)) {
  638. continue;
  639. }
  640. byte[] lookup = lookupRequest.buffer;
  641. if (lookup == null) {
  642. continue;
  643. }
  644. byte[] cropData = cropLookup(lookup);
  645. if (cropData == null) {
  646. continue;
  647. }
  648. File cache = new File(detectedCacheDir, UUID.randomUUID() + ".jpg");
  649. if (cache.createNewFile() && bytes2File(cropData, cache)) {
  650. subscriber.onNext(new ImageFile(new XPathFile(context, cache), ImageFile.CATEGORY_GALLERY));
  651. }
  652. } catch (Exception ignore) {
  653. }
  654. }
  655. subscriber.onComplete();
  656. } catch (Exception e) {
  657. subscriber.onError(e);
  658. } finally {
  659. closeAll();
  660. }
  661. }
  662. private boolean checkDetectedCache(Context context, long lastModified, Subscriber<? super ImageFile> subscriber) {
  663. File detectedCacheDir = getDetectedCacheDir(context, CACHE_DOMAIN);
  664. File targetCaches = new File(detectedCacheDir, CryptoUtils.HASH.md5(String.valueOf(lastModified)));
  665. File[] files = targetCaches.exists() && targetCaches.isDirectory() ? targetCaches.listFiles() : null;
  666. if (files != null && files.length > 0) {
  667. for (File file : files) {
  668. subscriber.onNext(new ImageFile(new XPathFile(this.context, file), ImageFile.CATEGORY_GALLERY));
  669. }
  670. return true;
  671. }
  672. return false;
  673. }
  674. private byte[] cropLookup(byte[] lookup) {
  675. for (int i = 0; i < lookup.length; i++) {
  676. if (lookup[i] == (byte) 0xFF && i + 1 < lookup.length && lookup[i + 1] == (byte) 0xD8) {
  677. return crop(lookup, i);
  678. }
  679. }
  680. return null;
  681. }
  682. private byte[] crop(byte[] lookup, int i) {
  683. byte[] crop = new byte[lookup.length - i];
  684. System.arraycopy(lookup, i, crop, 0, crop.length);
  685. return crop;
  686. }
  687. private void loadIndex(XFile indexFile, XFile dataFile0, XFile dataFile1) throws Exception {
  688. checkFileValid(indexFile, dataFile0, dataFile1);
  689. try (InputStream idxIs = indexFile.newInputStream();
  690. InputStream data0Is = dataFile0.newInputStream();
  691. InputStream data1Is = dataFile1.newInputStream()
  692. ) {
  693. File indexTemp = createTempFile("index.temp", idxIs);
  694. mIndexFile = new RandomAccessFile(indexTemp, "rw");
  695. File data0Temp = createTempFile("data0.temp", data0Is);
  696. mDataFile0 = new RandomAccessFile(data0Temp, "rw");
  697. File data1Temp = createTempFile("data1.temp", data1Is);
  698. mDataFile1 = new RandomAccessFile(data1Temp, "rw");
  699. // Map index file to memory
  700. mIndexChannel = mIndexFile.getChannel();
  701. mIndexBuffer = mIndexChannel.map(FileChannel.MapMode.READ_WRITE,
  702. 0, mIndexFile.length());
  703. mIndexBuffer.order(ByteOrder.LITTLE_ENDIAN);
  704. setActiveVariables();
  705. }
  706. }
  707. private void setActiveVariables() throws Exception {
  708. mActiveDataFile = (mActiveRegion == 0) ? mDataFile0 : mDataFile1;
  709. mActiveDataFile.setLength(mActiveBytes);
  710. mActiveDataFile.seek(mActiveBytes);
  711. mActiveHashStart = INDEX_HEADER_SIZE;
  712. if (mActiveRegion != 0) {
  713. mActiveHashStart += mMaxEntries * 12;
  714. }
  715. }
  716. private void checkFileValid(XFile indexFile, XFile dataFile0, XFile dataFile1) throws Exception {
  717. byte[] buf = indexHeader;
  718. try (InputStream inputStream = indexFile.newInputStream()) {
  719. if (inputStream.read(buf) != INDEX_HEADER_SIZE) {
  720. throw new Exception("cannot read header");
  721. }
  722. if (readInt(buf, IH_MAGIC) != MAGIC_INDEX_FILE) {
  723. throw new Exception("cannot read header magic");
  724. }
  725. }
  726. mMaxEntries = readInt(buf, IH_MAX_ENTRIES);
  727. mMaxBytes = readInt(buf, IH_MAX_BYTES);
  728. mActiveRegion = readInt(buf, IH_ACTIVE_REGION);
  729. int mActiveEntries = readInt(buf, IH_ACTIVE_ENTRIES);
  730. mActiveBytes = readInt(buf, IH_ACTIVE_BYTES);
  731. int sum = readInt(buf, IH_CHECKSUM);
  732. if (checkSum(buf, 0, IH_CHECKSUM) != sum) {
  733. throw new Exception("header checksum does not match");
  734. }
  735. // Sanity check
  736. if (mMaxEntries <= 0) {
  737. throw new Exception("invalid max entries");
  738. }
  739. if (mMaxBytes <= 0) {
  740. throw new Exception("invalid max bytes");
  741. }
  742. if (mActiveRegion != 0 && mActiveRegion != 1) {
  743. throw new Exception("invalid active region");
  744. }
  745. if (mActiveEntries < 0 || mActiveEntries > mMaxEntries) {
  746. throw new Exception("invalid active entries");
  747. }
  748. if (mActiveBytes < DATA_HEADER_SIZE || mActiveBytes > mMaxBytes) {
  749. throw new Exception("invalid active bytes");
  750. }
  751. if (indexFile.length() != INDEX_HEADER_SIZE + mMaxEntries * 12 * 2L) {
  752. throw new Exception("invalid index file length");
  753. }
  754. // Make sure data file has magic
  755. byte[] magic = new byte[4];
  756. try (InputStream data0Is = dataFile0.newInputStream()) {
  757. if (data0Is.read(magic) != 4) {
  758. throw new Exception("cannot read data file magic");
  759. }
  760. }
  761. if (readInt(magic, 0) != MAGIC_DATA_FILE) {
  762. throw new Exception("invalid data file magic");
  763. }
  764. try (InputStream data1Is = dataFile1.newInputStream()) {
  765. if (data1Is.read(magic) != 4) {
  766. throw new Exception("cannot read data file magic");
  767. }
  768. }
  769. if (readInt(magic, 0) != MAGIC_DATA_FILE) {
  770. throw new Exception("invalid data file magic");
  771. }
  772. }
  773. private File createTempFile(String fileName, InputStream inputStream) throws Exception {
  774. File tempFile = new File(context.getCacheDir(), fileName);
  775. if (tempFile.exists()) {
  776. tempFile.delete();
  777. }
  778. if (!tempFile.createNewFile()) {
  779. throw new Exception("cannot create temp file");
  780. }
  781. try (OutputStream outputStream = new FileOutputStream(tempFile)) {
  782. copyStream(inputStream, outputStream);
  783. }
  784. return tempFile;
  785. }
  786. public boolean lookup(LookupRequest req) throws IOException {
  787. if (lookupInternal(req.key, mActiveHashStart)) {
  788. return getBlob(mActiveDataFile, mFileOffset, req);
  789. }
  790. return false;
  791. }
  792. private int mFileOffset;
  793. private boolean lookupInternal(long key, int hashStart) {
  794. int slot = (int) (key % mMaxEntries);
  795. if (slot < 0) slot += mMaxEntries;
  796. int slotBegin = slot;
  797. while (true) {
  798. int offset = hashStart + slot * 12;
  799. long candidateKey = mIndexBuffer.getLong(offset);
  800. int candidateOffset = mIndexBuffer.getInt(offset + 8);
  801. if (candidateOffset == 0) {
  802. return false;
  803. } else if (candidateKey == key) {
  804. mFileOffset = candidateOffset;
  805. return true;
  806. } else {
  807. if (++slot >= mMaxEntries) {
  808. slot = 0;
  809. }
  810. if (slot == slotBegin) {
  811. mIndexBuffer.putInt(hashStart + slot * 12 + 8, 0);
  812. }
  813. }
  814. }
  815. }
  816. private boolean getBlob(RandomAccessFile file, int offset,
  817. LookupRequest req) throws IOException {
  818. byte[] header = blobHeader;
  819. long oldPosition = file.getFilePointer();
  820. try {
  821. file.seek(offset);
  822. if (file.read(header) != BLOB_HEADER_SIZE) {
  823. return false;
  824. }
  825. long blobKey = readLong(header, BH_KEY);
  826. if (blobKey == 0) {
  827. return false; // This entry has been cleared.
  828. }
  829. if (blobKey != req.key) {
  830. return false;
  831. }
  832. int sum = readInt(header, BH_CHECKSUM);
  833. int blobOffset = readInt(header, BH_OFFSET);
  834. if (blobOffset != offset) {
  835. return false;
  836. }
  837. int length = readInt(header, BH_LENGTH);
  838. if (length < 0 || length > mMaxBytes - offset - BLOB_HEADER_SIZE) {
  839. return false;
  840. }
  841. if (req.buffer == null || req.buffer.length < length) {
  842. req.buffer = new byte[length];
  843. }
  844. byte[] blob = req.buffer;
  845. req.length = length;
  846. if (file.read(blob, 0, length) != length) {
  847. return false;
  848. }
  849. return checkSum(blob, 0, length) == sum;
  850. } catch (Throwable t) {
  851. return false;
  852. } finally {
  853. file.seek(oldPosition);
  854. }
  855. }
  856. static int readInt(byte[] buf, int offset) {
  857. return (buf[offset] & 0xff)
  858. | ((buf[offset + 1] & 0xff) << 8)
  859. | ((buf[offset + 2] & 0xff) << 16)
  860. | ((buf[offset + 3] & 0xff) << 24);
  861. }
  862. static long readLong(byte[] buf, int offset) {
  863. long result = buf[offset + 7] & 0xff;
  864. for (int i = 6; i >= 0; i--) {
  865. result = (result << 8) | (buf[offset + i] & 0xff);
  866. }
  867. return result;
  868. }
  869. int checkSum(byte[] data, int offset, int nbytes) {
  870. mAdler32.reset();
  871. mAdler32.update(data, offset, nbytes);
  872. return (int) mAdler32.getValue();
  873. }
  874. private void copyStream(InputStream is, OutputStream os) throws Exception {
  875. byte[] buf = new byte[2048];
  876. int n;
  877. while ((n = is.read(buf)) > 0) {
  878. os.write(buf, 0, n);
  879. }
  880. os.flush();
  881. }
  882. private void closeAll() {
  883. closeSilently(mIndexChannel);
  884. closeSilently(mIndexFile);
  885. closeSilently(mDataFile0);
  886. closeSilently(mDataFile1);
  887. }
  888. private void closeSilently(Closeable c) {
  889. if (c == null) return;
  890. try {
  891. c.close();
  892. } catch (Throwable t) {
  893. // do nothing
  894. }
  895. }
  896. public static class LookupRequest {
  897. public long key; // input: the key to find
  898. public byte[] buffer; // input/output: the buffer to store the blob
  899. public int length; // output: the length of the blob
  900. public LookupRequest(long key) {
  901. this.key = key;
  902. }
  903. }
  904. }
  905. private static class GenericImgCollectionDetector extends Flowable<ImageFile> {
  906. private final int category;
  907. private String CACHE_DOMAIN = "generic_img_collection_detector";
  908. private final Context context;
  909. private final XFile xFile;
  910. public GenericImgCollectionDetector(Context context, XFile xFile, int category) {
  911. this.context = context;
  912. this.xFile = xFile;
  913. this.category = category;
  914. }
  915. @Override
  916. protected void subscribeActual(@NonNull Subscriber<? super ImageFile> subscriber) {
  917. long lastModified;
  918. try {
  919. lastModified = xFile.lastModified();
  920. CACHE_DOMAIN += xFile.getName();
  921. } catch (Exception e) {
  922. subscriber.onError(e);
  923. return;
  924. }
  925. if (checkDetectedCache(context, lastModified, subscriber)) {
  926. subscriber.onComplete();
  927. return;
  928. } else {
  929. clearDetectedCache(context, CACHE_DOMAIN);
  930. }
  931. File detectedCacheDir = getDetectedCacheDir(context, CACHE_DOMAIN);
  932. detectedCacheDir = new File(detectedCacheDir, CryptoUtils.HASH.md5(String.valueOf(lastModified)));
  933. if (!detectedCacheDir.exists()) {
  934. detectedCacheDir.mkdirs();
  935. }
  936. try (InputStream inputStream = xFile.newInputStream()) {
  937. ArrayList<Byte> imageBytes = new ArrayList<>();
  938. byte[] buffer = new byte[2048];
  939. int read;
  940. while ((read = inputStream.read(buffer)) != -1) {
  941. for (int i = 0; i < read; i++) {
  942. byte b = buffer[i];
  943. imageBytes.add(b);
  944. if (imageBytes.size() < 2) {
  945. continue;
  946. }
  947. if (imageBytes.size() == 2) {
  948. if (imageBytes.get(0) != (byte) 0xFF || imageBytes.get(1) != (byte) 0xD8) {
  949. imageBytes.remove(0);
  950. }
  951. continue;
  952. }
  953. if (i == read - 1 && inputStream.available() == 0) {
  954. if (imageBytes.get(imageBytes.size() - 2) == (byte) 0xFF && imageBytes.get(imageBytes.size() - 1) == (byte) 0xD9) {
  955. File cache = new File(detectedCacheDir, UUID.randomUUID() + ".jpg");
  956. if (cache.createNewFile() && bytes2File(imageBytes, cache)) {
  957. subscriber.onNext(new ImageFile(new XPathFile(context, cache), category));
  958. }
  959. }
  960. imageBytes.clear();
  961. } else if (imageBytes.size() >= 4) {
  962. if (imageBytes.get(imageBytes.size() - 1) == (byte) 0xD9
  963. && imageBytes.get(imageBytes.size() - 2) == (byte) 0xFF
  964. ) {
  965. File cache = new File(detectedCacheDir, UUID.randomUUID() + ".jpg");
  966. if (cache.createNewFile() && bytes2File(imageBytes, cache)) {
  967. subscriber.onNext(new ImageFile(new XPathFile(context, cache), category));
  968. }
  969. imageBytes.clear();
  970. }
  971. }
  972. }
  973. }
  974. subscriber.onComplete();
  975. } catch (Exception e) {
  976. subscriber.onError(e);
  977. }
  978. }
  979. private boolean checkDetectedCache(Context context, long lastModified, Subscriber<? super ImageFile> subscriber) {
  980. File detectedCacheDir = getDetectedCacheDir(context, CACHE_DOMAIN);
  981. File targetCaches = new File(detectedCacheDir, CryptoUtils.HASH.md5(String.valueOf(lastModified)));
  982. File[] files = targetCaches.exists() && targetCaches.isDirectory() ? targetCaches.listFiles() : null;
  983. if (files != null && files.length > 0) {
  984. for (File file : files) {
  985. subscriber.onNext(new ImageFile(new XPathFile(this.context, file), category));
  986. }
  987. return true;
  988. }
  989. return false;
  990. }
  991. }
  992. }