FacialLoginActivity.kt 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. package com.example.chemical.ui.login
  2. import android.os.*
  3. import android.util.Log
  4. import android.view.LayoutInflater
  5. import android.view.MotionEvent
  6. import android.view.View
  7. import android.widget.TextView
  8. import com.blankj.utilcode.util.AppUtils
  9. import com.blankj.utilcode.util.LogUtils
  10. import com.bumptech.glide.Glide
  11. import com.bumptech.glide.load.engine.DiskCacheStrategy
  12. import com.bumptech.glide.request.RequestOptions
  13. import com.example.chemical.ChemicalApp
  14. import com.example.chemical.R
  15. import com.example.chemical.comm.Constants
  16. import com.example.chemical.databinding.ActivityFacialLoginBinding
  17. import com.example.chemical.ui.common.BaseCountDownActivity
  18. import com.example.chemical.utils.HandlerUtil
  19. import com.example.chemical.utils.MediaPlayerHelper
  20. import com.example.chemical.utils.UiManager
  21. import com.example.chemical.weidith.AuthenticationDialog
  22. import com.example.chemical.weidith.CustomDialog
  23. import com.rc.core.log.RcLog
  24. import com.rc.httpcore.HttpClient
  25. import com.rc.httpcore.HttpConfig
  26. import com.rc.httpcore.client.ApiRepository
  27. import com.rc.httpcore.exception.NetException
  28. import com.rc.httpcore.vo.request.FaceCompareReq
  29. import io.fotoapparat.Fotoapparat
  30. import io.fotoapparat.facedetector.processor.FaceDetectorProcessor
  31. import io.fotoapparat.log.fileLogger
  32. import io.fotoapparat.log.logcat
  33. import io.fotoapparat.log.loggers
  34. import io.fotoapparat.selector.back
  35. import io.fotoapparat.selector.front
  36. import retrofit2.HttpException
  37. import java.io.File
  38. import java.net.ConnectException
  39. import java.net.SocketTimeoutException
  40. import java.text.SimpleDateFormat
  41. import java.util.*
  42. /**
  43. * 人脸登录
  44. */
  45. class FacialLoginActivity : BaseCountDownActivity<ActivityFacialLoginBinding>() {
  46. private lateinit var mFotoapparat: Fotoapparat
  47. // private lateinit var mCountDownTimer: CountDownTimer
  48. //人脸验证时间
  49. private val totalTimeInMillis: Long = 30 * 1000 // 总时常
  50. private lateinit var faceList: String
  51. private val handlerBack = Handler(Looper.getMainLooper())
  52. private var timeLeftInSeconds = 2
  53. private var mTvView: TextView? = null
  54. private var mDialogsAut: AuthenticationDialog? = null
  55. private val countHandler = Handler(Looper.getMainLooper()) //整个页面 60秒后 直接关闭
  56. override fun createViewBinding() = ActivityFacialLoginBinding.inflate(LayoutInflater.from(this))
  57. override fun initViews(savedInstanceState: Bundle?) {
  58. super.initViews(savedInstanceState)
  59. MediaPlayerHelper.playRawMp3(this, R.raw.login_ren_lian)
  60. // 使用 Glide 加载网络图片
  61. viewBinding.deptName.text = "${ChemicalApp.confs!!.deptName}-${ChemicalApp.confs!!.roomNum}"
  62. Glide.with(this)
  63. .load("${HttpConfig.API_BASE_IMG_URL}${ChemicalApp.confs!!.circularLogo}")
  64. .apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.AUTOMATIC))
  65. .into(viewBinding.image)
  66. var str = ""
  67. try {
  68. str = intent.getStringExtra("faceList")!!
  69. } catch (e: Exception) {
  70. }
  71. val mtypes = intent.getStringExtra("mtypes")
  72. try {
  73. when (mtypes) {
  74. "1" -> {
  75. viewBinding.linType.visibility = View.GONE
  76. }
  77. "4" -> {
  78. viewBinding.tvScan.visibility = View.GONE
  79. }
  80. "5" -> {
  81. viewBinding.tvSwipe.visibility = View.GONE
  82. }
  83. }
  84. } catch (e: Exception) {
  85. }
  86. val map = mutableMapOf<String, String>()
  87. if (mtypes != null) {
  88. map["mtypes"] = mtypes
  89. }
  90. if (str != null && str.length > 0) {
  91. // 去除字符串首尾的中括号
  92. faceList = str.removeSurrounding("[", "]")
  93. map["faceList"] = str
  94. }
  95. //跳转刷卡登录
  96. viewBinding.tvSwipe.setOnClickListener {
  97. UiManager.switcher(this, map, SwipeActivity::class.java)
  98. finish()
  99. }
  100. //跳转扫码登录
  101. viewBinding.tvScan.setOnClickListener {
  102. UiManager.switcher(this, map, ScanLoginActivity::class.java)
  103. finish()
  104. }
  105. viewBinding.tvReturn.text = "返回${ChemicalApp.confs!!.backTime}s"
  106. viewBinding.tvReturn.setOnClickListener {
  107. finish()
  108. }
  109. mFotoapparat = Fotoapparat.with(this)
  110. .into(viewBinding.cameraView)
  111. .lensPosition(
  112. if (Constants.FACE_TAG == 0) {
  113. front()
  114. } else {
  115. back()
  116. }
  117. )//front()前置 back 后置
  118. .frameProcessor(
  119. FaceDetectorProcessor.with(this)
  120. .listener { faces ->
  121. viewBinding.rectanglesView.setRectangles(faces)
  122. }.build()
  123. )
  124. .logger(loggers(logcat(), fileLogger(this)))
  125. .build()
  126. mFotoapparat.stop()
  127. mFotoapparat.start()
  128. // mCountDownTimer = object : CountDownTimer(totalTimeInMillis, 1000) {
  129. // override fun onTick(millisUntilFinished: Long) {
  130. // val secondsRemaining = millisUntilFinished / 1000
  131. // // 在最后六秒进行提示
  132. // if (secondsRemaining.toInt() == 6) {
  133. // val message = "多次识别失败 $secondsRemaining 秒后关闭当前页面,请注意!"
  134. // showToast(message)
  135. // }
  136. // }
  137. //
  138. // override fun onFinish() {
  139. // mFotoapparat.stop()
  140. // cancelTime()
  141. // finish()
  142. // }
  143. // }
  144. // mCountDownTimer.start()
  145. handlerBack.post(countdownRunnableTwo)
  146. countHandler.postDelayed({
  147. finish()
  148. }, totalTimeInMillis) // 15秒后关闭对话框
  149. }
  150. override fun onStart() {
  151. super.onStart()
  152. // mFotoapparat.start()
  153. }
  154. override fun onStop() {
  155. super.onStop()
  156. // mFotoapparat.stop()
  157. }
  158. override fun onBackPressed() {
  159. super.onBackPressed()
  160. finish()
  161. }
  162. override fun onDestroy() {
  163. super.onDestroy()
  164. // cancelTime()//手动关闭
  165. RcLog.info("=============onDestroy")
  166. // handlerUtil.removeCallbacks(task)
  167. // handlerUtil.stopAllTasks()
  168. // 移除回调,以防止内存泄漏
  169. try {
  170. mFotoapparat.stop()
  171. handlerBack.removeCallbacks(countdownRunnable)
  172. handlerBack.removeCallbacks(countdownRunnableTwo)
  173. handlerBack.removeCallbacksAndMessages(null)
  174. dismissLoading()
  175. } catch (e: Exception) {
  176. }
  177. try {
  178. countHandler.removeCallbacksAndMessages(null)
  179. } catch (e: Exception) {
  180. }
  181. }
  182. private fun takePicture() {
  183. RcLog.info("=======111人脸登录任务进行中")
  184. val format = SimpleDateFormat("yyyyMMdd_HHmmssSSS", Locale.getDefault())
  185. val fileName = "${format.format(Calendar.getInstance().time)}.jpg"
  186. val photoFile = File(this.getExternalFilesDir("photos"), fileName)
  187. try {
  188. mFotoapparat.takePicture()
  189. .saveToFile(photoFile)
  190. .whenAvailable {
  191. callFaceMatchingApi(photoFile)
  192. }
  193. } catch (e: Exception) {
  194. }
  195. }
  196. private fun callFaceMatchingApi(
  197. featureData: File,
  198. ) {
  199. showLoading("比对中....")
  200. val param = FaceCompareReq().apply {
  201. data = null
  202. userIds = faceList
  203. }
  204. val disposable = ApiRepository.faceCompare(featureData, param)
  205. .subscribe({ success ->
  206. dismissLoading()
  207. ChemicalApp.userData = success
  208. LogUtils.d(success.userId, ChemicalApp.subjectId)
  209. authenticationInfo(success.userId, ChemicalApp.subjectId!!)
  210. }, { throwable ->
  211. dismissLoading()
  212. throwableView(throwable)
  213. })
  214. addDisposable(disposable)
  215. }
  216. //验证当前人员身份
  217. private fun authenticationInfo(userId: String, subId: String) {
  218. LogUtils.d(userId, subId)
  219. showLoading("验证中...")
  220. val disposable = ApiRepository.userCardValidation(userId, subId)
  221. .subscribe({ data ->
  222. dismissLoading()
  223. val allFalse = with(data) {
  224. cabinetAdmin == false &&
  225. belongUser == false &&
  226. toipcUser == false &&
  227. safeUser == false &&
  228. collegeAdmin == false &&
  229. schoolLevelAdmin == false &&
  230. adminUser == false
  231. apply == false &&
  232. white == false
  233. }
  234. if (allFalse) {
  235. HttpClient.token = null
  236. ChemicalApp.userData = null
  237. customDialogView(2, "身份认证不通过")
  238. } else {
  239. //校级管理员 schoolLevelAdmin
  240. //院级管理员 collegeAdmin
  241. //实验室负责人 adminUser
  242. //安全负责人 safeUser
  243. //柜锁管理员 cabinetAdmin
  244. //是否化学品归属人 belongUser
  245. //是否化学品归属课题组下成员 toipcUser
  246. if (data.schoolLevelAdmin == true || data.collegeAdmin == true) {
  247. //院级管理员 or 校级管理员
  248. authenticationDialog(data.faceImg, data.userName)
  249. } else if (data.adminUser == true || data.safeUser == true || data.cabinetAdmin == true) {
  250. //实验室负责人 or 安全负责人 or 柜锁管理员
  251. authenticationDialog(data.faceImg, data.userName)
  252. } else if (data.belongUser == true || data.toipcUser == true) { //当前身份 归属人or课题组
  253. authenticationDialog(data.faceImg, data.userName)
  254. } else if (data.white == true || data.apply == true) {// 白名单和实验室准入
  255. authenticationDialog(data.faceImg, data.userName)
  256. } else {
  257. HttpClient.token = null
  258. ChemicalApp.userData = null
  259. customDialogView(2, "身份认证不通过")
  260. }
  261. }
  262. }, { throwable ->
  263. dismissLoading()
  264. //暂时注释掉 防止异步请求后 在认证时 token 丢失
  265. // startCountdownAndExecuteMethod()
  266. throwableView(throwable)
  267. })
  268. addDisposable(disposable)
  269. }
  270. //身份认证成功
  271. private fun authenticationDialog(faceImg: String?, userName: String) {
  272. mFotoapparat.stop()
  273. handlerBack.removeCallbacks(countdownRunnableTwo)
  274. MediaPlayerHelper.playRawMp3(this, R.raw.login_ren_zheng_tong_hua)
  275. mDialogsAut = AuthenticationDialog(
  276. this,
  277. faceImg,
  278. ChemicalApp.confs!!.subName,
  279. ChemicalApp.confs!!.deptName,
  280. "${ChemicalApp.confs!!.buildName}${ChemicalApp.confs!!.floorName}",
  281. userName, object : AuthenticationDialog.IClickLit {
  282. override fun onUpView(tvView: TextView) {
  283. mTvView = tvView
  284. }
  285. })
  286. mDialogsAut!!.show()
  287. // 开始倒计时
  288. handlerBack.post(countdownRunnable)
  289. // 获取对话框的 Window 对象
  290. mDialogsAut!!.window?.decorView?.setOnTouchListener { _, event ->
  291. // 判断是否点击了对话框外部空白区域
  292. if (event.action == MotionEvent.ACTION_DOWN) {
  293. val x = event.x
  294. val y = event.y
  295. val dialogView = mDialogsAut!!.window?.decorView
  296. if (dialogView != null && (x < 0 || x > dialogView.width || y < 0 || y > dialogView.height)) {
  297. // 在此处执行点击对话框外部空白区域时的操作
  298. // 例如关闭对话框
  299. // 移除回调,以防止内存泄漏
  300. mDialogsAut!!.dismiss()
  301. finish()
  302. return@setOnTouchListener true
  303. }
  304. }
  305. return@setOnTouchListener false
  306. }
  307. }
  308. private val countdownRunnable = object : Runnable {
  309. override fun run() {
  310. if (timeLeftInSeconds > 0) {
  311. mTvView!!.text = "${timeLeftInSeconds}秒后自动返回首页"
  312. timeLeftInSeconds--
  313. handlerBack.postDelayed(this, 1000)
  314. } else {
  315. mDialogsAut!!.dismiss()
  316. finish()
  317. }
  318. }
  319. }
  320. private val countdownRunnableTwo = object : Runnable {
  321. override fun run() {
  322. takePicture()
  323. handlerBack.postDelayed(this, 4000)
  324. }
  325. }
  326. /**
  327. * 0 没有图标 1 绿色(成功) 2红色(失败)
  328. * 失败或者成功的弹框
  329. */
  330. private fun customDialogView(types: Int, msg: String) {
  331. val customDialog = CustomDialog(this, types, msg)
  332. if (!this.isFinishing && !this.isDestroyed) {
  333. customDialog.show()
  334. }
  335. }
  336. /**
  337. * 异常处理
  338. */
  339. private fun throwableView(throwable: Throwable) {
  340. LogUtils.e(Log.getStackTraceString(throwable))
  341. when (throwable) {
  342. is NetException -> {
  343. if (throwable.message.isNullOrEmpty()) {
  344. "接口请求失败(${throwable.code})"
  345. } else {
  346. throwable.message!!
  347. }
  348. }
  349. is SocketTimeoutException -> "请求超时,请稍后重试"
  350. is ConnectException -> "无法连接服务器,请检查网络"
  351. is HttpException -> "服务器繁忙,请稍后重试"
  352. else -> "服务器异常"
  353. }?.let { customDialogView(2, "$it") }
  354. }
  355. }