ImageDeepDetector.java 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403
  1. package com.datarecovery.master.utils;
  2. import static android.content.Context.POWER_SERVICE;
  3. import android.app.PendingIntent;
  4. import android.content.Context;
  5. import android.database.Cursor;
  6. import android.database.sqlite.SQLiteDatabase;
  7. import android.net.Uri;
  8. import android.os.CancellationSignal;
  9. import android.os.Environment;
  10. import android.os.PowerManager;
  11. import android.provider.MediaStore;
  12. import android.text.TextUtils;
  13. import androidx.databinding.BaseObservable;
  14. import androidx.databinding.Bindable;
  15. import com.atmob.common.crypto.CryptoUtils;
  16. import com.atmob.common.runtime.ActivityUtil;
  17. import com.atmob.common.runtime.ContextUtil;
  18. import com.datarecovery.master.BR;
  19. import com.datarecovery.master.utils.xfile.XFile;
  20. import com.datarecovery.master.utils.xfile.XFileSearch;
  21. import com.datarecovery.master.utils.xfile.XPathFile;
  22. import org.reactivestreams.Publisher;
  23. import org.reactivestreams.Subscriber;
  24. import java.io.Closeable;
  25. import java.io.File;
  26. import java.io.FileOutputStream;
  27. import java.io.IOException;
  28. import java.io.InputStream;
  29. import java.io.OutputStream;
  30. import java.io.RandomAccessFile;
  31. import java.nio.ByteOrder;
  32. import java.nio.MappedByteBuffer;
  33. import java.nio.channels.FileChannel;
  34. import java.util.ArrayList;
  35. import java.util.Collections;
  36. import java.util.List;
  37. import java.util.Objects;
  38. import java.util.UUID;
  39. import java.util.concurrent.TimeUnit;
  40. import java.util.zip.Adler32;
  41. import atmob.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
  42. import atmob.reactivex.rxjava3.annotations.NonNull;
  43. import atmob.reactivex.rxjava3.core.BackpressureStrategy;
  44. import atmob.reactivex.rxjava3.core.Flowable;
  45. import atmob.reactivex.rxjava3.core.FlowableOnSubscribe;
  46. import atmob.reactivex.rxjava3.functions.Function;
  47. import atmob.reactivex.rxjava3.schedulers.Schedulers;
  48. public class ImageDeepDetector {
  49. private static final int IMAGE_SUFFIX = 1;
  50. private static final int WECHAT_CACHE = 2;
  51. private static final int GALLERY_CACHE = 3;
  52. private static final int IMG_MAGIC = 4;
  53. private static final int OPPO_GALLERY_CACHE = 5;
  54. private static final int VIVO_GALLERY_CACHE = 6;
  55. private static final int XIAOMI_GALLERY_CACHE = 7;
  56. private static final int MEIZU_GALLERY_CACHE = 8;
  57. private static final int HUAWEI_GALLERY_CACHE = 9;
  58. public static Flowable<List<ImageFile>> detect(Context context) {
  59. return Flowable.create((FlowableOnSubscribe<XFile>) emitter -> {
  60. try {
  61. CancellationSignal cancellationSignal = XFileSearch.searchExternalStorageAsync(context,
  62. new XFileSearch.FileFilter() {
  63. @Override
  64. public boolean acceptFile(XFile file) {
  65. return isAcceptFile(file);
  66. }
  67. @Override
  68. public boolean acceptDirectory(XFile file) {
  69. return isAcceptDirectory(file);
  70. }
  71. @Override
  72. public boolean filterDirectory(XFile file) {
  73. return isFilterDirectory(file);
  74. }
  75. },
  76. new XFileSearch.FileSearchCallback() {
  77. @Override
  78. public void onStart() {
  79. }
  80. @Override
  81. public void onEachFile(XFile file) {
  82. emitter.onNext(file);
  83. }
  84. @Override
  85. public void onFinish() {
  86. emitter.onComplete();
  87. }
  88. });
  89. emitter.setCancellable(cancellationSignal::cancel);
  90. } catch (Exception e) {
  91. emitter.onError(e);
  92. }
  93. }, BackpressureStrategy.BUFFER)
  94. .filter(xFile -> xFile.getTag() != null)
  95. .flatMap((Function<XFile, Publisher<ImageFile>>) xFile -> {
  96. int tag = (int) xFile.getTag();
  97. switch (tag) {
  98. case IMG_MAGIC:
  99. case IMAGE_SUFFIX:
  100. return Flowable.just(new ImageFile(xFile));
  101. case XIAOMI_GALLERY_CACHE:
  102. return Flowable.just(new ImageFile(xFile, ImageFile.CATEGORY_GALLERY));
  103. case WECHAT_CACHE:
  104. return detectWechatCache(context, xFile);
  105. case GALLERY_CACHE:
  106. return detectGalleryCache(context, xFile);
  107. case OPPO_GALLERY_CACHE:
  108. return detectOppoGalleryCache(context, xFile);
  109. case VIVO_GALLERY_CACHE:
  110. return detectVivoGalleryCache(context, xFile);
  111. case MEIZU_GALLERY_CACHE:
  112. return detectMeizuGalleryCache(context, xFile);
  113. case HUAWEI_GALLERY_CACHE:
  114. return detectHuaweiGalleryCache(context, xFile);
  115. default:
  116. return Flowable.empty();
  117. }
  118. })
  119. .buffer(200, TimeUnit.MILLISECONDS)
  120. .filter(imageFiles -> imageFiles != null && imageFiles.size() > 0)
  121. .observeOn(AndroidSchedulers.mainThread())
  122. .doOnSubscribe(subscription -> {
  123. subscription.request(Long.MAX_VALUE);
  124. acquireWakeLock(context);
  125. })
  126. .doOnCancel(() -> releaseWakeLock(context))
  127. .doOnTerminate(() -> releaseWakeLock(context));
  128. }
  129. private static void releaseWakeLock(Context context) {
  130. PowerManager powerManager = (PowerManager) context.getSystemService(POWER_SERVICE);
  131. PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
  132. "ImageDeepDetector::detect");
  133. if (wakeLock.isHeld()) {
  134. wakeLock.release();
  135. }
  136. }
  137. private static void acquireWakeLock(Context context) {
  138. PowerManager powerManager = (PowerManager) context.getSystemService(POWER_SERVICE);
  139. PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
  140. "ImageDeepDetector::detect");
  141. wakeLock.acquire(10 * 60 * 1000L /*10 minutes*/);
  142. }
  143. private static boolean isFilterDirectory(XFile file) {
  144. try {
  145. String path = file.getPath();
  146. if (TextUtils.isEmpty(path)) {
  147. return false;
  148. }
  149. if (path.endsWith(ContextUtil.getContext().getPackageName())) {
  150. return true;
  151. }
  152. if (path.contains("com.kuaishou.nebula") && (path.endsWith("live_gift_store_icon_directory") ||
  153. path.endsWith("magic_finger_resource") || path.endsWith("theme_resource") ||
  154. path.endsWith("magic_emoji_resource") || path.endsWith(".material_library_resource") ||
  155. path.endsWith("sticker_resource") || path.endsWith("preload%2Ficon%2Fcommon") ||
  156. path.endsWith("preload/icon/common") || path.endsWith(".emoji")
  157. )) {
  158. return true;
  159. }
  160. if ((path.contains("com.tencent.mobileqq") || path.endsWith("com.tencent.tim")) && (path.endsWith("qvideo_newvideo_tips") ||
  161. path.endsWith("Gameicon") || path.endsWith("html5") || path.endsWith(".preloaduni") ||
  162. path.endsWith(".apollo")) || path.endsWith("editor%2Fresources") || path.endsWith("editor/resources") ||
  163. path.endsWith("lottie") || path.endsWith(".vaspoke") || path.endsWith("newpoke") ||
  164. path.endsWith("qcircle%2Ffile%2Fdownload") || path.endsWith("qcircle/file/download") ||
  165. path.endsWith("qzone%2Fzip_cache") || path.endsWith("qzone/zip_cache") || path.endsWith("poke") ||
  166. path.endsWith("DoutuRes")) {
  167. return true;
  168. }
  169. if ((path.contains("com.ss.android.article.video") || path.contains("com.ss.android.ugc.aweme")) && (path.endsWith("liveroom") ||
  170. path.endsWith("effect") || path.endsWith("card_3d_res") || path.endsWith("weboffline") || path.endsWith("fantasy_lottie_res")
  171. )) {
  172. return true;
  173. }
  174. if ((path.contains("com.taobao.taobao") || path.contains("com.tmall.wireless")) && (path.endsWith("AVFSCache") ||
  175. path.endsWith("gs_fs"))) {
  176. return true;
  177. }
  178. if ((path.contains("com.baidu.BaiduMap")) && (path.endsWith("sticker"))) {
  179. return true;
  180. }
  181. if ((path.contains("com.eg.android.AlipayGphone")) && (path.endsWith("Sandbox") ||
  182. path.endsWith("emojiFiles"))) {
  183. return true;
  184. }
  185. if ((path.contains("air.tv.douyu.android")) && (path.endsWith("skin_download_dir"))) {
  186. return true;
  187. }
  188. if ((path.contains("com.kugou.android")) && (path.endsWith("kugou/lyric") ||
  189. path.endsWith("kugou%2Flyric"))) {
  190. return true;
  191. }
  192. if ((path.contains("com.ss.android.article.news") || path.contains("com.ss.android.ugc.aweme"))
  193. && (path.endsWith("resources%2Fvariety") || path.endsWith("resources/variety"))) {
  194. return true;
  195. }
  196. if ((path.contains("com.autonavi.minimap") || path.contains("com.amap.android.ams")) && (path.endsWith("sharetrip.taxi") ||
  197. path.endsWith("sharetrip%2Ftaxi") || path.endsWith("httpcache"))) {
  198. return true;
  199. }
  200. if (path.contains("tencent/MobileQQ/doodle_template") || path.endsWith("tencent%2FMobileQQ%2Fdoodle_template")) {
  201. return true;
  202. }
  203. if (path.contains(".mob_ad/.material") || path.endsWith("mob_ad%2F.material")) {
  204. return true;
  205. }
  206. if (path.contains("bddownload/common") || path.endsWith("bddownload%2Fcommon")) {
  207. return true;
  208. }
  209. if (path.contains("Pictures/.gs_fs") || path.endsWith("Pictures%2F.gs_fs")) {
  210. return true;
  211. }
  212. if (path.endsWith("files/amap") || path.endsWith("files%2Famap")) {
  213. return true;
  214. }
  215. if (path.endsWith("ksadsdk")) {
  216. return true;
  217. }
  218. if (path.endsWith("files%2Fbddownload%2Fimg_download") || path.endsWith("files/bddownload/img_download")) {
  219. return true;
  220. }
  221. if (path.endsWith("__MACOSX")) {
  222. return true;
  223. }
  224. } catch (Exception ignore) {
  225. }
  226. return false;
  227. }
  228. private static Flowable<ImageFile> detectHuaweiGalleryCache(Context context, XFile xFile) {
  229. return new HuaweiGalleryCacheDetector(context, xFile)
  230. .subscribeOn(Schedulers.io())
  231. .onErrorComplete();
  232. }
  233. private static Flowable<ImageFile> detectMeizuGalleryCache(Context context, XFile xFile) {
  234. return new GenericImgCollectionDetector(context, xFile, ImageFile.CATEGORY_GALLERY)
  235. .subscribeOn(Schedulers.io())
  236. .onErrorComplete();
  237. }
  238. private static Flowable<ImageFile> detectVivoGalleryCache(Context context, XFile xFile) {
  239. return new GenericImgCollectionDetector(context, xFile, ImageFile.CATEGORY_GALLERY)
  240. .subscribeOn(Schedulers.io())
  241. .onErrorComplete();
  242. }
  243. private static Flowable<ImageFile> detectOppoGalleryCache(Context context, XFile xFile) {
  244. return new GenericImgCollectionDetector(context, xFile, ImageFile.CATEGORY_GALLERY)
  245. .subscribeOn(Schedulers.io())
  246. .onErrorComplete();
  247. }
  248. private static Flowable<ImageFile> detectGalleryCache(Context context, XFile xFile) {
  249. return new GalleryCacheDetector(context, xFile)
  250. .subscribeOn(Schedulers.io())
  251. .onErrorComplete();
  252. }
  253. private static Flowable<ImageFile> detectWechatCache(Context context, XFile xFile) {
  254. return new WechatCacheDetector(context, xFile)
  255. .subscribeOn(Schedulers.io())
  256. .onErrorComplete();
  257. }
  258. private static boolean isAcceptDirectory(XFile file) {
  259. try {
  260. String path = file.getPath();
  261. if (isGalleryCacheDirectory(path)) {
  262. file.setTag(GALLERY_CACHE);
  263. return true;
  264. }
  265. } catch (Exception ignore) {
  266. }
  267. return false;
  268. }
  269. private static boolean isAcceptFile(XFile file) {
  270. try {
  271. if (file.length() == 0) {
  272. return false;
  273. }
  274. } catch (Exception ignore) {
  275. }
  276. try {
  277. String name = file.getName();
  278. if (isImageSuffix(name)) {
  279. file.setTag(IMAGE_SUFFIX);
  280. return true;
  281. }
  282. } catch (Exception ignore) {
  283. }
  284. try {
  285. String path = file.getPath();
  286. if (isWechatCacheFile(path)) {
  287. file.setTag(WECHAT_CACHE);
  288. return true;
  289. }
  290. if (isOppoGalleryCacheFile(path)) {
  291. file.setTag(OPPO_GALLERY_CACHE);
  292. return true;
  293. }
  294. if (isVivoGalleryCacheFile(path)) {
  295. file.setTag(VIVO_GALLERY_CACHE);
  296. return true;
  297. }
  298. if (isXiaomiGalleryCacheFile(path)) {
  299. file.setTag(XIAOMI_GALLERY_CACHE);
  300. return true;
  301. }
  302. if (isMeizuGalleryCacheFile(path)) {
  303. file.setTag(MEIZU_GALLERY_CACHE);
  304. return true;
  305. }
  306. if (isHuaweiGalleryCacheFile(path)) {
  307. file.setTag(HUAWEI_GALLERY_CACHE);
  308. return true;
  309. }
  310. } catch (Exception ignore) {
  311. }
  312. if (hasImgMagic(file)) {
  313. file.setTag(IMG_MAGIC);
  314. return true;
  315. }
  316. return false;
  317. }
  318. private static boolean hasImgMagic(XFile file) {
  319. try (InputStream inputStream = file.newInputStream()) {
  320. byte[] bytes = new byte[8];
  321. if (inputStream.read(bytes) != 8) {
  322. return false;
  323. }
  324. if (bytes[0] == (byte) 0x89 && bytes[1] == (byte) 0x50 && bytes[2] == (byte) 0x4E && bytes[3] == (byte) 0x47
  325. && bytes[4] == (byte) 0x0D && bytes[5] == (byte) 0x0A && bytes[6] == (byte) 0x1A && bytes[7] == (byte) 0x0A) {
  326. // png
  327. return true;
  328. }
  329. boolean hasHeaderMagic = bytes[0] == (byte) 0xFF && bytes[1] == (byte) 0xD8 && bytes[2] == (byte) 0xFF; // jpg header
  330. if (!hasHeaderMagic) {
  331. return false;
  332. }
  333. long skip = inputStream.available() - 2;
  334. if (inputStream.skip(skip) != skip) {
  335. return false;
  336. }
  337. if (inputStream.read(bytes) != 2) {
  338. return false;
  339. }
  340. return bytes[0] == (byte) 0xFF && bytes[1] == (byte) 0xD9;
  341. } catch (Exception ignore) {
  342. }
  343. return false;
  344. }
  345. private static boolean isGalleryCacheDirectory(String path) {
  346. if (TextUtils.isEmpty(path)) {
  347. return false;
  348. }
  349. return path.contains("com.android.gallery3d%2Fcache") ||
  350. path.contains("com.android.gallery3d/cache");
  351. }
  352. private static boolean isWechatCacheFile(String name) {
  353. if (TextUtils.isEmpty(name)) {
  354. return false;
  355. }
  356. return name.contains("com.tencent.mm%2Fcache%2Fimgcache%2Fcache.data") ||
  357. name.contains("com.tencent.mm/cache/imgcache/cache.data");
  358. }
  359. private static boolean isOppoGalleryCacheFile(String path) {
  360. if (TextUtils.isEmpty(path)) {
  361. return false;
  362. }
  363. if (!path.contains("com.coloros.gallery3d%2Fcache") &&
  364. !path.contains("com.coloros.gallery3d/cache")) {
  365. return false;
  366. }
  367. return path.contains("imgcache") || path.contains("screennailcache")
  368. || path.contains("tilecache");
  369. }
  370. private static boolean isVivoGalleryCacheFile(String path) {
  371. if (TextUtils.isEmpty(path)) {
  372. return false;
  373. }
  374. if (!path.contains("com.vivo.gallery%2Fcache") &&
  375. !path.contains("com.vivo.gallery/cache")) {
  376. return false;
  377. }
  378. return path.contains("imgcache") || path.contains("trackthumbnail_cache");
  379. }
  380. private static boolean isXiaomiGalleryCacheFile(String path) {
  381. if (TextUtils.isEmpty(path)) {
  382. return false;
  383. }
  384. if (!path.contains("com.miui.gallery%2Ffiles%2Fgallery_disk_cache") &&
  385. !path.contains("com.miui.gallery/files/gallery_disk_cache")) {
  386. return false;
  387. }
  388. return path.contains("full_size") || path.contains("small_size");
  389. }
  390. private static boolean isMeizuGalleryCacheFile(String path) {
  391. if (TextUtils.isEmpty(path)) {
  392. return false;
  393. }
  394. if (!path.contains("com.meizu.media.gallery%2Fcache") &&
  395. !path.contains("com.meizu.media.gallery/cache")) {
  396. return false;
  397. }
  398. return path.contains("bestPhotoCache") || path.contains("face_thumbnails")
  399. || path.contains("uri_thumbnail_cache");
  400. }
  401. private static boolean isHuaweiGalleryCacheFile(String path) {
  402. if (TextUtils.isEmpty(path)) {
  403. return false;
  404. }
  405. if (!path.contains("com.huawei.photos%2Ffiles%2Fthumbdb") &&
  406. !path.contains("com.huawei.photos/files/thumbdb")) {
  407. return false;
  408. }
  409. return path.endsWith("photoshare.db");
  410. }
  411. private static boolean isImageSuffix(String name) {
  412. if (TextUtils.isEmpty(name)) {
  413. return false;
  414. }
  415. return name.endsWith(".jpg") || name.endsWith(".jpeg") || name.endsWith(".png")
  416. || name.endsWith(".gif") || name.endsWith(".bmp") || name.endsWith(".webp")
  417. || name.endsWith(".tiff") || name.endsWith(".psd") || name.endsWith(".svg")
  418. || name.endsWith(".raw") || name.endsWith(".heif") || name.endsWith(".indd");
  419. }
  420. private static boolean bytes2File(byte[] bytes, File file) {
  421. try (FileOutputStream fileOutputStream = new FileOutputStream(file)) {
  422. fileOutputStream.write(bytes);
  423. fileOutputStream.flush();
  424. return true;
  425. } catch (Exception e) {
  426. e.printStackTrace();
  427. }
  428. return false;
  429. }
  430. private static boolean bytes2File(List<Byte> bytes, File file) {
  431. try (FileOutputStream fileOutputStream = new FileOutputStream(file)) {
  432. for (Byte aByte : bytes) {
  433. fileOutputStream.write(aByte);
  434. }
  435. fileOutputStream.flush();
  436. return true;
  437. } catch (Exception e) {
  438. e.printStackTrace();
  439. }
  440. return false;
  441. }
  442. private static File getDetectedCacheDir(Context context, String domain) {
  443. File cacheDir;
  444. if (Objects.equals(Environment.getExternalStorageState(), Environment.MEDIA_MOUNTED)
  445. && Environment.getExternalStorageDirectory().canWrite()) {
  446. cacheDir = context.getExternalCacheDir();
  447. } else {
  448. cacheDir = context.getCacheDir();
  449. }
  450. File detectedCacheDir = new File(cacheDir, CryptoUtils.HASH.md5(domain));
  451. if (!detectedCacheDir.exists()) {
  452. detectedCacheDir.mkdirs();
  453. }
  454. return detectedCacheDir;
  455. }
  456. private static void clearDetectedCache(Context context, String domain) {
  457. File detectedCacheDir = getDetectedCacheDir(context, domain);
  458. try {
  459. clearDir(detectedCacheDir);
  460. } catch (Exception e) {
  461. e.printStackTrace();
  462. }
  463. }
  464. private static void clearDir(File dir) {
  465. if (dir == null || !dir.exists()) {
  466. return;
  467. }
  468. File[] files = dir.listFiles();
  469. if (files == null || files.length == 0) {
  470. dir.delete();
  471. return;
  472. }
  473. for (File file : files) {
  474. if (file.isDirectory()) {
  475. clearDir(file);
  476. } else {
  477. file.delete();
  478. }
  479. }
  480. dir.delete();
  481. }
  482. public static class ImageFile extends BaseObservable {
  483. public static int CATEGORY_UNKNOWN = -1;
  484. public static int CATEGORY_OTHER = 0;
  485. public static int CATEGORY_QQ = 1;
  486. public static int CATEGORY_WECHAT = 2;
  487. public static int CATEGORY_GALLERY = 3;
  488. private final XFile xFile;
  489. private String name;
  490. private long size;
  491. private String sizeDescribe;
  492. private Uri uri;
  493. private String path;
  494. private int category;
  495. private String fileType;
  496. private boolean isCheck;
  497. private long lastModified;
  498. public ImageFile(XFile xFile) {
  499. this(xFile, CATEGORY_UNKNOWN);
  500. }
  501. public ImageFile(XFile xFile, int category) {
  502. this.category = category;
  503. this.xFile = xFile;
  504. try {
  505. this.name = xFile.getName();
  506. } catch (Exception ignore) {
  507. }
  508. try {
  509. this.size = xFile.length();
  510. } catch (Exception ignore) {
  511. }
  512. try {
  513. this.uri = xFile.getUri();
  514. } catch (Exception ignore) {
  515. }
  516. try {
  517. this.path = xFile.getPath();
  518. } catch (Exception ignore) {
  519. }
  520. try {
  521. this.lastModified = xFile.lastModified();
  522. } catch (Exception ignore) {
  523. }
  524. this.fileType = FileUtil.getImageFileType(name);
  525. this.sizeDescribe = FileUtil.formatShortBytes(this.size);
  526. }
  527. public String getPath() {
  528. return path;
  529. }
  530. public long getLastModified() {
  531. return lastModified;
  532. }
  533. public String getSizeDescribe() {
  534. return sizeDescribe;
  535. }
  536. public String getFileType() {
  537. return fileType;
  538. }
  539. public String getName() {
  540. return name;
  541. }
  542. public long getSize() {
  543. return size;
  544. }
  545. public Uri getUri() {
  546. return uri;
  547. }
  548. @Bindable
  549. public boolean isCheck() {
  550. return isCheck;
  551. }
  552. public void setCheck(boolean check) {
  553. isCheck = check;
  554. notifyPropertyChanged(BR.check);
  555. }
  556. public InputStream newInputStream() throws Exception {
  557. return xFile.newInputStream();
  558. }
  559. public boolean delete() throws Exception {
  560. return xFile.delete();
  561. }
  562. public int getCategory() {
  563. if (category != CATEGORY_UNKNOWN) {
  564. return category;
  565. }
  566. if (isGallery()) {
  567. return CATEGORY_GALLERY;
  568. } else if (isWechat()) {
  569. return CATEGORY_WECHAT;
  570. } else if (isQQ()) {
  571. return CATEGORY_QQ;
  572. } else {
  573. return CATEGORY_OTHER;
  574. }
  575. }
  576. private boolean isQQ() {
  577. if (TextUtils.isEmpty(path)) {
  578. return false;
  579. }
  580. return path.contains("com.tencent.mobileqq") || path.contains("com.tencent.tim");
  581. }
  582. private boolean isWechat() {
  583. return !TextUtils.isEmpty(path) && path.contains("com.tencent.mm");
  584. }
  585. private boolean isGallery() {
  586. return !TextUtils.isEmpty(path) && (
  587. path.contains("com.android.gallery3d") ||
  588. path.contains("com.coloros.gallery3d") ||
  589. path.contains("com.vivo.gallery") ||
  590. path.contains("com.miui.gallery") ||
  591. path.contains("com.meizu.media.gallery") ||
  592. path.contains("com.oppo.gallery3d") ||
  593. path.contains("com.android.gallery") ||
  594. path.contains("com.huawei.photos") ||
  595. path.contains("DCIM") ||
  596. path.contains("Pictures") ||
  597. path.contains(".RecycleBin") ||
  598. path.contains(".photoShare")
  599. );
  600. }
  601. }
  602. private static class WechatCacheDetector extends Flowable<ImageFile> {
  603. private static final String CACHE_DOMAIN = "wechat_cache_detector";
  604. private final XFile xFile;
  605. private final Context context;
  606. public WechatCacheDetector(Context context, XFile xFile) {
  607. this.context = context;
  608. this.xFile = xFile;
  609. }
  610. @Override
  611. protected void subscribeActual(@NonNull Subscriber<? super ImageFile> subscriber) {
  612. long lastModified;
  613. try {
  614. lastModified = xFile.lastModified();
  615. } catch (Exception e) {
  616. subscriber.onError(e);
  617. return;
  618. }
  619. if (checkDetectedCache(context, lastModified, subscriber)) {
  620. subscriber.onComplete();
  621. return;
  622. } else {
  623. clearDetectedCache(context, CACHE_DOMAIN);
  624. }
  625. File detectedCacheDir = getDetectedCacheDir(context, CACHE_DOMAIN);
  626. detectedCacheDir = new File(detectedCacheDir, CryptoUtils.HASH.md5(String.valueOf(lastModified)));
  627. if (!detectedCacheDir.exists()) {
  628. detectedCacheDir.mkdirs();
  629. }
  630. try (InputStream inputStream = xFile.newInputStream()) {
  631. ArrayList<Byte> imageBytes = new ArrayList<>();
  632. byte[] buffer = new byte[2048];
  633. int read;
  634. while ((read = inputStream.read(buffer)) != -1) {
  635. for (int i = 0; i < read; i++) {
  636. byte b = buffer[i];
  637. imageBytes.add(b);
  638. if (imageBytes.size() < 2) {
  639. continue;
  640. }
  641. if (imageBytes.size() == 2) {
  642. if (imageBytes.get(0) != (byte) 0xFF || imageBytes.get(1) != (byte) 0xD8) {
  643. imageBytes.remove(0);
  644. }
  645. continue;
  646. }
  647. if (i == read - 1 && inputStream.available() == 0) {
  648. if (imageBytes.get(imageBytes.size() - 2) == (byte) 0xFF && imageBytes.get(imageBytes.size() - 1) == (byte) 0xD9) {
  649. File cache = new File(detectedCacheDir, UUID.randomUUID().toString());
  650. if (cache.createNewFile() && bytes2File(imageBytes, cache)) {
  651. subscriber.onNext(new ImageFile(new XPathFile(context, cache), ImageFile.CATEGORY_WECHAT));
  652. }
  653. }
  654. imageBytes.clear();
  655. } else if (imageBytes.size() >= 6) {
  656. if (imageBytes.get(imageBytes.size() - 1) == (byte) 0xD8
  657. && imageBytes.get(imageBytes.size() - 2) == (byte) 0xFF
  658. && imageBytes.get(imageBytes.size() - 3) == (byte) 0xD9
  659. && imageBytes.get(imageBytes.size() - 4) == (byte) 0xFF
  660. ) {
  661. imageBytes.remove(imageBytes.size() - 1);
  662. imageBytes.remove(imageBytes.size() - 1);
  663. File cache = new File(detectedCacheDir, UUID.randomUUID().toString());
  664. if (cache.createNewFile() && bytes2File(imageBytes, cache)) {
  665. subscriber.onNext(new ImageFile(new XPathFile(context, cache), ImageFile.CATEGORY_WECHAT));
  666. }
  667. imageBytes.clear();
  668. imageBytes.add((byte) 0xFF);
  669. imageBytes.add((byte) 0xD8);
  670. }
  671. }
  672. }
  673. }
  674. subscriber.onComplete();
  675. } catch (Exception e) {
  676. subscriber.onError(e);
  677. }
  678. }
  679. private boolean checkDetectedCache(Context context, long lastModified, Subscriber<? super ImageFile> subscriber) {
  680. File detectedCacheDir = getDetectedCacheDir(context, CACHE_DOMAIN);
  681. File targetCaches = new File(detectedCacheDir, CryptoUtils.HASH.md5(String.valueOf(lastModified)));
  682. File[] files = targetCaches.exists() && targetCaches.isDirectory() ? targetCaches.listFiles() : null;
  683. if (files != null && files.length > 0) {
  684. for (File file : files) {
  685. subscriber.onNext(new ImageFile(new XPathFile(this.context, file), ImageFile.CATEGORY_WECHAT));
  686. }
  687. return true;
  688. }
  689. return false;
  690. }
  691. }
  692. private static class GalleryCacheDetector extends Flowable<ImageFile> {
  693. private static final String CACHE_DOMAIN = "gallery_cache_detector";
  694. private static final int MAGIC_INDEX_FILE = 0xB3273030;
  695. private static final int MAGIC_DATA_FILE = 0xBD248510;
  696. // index header offset
  697. private static final int IH_MAGIC = 0;
  698. private static final int IH_MAX_ENTRIES = 4;
  699. private static final int IH_MAX_BYTES = 8;
  700. private static final int IH_ACTIVE_REGION = 12;
  701. private static final int IH_ACTIVE_ENTRIES = 16;
  702. private static final int IH_ACTIVE_BYTES = 20;
  703. private static final int IH_CHECKSUM = 28;
  704. private static final int INDEX_HEADER_SIZE = 32;
  705. private static final int DATA_HEADER_SIZE = 4;
  706. // blob header offset
  707. private static final int BH_KEY = 0;
  708. private static final int BH_CHECKSUM = 8;
  709. private static final int BH_OFFSET = 12;
  710. private static final int BH_LENGTH = 16;
  711. private static final int BLOB_HEADER_SIZE = 20;
  712. private final XFile galleryCacheDir;
  713. private final byte[] indexHeader;
  714. private final byte[] blobHeader;
  715. private final Adler32 mAdler32 = new Adler32();
  716. private final Context context;
  717. private int mMaxEntries;
  718. private int mMaxBytes;
  719. private int mActiveRegion;
  720. private int mActiveBytes;
  721. private FileChannel mIndexChannel;
  722. private MappedByteBuffer mIndexBuffer;
  723. private RandomAccessFile mIndexFile;
  724. private RandomAccessFile mDataFile0;
  725. private RandomAccessFile mDataFile1;
  726. private RandomAccessFile mActiveDataFile;
  727. private int mActiveHashStart;
  728. private File indexTemp;
  729. private File data0Temp;
  730. private File data1Temp;
  731. public GalleryCacheDetector(Context context, XFile galleryCacheDir) {
  732. this.context = context;
  733. this.galleryCacheDir = galleryCacheDir;
  734. this.indexHeader = new byte[INDEX_HEADER_SIZE];
  735. this.blobHeader = new byte[BLOB_HEADER_SIZE];
  736. }
  737. @Override
  738. protected void subscribeActual(@NonNull Subscriber<? super ImageFile> subscriber) {
  739. XFile[] xFiles;
  740. try {
  741. xFiles = galleryCacheDir.listFiles();
  742. } catch (Exception e) {
  743. subscriber.onError(e);
  744. return;
  745. }
  746. if (xFiles == null || xFiles.length == 0) {
  747. subscriber.onComplete();
  748. return;
  749. }
  750. XFile indexFile = null;
  751. XFile dataFile0 = null;
  752. XFile dataFile1 = null;
  753. for (XFile xFile : xFiles) {
  754. try {
  755. String name = xFile.getName();
  756. if (name.endsWith(".idx")) {
  757. indexFile = xFile;
  758. } else if (name.endsWith(".0")) {
  759. dataFile0 = xFile;
  760. } else if (name.endsWith(".1")) {
  761. dataFile1 = xFile;
  762. }
  763. } catch (Exception e) {
  764. subscriber.onError(e);
  765. }
  766. }
  767. if (indexFile == null || dataFile0 == null || dataFile1 == null) {
  768. subscriber.onComplete();
  769. return;
  770. }
  771. doDetect(indexFile, dataFile0, dataFile1, subscriber);
  772. }
  773. private void doDetect(XFile indexFile, XFile dataFile0, XFile dataFile1, Subscriber<? super ImageFile> subscriber) {
  774. try {
  775. long lastModified;
  776. try {
  777. lastModified = indexFile.lastModified();
  778. } catch (Exception e) {
  779. subscriber.onError(e);
  780. return;
  781. }
  782. if (checkDetectedCache(context, lastModified, subscriber)) {
  783. subscriber.onComplete();
  784. return;
  785. } else {
  786. clearDetectedCache(context, CACHE_DOMAIN);
  787. }
  788. File detectedCacheDir = getDetectedCacheDir(context, CACHE_DOMAIN);
  789. detectedCacheDir = new File(detectedCacheDir, CryptoUtils.HASH.md5(String.valueOf(lastModified)));
  790. if (!detectedCacheDir.exists()) {
  791. detectedCacheDir.mkdirs();
  792. }
  793. loadIndex(indexFile, dataFile0, dataFile1);
  794. for (int i = 0; i < mMaxEntries; i++) {
  795. int offset = mActiveHashStart + i * 12;
  796. long candidateKey = mIndexBuffer.getLong(offset);
  797. try {
  798. LookupRequest lookupRequest = new LookupRequest(candidateKey);
  799. if (!lookup(lookupRequest)) {
  800. continue;
  801. }
  802. byte[] lookup = lookupRequest.buffer;
  803. if (lookup == null) {
  804. continue;
  805. }
  806. byte[] cropData = cropLookup(lookup);
  807. if (cropData == null) {
  808. continue;
  809. }
  810. File cache = new File(detectedCacheDir, UUID.randomUUID().toString());
  811. if (cache.createNewFile() && bytes2File(cropData, cache)) {
  812. subscriber.onNext(new ImageFile(new XPathFile(context, cache), ImageFile.CATEGORY_GALLERY));
  813. }
  814. } catch (Exception ignore) {
  815. }
  816. }
  817. subscriber.onComplete();
  818. } catch (Exception e) {
  819. subscriber.onError(e);
  820. } finally {
  821. closeAll();
  822. deleteTempFiles();
  823. }
  824. }
  825. private boolean checkDetectedCache(Context context, long lastModified, Subscriber<? super ImageFile> subscriber) {
  826. File detectedCacheDir = getDetectedCacheDir(context, CACHE_DOMAIN);
  827. File targetCaches = new File(detectedCacheDir, CryptoUtils.HASH.md5(String.valueOf(lastModified)));
  828. File[] files = targetCaches.exists() && targetCaches.isDirectory() ? targetCaches.listFiles() : null;
  829. if (files != null && files.length > 0) {
  830. for (File file : files) {
  831. subscriber.onNext(new ImageFile(new XPathFile(this.context, file), ImageFile.CATEGORY_GALLERY));
  832. }
  833. return true;
  834. }
  835. return false;
  836. }
  837. private byte[] cropLookup(byte[] lookup) {
  838. for (int i = 0; i < lookup.length; i++) {
  839. if (lookup[i] == (byte) 0xFF && i + 1 < lookup.length && lookup[i + 1] == (byte) 0xD8) {
  840. return crop(lookup, i);
  841. }
  842. }
  843. return null;
  844. }
  845. private byte[] crop(byte[] lookup, int i) {
  846. byte[] crop = new byte[lookup.length - i];
  847. System.arraycopy(lookup, i, crop, 0, crop.length);
  848. return crop;
  849. }
  850. private void loadIndex(XFile indexFile, XFile dataFile0, XFile dataFile1) throws Exception {
  851. checkFileValid(indexFile, dataFile0, dataFile1);
  852. try (InputStream idxIs = indexFile.newInputStream();
  853. InputStream data0Is = dataFile0.newInputStream();
  854. InputStream data1Is = dataFile1.newInputStream()
  855. ) {
  856. indexTemp = createTempFile("index.temp", idxIs);
  857. mIndexFile = new RandomAccessFile(indexTemp, "rw");
  858. data0Temp = createTempFile("data0.temp", data0Is);
  859. mDataFile0 = new RandomAccessFile(data0Temp, "rw");
  860. data1Temp = createTempFile("data1.temp", data1Is);
  861. mDataFile1 = new RandomAccessFile(data1Temp, "rw");
  862. // Map index file to memory
  863. mIndexChannel = mIndexFile.getChannel();
  864. mIndexBuffer = mIndexChannel.map(FileChannel.MapMode.READ_WRITE,
  865. 0, mIndexFile.length());
  866. mIndexBuffer.order(ByteOrder.LITTLE_ENDIAN);
  867. setActiveVariables();
  868. }
  869. }
  870. private void setActiveVariables() throws Exception {
  871. mActiveDataFile = (mActiveRegion == 0) ? mDataFile0 : mDataFile1;
  872. mActiveDataFile.setLength(mActiveBytes);
  873. mActiveDataFile.seek(mActiveBytes);
  874. mActiveHashStart = INDEX_HEADER_SIZE;
  875. if (mActiveRegion != 0) {
  876. mActiveHashStart += mMaxEntries * 12;
  877. }
  878. }
  879. private void checkFileValid(XFile indexFile, XFile dataFile0, XFile dataFile1) throws Exception {
  880. byte[] buf = indexHeader;
  881. try (InputStream inputStream = indexFile.newInputStream()) {
  882. if (inputStream.read(buf) != INDEX_HEADER_SIZE) {
  883. throw new Exception("cannot read header");
  884. }
  885. if (readInt(buf, IH_MAGIC) != MAGIC_INDEX_FILE) {
  886. throw new Exception("cannot read header magic");
  887. }
  888. }
  889. mMaxEntries = readInt(buf, IH_MAX_ENTRIES);
  890. mMaxBytes = readInt(buf, IH_MAX_BYTES);
  891. mActiveRegion = readInt(buf, IH_ACTIVE_REGION);
  892. int mActiveEntries = readInt(buf, IH_ACTIVE_ENTRIES);
  893. mActiveBytes = readInt(buf, IH_ACTIVE_BYTES);
  894. int sum = readInt(buf, IH_CHECKSUM);
  895. if (checkSum(buf, 0, IH_CHECKSUM) != sum) {
  896. throw new Exception("header checksum does not match");
  897. }
  898. // Sanity check
  899. if (mMaxEntries <= 0) {
  900. throw new Exception("invalid max entries");
  901. }
  902. if (mMaxBytes <= 0) {
  903. throw new Exception("invalid max bytes");
  904. }
  905. if (mActiveRegion != 0 && mActiveRegion != 1) {
  906. throw new Exception("invalid active region");
  907. }
  908. if (mActiveEntries < 0 || mActiveEntries > mMaxEntries) {
  909. throw new Exception("invalid active entries");
  910. }
  911. if (mActiveBytes < DATA_HEADER_SIZE || mActiveBytes > mMaxBytes) {
  912. throw new Exception("invalid active bytes");
  913. }
  914. if (indexFile.length() != INDEX_HEADER_SIZE + mMaxEntries * 12 * 2L) {
  915. throw new Exception("invalid index file length");
  916. }
  917. // Make sure data file has magic
  918. byte[] magic = new byte[4];
  919. try (InputStream data0Is = dataFile0.newInputStream()) {
  920. if (data0Is.read(magic) != 4) {
  921. throw new Exception("cannot read data file magic");
  922. }
  923. }
  924. if (readInt(magic, 0) != MAGIC_DATA_FILE) {
  925. throw new Exception("invalid data file magic");
  926. }
  927. try (InputStream data1Is = dataFile1.newInputStream()) {
  928. if (data1Is.read(magic) != 4) {
  929. throw new Exception("cannot read data file magic");
  930. }
  931. }
  932. if (readInt(magic, 0) != MAGIC_DATA_FILE) {
  933. throw new Exception("invalid data file magic");
  934. }
  935. }
  936. private File createTempFile(String fileName, InputStream inputStream) throws Exception {
  937. File tempFile = new File(context.getCacheDir(), fileName);
  938. if (tempFile.exists()) {
  939. tempFile.delete();
  940. }
  941. if (!tempFile.createNewFile()) {
  942. throw new Exception("cannot create temp file");
  943. }
  944. try (OutputStream outputStream = new FileOutputStream(tempFile)) {
  945. copyStream(inputStream, outputStream);
  946. }
  947. return tempFile;
  948. }
  949. public boolean lookup(LookupRequest req) throws IOException {
  950. if (lookupInternal(req.key, mActiveHashStart)) {
  951. return getBlob(mActiveDataFile, mFileOffset, req);
  952. }
  953. return false;
  954. }
  955. private int mFileOffset;
  956. private boolean lookupInternal(long key, int hashStart) {
  957. int slot = (int) (key % mMaxEntries);
  958. if (slot < 0) slot += mMaxEntries;
  959. int slotBegin = slot;
  960. while (true) {
  961. int offset = hashStart + slot * 12;
  962. long candidateKey = mIndexBuffer.getLong(offset);
  963. int candidateOffset = mIndexBuffer.getInt(offset + 8);
  964. if (candidateOffset == 0) {
  965. return false;
  966. } else if (candidateKey == key) {
  967. mFileOffset = candidateOffset;
  968. return true;
  969. } else {
  970. if (++slot >= mMaxEntries) {
  971. slot = 0;
  972. }
  973. if (slot == slotBegin) {
  974. mIndexBuffer.putInt(hashStart + slot * 12 + 8, 0);
  975. }
  976. }
  977. }
  978. }
  979. private boolean getBlob(RandomAccessFile file, int offset,
  980. LookupRequest req) throws IOException {
  981. byte[] header = blobHeader;
  982. long oldPosition = file.getFilePointer();
  983. try {
  984. file.seek(offset);
  985. if (file.read(header) != BLOB_HEADER_SIZE) {
  986. return false;
  987. }
  988. long blobKey = readLong(header, BH_KEY);
  989. if (blobKey == 0) {
  990. return false; // This entry has been cleared.
  991. }
  992. if (blobKey != req.key) {
  993. return false;
  994. }
  995. int sum = readInt(header, BH_CHECKSUM);
  996. int blobOffset = readInt(header, BH_OFFSET);
  997. if (blobOffset != offset) {
  998. return false;
  999. }
  1000. int length = readInt(header, BH_LENGTH);
  1001. if (length < 0 || length > mMaxBytes - offset - BLOB_HEADER_SIZE) {
  1002. return false;
  1003. }
  1004. if (req.buffer == null || req.buffer.length < length) {
  1005. req.buffer = new byte[length];
  1006. }
  1007. byte[] blob = req.buffer;
  1008. req.length = length;
  1009. if (file.read(blob, 0, length) != length) {
  1010. return false;
  1011. }
  1012. return checkSum(blob, 0, length) == sum;
  1013. } catch (Throwable t) {
  1014. return false;
  1015. } finally {
  1016. file.seek(oldPosition);
  1017. }
  1018. }
  1019. static int readInt(byte[] buf, int offset) {
  1020. return (buf[offset] & 0xff)
  1021. | ((buf[offset + 1] & 0xff) << 8)
  1022. | ((buf[offset + 2] & 0xff) << 16)
  1023. | ((buf[offset + 3] & 0xff) << 24);
  1024. }
  1025. static long readLong(byte[] buf, int offset) {
  1026. long result = buf[offset + 7] & 0xff;
  1027. for (int i = 6; i >= 0; i--) {
  1028. result = (result << 8) | (buf[offset + i] & 0xff);
  1029. }
  1030. return result;
  1031. }
  1032. int checkSum(byte[] data, int offset, int nbytes) {
  1033. mAdler32.reset();
  1034. mAdler32.update(data, offset, nbytes);
  1035. return (int) mAdler32.getValue();
  1036. }
  1037. private void copyStream(InputStream is, OutputStream os) throws Exception {
  1038. byte[] buf = new byte[2048];
  1039. int n;
  1040. while ((n = is.read(buf)) > 0) {
  1041. os.write(buf, 0, n);
  1042. }
  1043. os.flush();
  1044. }
  1045. private void closeAll() {
  1046. closeSilently(mIndexChannel);
  1047. closeSilently(mIndexFile);
  1048. closeSilently(mDataFile0);
  1049. closeSilently(mDataFile1);
  1050. }
  1051. private void closeSilently(Closeable c) {
  1052. if (c == null) return;
  1053. try {
  1054. c.close();
  1055. } catch (Throwable t) {
  1056. // do nothing
  1057. }
  1058. }
  1059. private void deleteTempFiles() {
  1060. deleteSilently(indexTemp);
  1061. deleteSilently(data0Temp);
  1062. deleteSilently(data1Temp);
  1063. }
  1064. private void deleteSilently(File tempFile) {
  1065. if (tempFile == null) {
  1066. return;
  1067. }
  1068. try {
  1069. if (tempFile.exists()) {
  1070. tempFile.delete();
  1071. }
  1072. } catch (Throwable t) {
  1073. // do nothing
  1074. }
  1075. }
  1076. public static class LookupRequest {
  1077. public long key; // input: the key to find
  1078. public byte[] buffer; // input/output: the buffer to store the blob
  1079. public int length; // output: the length of the blob
  1080. public LookupRequest(long key) {
  1081. this.key = key;
  1082. }
  1083. }
  1084. }
  1085. private static class GenericImgCollectionDetector extends Flowable<ImageFile> {
  1086. private final int category;
  1087. private String CACHE_DOMAIN = "generic_img_collection_detector";
  1088. private final Context context;
  1089. private final XFile xFile;
  1090. public GenericImgCollectionDetector(Context context, XFile xFile, int category) {
  1091. this.context = context;
  1092. this.xFile = xFile;
  1093. this.category = category;
  1094. }
  1095. @Override
  1096. protected void subscribeActual(@NonNull Subscriber<? super ImageFile> subscriber) {
  1097. long lastModified;
  1098. try {
  1099. lastModified = xFile.lastModified();
  1100. CACHE_DOMAIN += xFile.getName();
  1101. } catch (Exception e) {
  1102. subscriber.onError(e);
  1103. return;
  1104. }
  1105. if (checkDetectedCache(context, lastModified, subscriber)) {
  1106. subscriber.onComplete();
  1107. return;
  1108. } else {
  1109. clearDetectedCache(context, CACHE_DOMAIN);
  1110. }
  1111. File detectedCacheDir = getDetectedCacheDir(context, CACHE_DOMAIN);
  1112. detectedCacheDir = new File(detectedCacheDir, CryptoUtils.HASH.md5(String.valueOf(lastModified)));
  1113. if (!detectedCacheDir.exists()) {
  1114. detectedCacheDir.mkdirs();
  1115. }
  1116. try (InputStream inputStream = xFile.newInputStream()) {
  1117. ArrayList<Byte> imageBytes = new ArrayList<>();
  1118. byte[] buffer = new byte[2048];
  1119. int read;
  1120. while ((read = inputStream.read(buffer)) != -1) {
  1121. for (int i = 0; i < read; i++) {
  1122. byte b = buffer[i];
  1123. imageBytes.add(b);
  1124. if (imageBytes.size() < 3) {
  1125. continue;
  1126. }
  1127. if (imageBytes.size() == 3) {
  1128. if (imageBytes.get(0) != (byte) 0xFF || imageBytes.get(1) != (byte) 0xD8 || imageBytes.get(2) != (byte) 0xFF) {
  1129. imageBytes.remove(0);
  1130. }
  1131. continue;
  1132. }
  1133. if (i == read - 1 && inputStream.available() == 0) {
  1134. if (imageBytes.get(imageBytes.size() - 2) == (byte) 0xFF && imageBytes.get(imageBytes.size() - 1) == (byte) 0xD9) {
  1135. File cache = new File(detectedCacheDir, UUID.randomUUID().toString());
  1136. if (cache.createNewFile() && bytes2File(imageBytes, cache)) {
  1137. subscriber.onNext(new ImageFile(new XPathFile(context, cache), category));
  1138. }
  1139. }
  1140. imageBytes.clear();
  1141. } else if (imageBytes.size() >= 5) {
  1142. if (imageBytes.get(imageBytes.size() - 1) == (byte) 0xD9
  1143. && imageBytes.get(imageBytes.size() - 2) == (byte) 0xFF
  1144. ) {
  1145. File cache = new File(detectedCacheDir, UUID.randomUUID().toString());
  1146. if (cache.createNewFile() && bytes2File(imageBytes, cache)) {
  1147. subscriber.onNext(new ImageFile(new XPathFile(context, cache), category));
  1148. }
  1149. imageBytes.clear();
  1150. }
  1151. }
  1152. }
  1153. }
  1154. subscriber.onComplete();
  1155. } catch (Exception e) {
  1156. subscriber.onError(e);
  1157. }
  1158. }
  1159. private boolean checkDetectedCache(Context context, long lastModified, Subscriber<? super ImageFile> subscriber) {
  1160. File detectedCacheDir = getDetectedCacheDir(context, CACHE_DOMAIN);
  1161. File targetCaches = new File(detectedCacheDir, CryptoUtils.HASH.md5(String.valueOf(lastModified)));
  1162. File[] files = targetCaches.exists() && targetCaches.isDirectory() ? targetCaches.listFiles() : null;
  1163. if (files != null && files.length > 0) {
  1164. for (File file : files) {
  1165. subscriber.onNext(new ImageFile(new XPathFile(this.context, file), category));
  1166. }
  1167. return true;
  1168. }
  1169. return false;
  1170. }
  1171. }
  1172. private static class HuaweiGalleryCacheDetector extends Flowable<ImageFile> {
  1173. private static final String CACHE_DOMAIN = "huawei_gallery_cache_detector";
  1174. private final Context context;
  1175. private final XFile dbFile;
  1176. public HuaweiGalleryCacheDetector(Context context, XFile dbFile) {
  1177. this.context = context;
  1178. this.dbFile = dbFile;
  1179. }
  1180. @Override
  1181. protected void subscribeActual(@NonNull Subscriber<? super ImageFile> subscriber) {
  1182. long lastModified;
  1183. try {
  1184. lastModified = dbFile.lastModified();
  1185. } catch (Exception e) {
  1186. subscriber.onError(e);
  1187. return;
  1188. }
  1189. if (checkDetectedCache(context, lastModified, subscriber)) {
  1190. subscriber.onComplete();
  1191. return;
  1192. } else {
  1193. clearDetectedCache(context, CACHE_DOMAIN);
  1194. }
  1195. File detectedCacheDir = getDetectedCacheDir(context, CACHE_DOMAIN);
  1196. detectedCacheDir = new File(detectedCacheDir, CryptoUtils.HASH.md5(String.valueOf(lastModified)));
  1197. if (!detectedCacheDir.exists()) {
  1198. detectedCacheDir.mkdirs();
  1199. }
  1200. File dbTempFile;
  1201. try {
  1202. dbTempFile = createDbTempFile(detectedCacheDir);
  1203. } catch (Exception e) {
  1204. subscriber.onError(e);
  1205. return;
  1206. }
  1207. try (SQLiteDatabase sqLiteDatabase = SQLiteDatabase.openDatabase(dbTempFile.getPath(), null, SQLiteDatabase.OPEN_READONLY);
  1208. Cursor cursor = sqLiteDatabase.rawQuery("select * from general_kv", null)
  1209. ) {
  1210. int vIndex = cursor.getColumnIndex("v");
  1211. if (vIndex == -1) {
  1212. subscriber.onComplete();
  1213. return;
  1214. }
  1215. while (cursor.moveToNext()) {
  1216. byte[] data = cursor.getBlob(vIndex);
  1217. if (data == null || data.length == 0) {
  1218. continue;
  1219. }
  1220. File cache = new File(detectedCacheDir, UUID.randomUUID().toString());
  1221. if (cache.createNewFile() && bytes2File(data, cache)) {
  1222. subscriber.onNext(new ImageFile(new XPathFile(context, cache), ImageFile.CATEGORY_GALLERY));
  1223. }
  1224. }
  1225. subscriber.onComplete();
  1226. } catch (Exception e) {
  1227. subscriber.onError(e);
  1228. } finally {
  1229. if (dbTempFile != null && dbTempFile.exists()) {
  1230. dbTempFile.delete();
  1231. }
  1232. }
  1233. }
  1234. private File createDbTempFile(File detectedCacheDir) throws Exception {
  1235. File dbTempFile = new File(detectedCacheDir, "huawei_gallery_cache_detector.db");
  1236. if (dbTempFile.exists()) {
  1237. dbTempFile.delete();
  1238. }
  1239. try (InputStream inputStream = dbFile.newInputStream();
  1240. OutputStream outputStream = new FileOutputStream(dbTempFile)
  1241. ) {
  1242. byte[] buffer = new byte[2048];
  1243. int read;
  1244. while ((read = inputStream.read(buffer)) != -1) {
  1245. outputStream.write(buffer, 0, read);
  1246. }
  1247. outputStream.flush();
  1248. return dbTempFile;
  1249. }
  1250. }
  1251. private boolean checkDetectedCache(Context context, long lastModified, Subscriber<? super ImageFile> subscriber) {
  1252. File detectedCacheDir = getDetectedCacheDir(context, CACHE_DOMAIN);
  1253. File targetCaches = new File(detectedCacheDir, CryptoUtils.HASH.md5(String.valueOf(lastModified)));
  1254. File[] files = targetCaches.exists() && targetCaches.isDirectory() ? targetCaches.listFiles() : null;
  1255. if (files != null && files.length > 0) {
  1256. for (File file : files) {
  1257. if (file.getName().endsWith(".db")) {
  1258. continue;
  1259. }
  1260. subscriber.onNext(new ImageFile(new XPathFile(this.context, file), ImageFile.CATEGORY_GALLERY));
  1261. }
  1262. return true;
  1263. }
  1264. return false;
  1265. }
  1266. }
  1267. }