EditorGroup.swift 229 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954
  1. //
  2. // EditorGroup.swift
  3. // Qmera
  4. //
  5. // Created by Akhmad Al Qindi Irsyam on 20/09/21.
  6. //
  7. import UIKit
  8. import AVKit
  9. import AVFoundation
  10. import QuickLook
  11. import ReadabilityKit
  12. import Photos
  13. import NotificationBannerSwift
  14. import nuSDKService
  15. public class EditorGroup: UIViewController {
  16. @IBOutlet var viewButton: UIView!
  17. @IBOutlet var constraintViewTextField: NSLayoutConstraint!
  18. @IBOutlet var buttonVoice: UIButton!
  19. @IBOutlet var buttonSendImage: UIButton!
  20. @IBOutlet var buttonSendPhoto: UIButton!
  21. @IBOutlet var buttonSendSticker: UIButton!
  22. @IBOutlet var buttonSendFile: UIButton!
  23. @IBOutlet var textFieldSend: UITextView!
  24. @IBOutlet var heightTextFieldSend: NSLayoutConstraint!
  25. @IBOutlet var buttonSendChat: UIButton!
  26. @IBOutlet var tableChatView: UITableView!
  27. @IBOutlet var constraintTopTextField: NSLayoutConstraint!
  28. @IBOutlet var constraintBottomAttachment: NSLayoutConstraint!
  29. @IBOutlet var viewTextfield: UIView!
  30. @IBOutlet weak var buttonAckConfidential: UIButton!
  31. @IBOutlet weak var constraintBottomTableViewWithTextfield: NSLayoutConstraint!
  32. @IBOutlet weak var viewAttachment: UIStackView!
  33. public var dataGroup: [String: Any?] = [:]
  34. public var dataTopic: [String: Any?] = [:]
  35. var dataMessages: [[String: Any?]] = []
  36. var dataDates: [String] = []
  37. public var dataMessageForward: [[String: Any?]]?
  38. var imageVideoPicker: ImageVideoPicker!
  39. var documentPicker: DocumentPicker!
  40. var currentIndexpath: IndexPath?
  41. var previewItem: NSURL?
  42. var reffId: String?
  43. var stickers = [String]()
  44. public var unique_l_pin = ""
  45. public var fromNotification = false
  46. var isHistoryCC = false
  47. var complaintId = ""
  48. var counter = 0
  49. var markerCounter: String?
  50. var buttonScrollToBottom = UIButton()
  51. let indicatorCounterBSTB = UIView()
  52. let labelCounter = UILabel()
  53. let containerActionGroup = UIView()
  54. var removed = false
  55. var isAck = false
  56. var copySession = false
  57. var forwardSession = false
  58. var deleteSession = false
  59. var isSearching = false
  60. let containerMultpileSelectSession = UIView()
  61. let viewSticker = UIView()
  62. let containerLink = UIView()
  63. let containerPreviewReply = UIView()
  64. var bottomAnchorPreviewReply = NSLayoutConstraint()
  65. let containerAction = UIView()
  66. var allowTyping = true
  67. let contactChatNav = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "contactChatNav") as! UINavigationController
  68. var searchBar: UISearchBar!
  69. var constraintBottomContainerMultpileSelectSession = NSLayoutConstraint()
  70. var titleSearchMatches: UILabel!
  71. var textSearch = ""
  72. var countMatchesSearch = 0
  73. var lastScrollIdxSearch = 0
  74. var buttonUp: UIButton!
  75. var buttonDown: UIButton!
  76. public override func viewDidDisappear(_ animated: Bool) {
  77. if self.isMovingFromParent {
  78. UserDefaults.standard.removeObject(forKey: "inEditorGroup")
  79. NotificationCenter.default.removeObserver(self)
  80. }
  81. }
  82. public override func viewDidAppear(_ animated: Bool) {
  83. navigationController?.navigationBar.isTranslucent = false
  84. navigationController?.navigationBar.backgroundColor = .mainColor
  85. navigationController?.navigationBar.tintColor = .white
  86. if self.navigationController?.isNavigationBarHidden ?? false {
  87. self.navigationController?.setNavigationBarHidden(false, animated: false)
  88. }
  89. updateProfile()
  90. }
  91. public override func viewDidLoad() {
  92. super.viewDidLoad()
  93. // navigationController?.navigationBar.topItem?.title = ""
  94. viewButton.layer.shadowColor = UIColor.gray.cgColor
  95. viewButton.layer.shadowOpacity = 1
  96. viewButton.layer.shadowOffset = .zero
  97. viewButton.layer.shadowRadius = 3
  98. // buttonVoice.setImage(resizeImage(image: UIImage(named: "Voice-Record", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!, targetSize: CGSize(width: 30, height: 30)), for: .normal)
  99. buttonSendImage.setImage(resizeImage(image: UIImage(named: "Send-Image", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!, targetSize: CGSize(width: 30, height: 30)).withTintColor(.mainColor), for: .normal)
  100. buttonSendPhoto.setImage(resizeImage(image: UIImage(named: "Camera", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!, targetSize: CGSize(width: 30, height: 30)).withTintColor(.mainColor), for: .normal)
  101. buttonSendSticker.setImage(resizeImage(image: UIImage(named: "Sticker---Emoji", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!, targetSize: CGSize(width: 30, height: 30)).withTintColor(.mainColor), for: .normal)
  102. buttonSendFile.setImage(resizeImage(image: UIImage(named: "File---Documents", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!, targetSize: CGSize(width: 30, height: 30)).withTintColor(.mainColor), for: .normal)
  103. buttonSendChat.setImage(resizeImage(image: UIImage(named: "Send-(White)", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!, targetSize: CGSize(width: 30, height: 30)).withRenderingMode(.alwaysOriginal), for: .normal)
  104. buttonSendChat.circle()
  105. buttonSendChat.addTarget(self, action: #selector(sendTapped), for: .touchUpInside)
  106. buttonAckConfidential.circle()
  107. buttonAckConfidential.addTarget(self, action: #selector(showChooserACKConfidential), for: .touchUpInside)
  108. textFieldSend.layer.cornerRadius = textFieldSend.maxCornerRadius()
  109. textFieldSend.layer.borderWidth = 1.0
  110. textFieldSend.text = "Send message".localized()
  111. textFieldSend.textColor = UIColor.lightGray
  112. textFieldSend.textContainerInset = UIEdgeInsets(top: 12, left: 20, bottom: 11, right: 40)
  113. textFieldSend.layer.borderColor = UIColor.lightGray.withAlphaComponent(0.5).cgColor
  114. textFieldSend.font = UIFont.systemFont(ofSize: 12)
  115. textFieldSend.delegate = self
  116. navigationItem.rightBarButtonItem?.tintColor = UIColor.secondaryColor
  117. imageVideoPicker = ImageVideoPicker(presentationController: self, delegate: self)
  118. documentPicker = DocumentPicker(presentationController: self, delegate: self)
  119. let fm = FileManager.default
  120. let path = Bundle.resourceBundle(for: Nexilis.self).resourcePath!
  121. let items = try! fm.contentsOfDirectory(atPath: path)
  122. for item in items {
  123. if item.hasPrefix("sticker") {
  124. stickers.append(item)
  125. }
  126. }
  127. tableChatView.register(UITableViewCell.self, forCellReuseIdentifier: "cellEditorGroup")
  128. loadData()
  129. setRightButtonItem()
  130. let center: NotificationCenter = NotificationCenter.default
  131. center.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
  132. center.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
  133. center.addObserver(self, selector: #selector(onReceiveMessage(notification:)), name: NSNotification.Name(rawValue: "onReceiveChat"), object: nil)
  134. center.addObserver(self, selector: #selector(onStatusChat(notification:)), name: NSNotification.Name(rawValue: "onMessageChat"), object: nil)
  135. center.addObserver(self, selector: #selector(onUploadChat(notification:)), name: NSNotification.Name(rawValue: "onUploadChat"), object: nil)
  136. center.addObserver(self, selector: #selector(onMemberTopic(notification:)), name: NSNotification.Name(rawValue: "onMember"), object: nil)
  137. center.addObserver(self, selector: #selector(onGroup(notification:)), name: NSNotification.Name(rawValue: "onGroup"), object: nil)
  138. center.addObserver(self, selector: #selector(onMemberTopic(notification:)), name: NSNotification.Name(rawValue: "onTopic"), object: nil)
  139. if dataMessageForward != nil {
  140. for i in 0..<dataMessageForward!.count {
  141. sendChat(message_scope_id: "4", status: "2", message_text: dataMessageForward![i]["message_text"] as! String, credential: "0", attachment_flag: dataMessageForward![i]["attachment_flag"] as! String, ex_blog_id: "", message_large_text: "", ex_format: "", image_id: dataMessageForward![i]["image_id"] as! String, audio_id: dataMessageForward![i]["audio_id"] as! String, video_id: dataMessageForward![i]["video_id"] as! String, file_id: dataMessageForward![i]["file_id"] as! String, thumb_id: dataMessageForward![i]["thumb_id"] as! String, reff_id: "", read_receipts: "", is_call_center: "0", call_center_id: "", viewController: self)
  142. }
  143. dataMessageForward = nil
  144. }
  145. }
  146. private func updateProfile() {
  147. let idMe = UserDefaults.standard.string(forKey: "me") as String?
  148. DispatchQueue.global().async {
  149. let message = CoreMessage_TMessageBank.getBatchBuddiesInfos(p_f_pin: idMe!, last_update: 0)
  150. let _ = Nexilis.write(message: message)
  151. }
  152. }
  153. private func setRightButtonItem() {
  154. navigationItem.rightBarButtonItems = nil
  155. navigationItem.rightBarButtonItem = nil
  156. let menu = UIMenu(title: "", children: [
  157. UIAction(title: "Delete Conversation".localized(), handler: {(_) in
  158. let alert = UIAlertController(title: "", message: "Are you sure to delete all message in this conversation?".localized(), preferredStyle: .alert)
  159. alert.addAction(UIAlertAction(title: "Cancel".localized(), style: UIAlertAction.Style.default, handler: nil))
  160. alert.addAction(UIAlertAction(title: "Delete".localized(), style: .destructive, handler: {(_) in
  161. var l_pin = self.dataGroup["group_id"] as! String
  162. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  163. if (self.dataTopic["chat_id"] as! String != "") {
  164. l_pin = self.dataTopic["chat_id"] as! String
  165. }
  166. _ = Database.shared.deleteRecord(fmdb: fmdb, table: "MESSAGE", _where: "(l_pin='\(self.dataGroup["group_id"]!!)' and chat_id='\(self.dataTopic["chat_id"]!!)') and message_scope_id='4'")
  167. _ = Database.shared.deleteRecord(fmdb: fmdb, table: "MESSAGE_SUMMARY", _where: "l_pin='\(l_pin)'")
  168. })
  169. if self.fromNotification {
  170. self.didTapExit()
  171. } else {
  172. self.navigationController?.popViewController(animated: true)
  173. }
  174. // self.dataMessages.removeAll()
  175. // self.dataDates.removeAll()
  176. // self.tableChatView.reloadData()
  177. }))
  178. self.present(alert, animated: true, completion: nil)
  179. }),
  180. ])
  181. if !isHistoryCC {
  182. let moreIcon = UIBarButtonItem(image: UIImage(systemName: "ellipsis", withConfiguration: UIImage.SymbolConfiguration(pointSize: 18, weight: .regular, scale: .default)), menu: menu)
  183. let buttonSearch = UIBarButtonItem(image: UIImage(systemName: "magnifyingglass", withConfiguration: UIImage.SymbolConfiguration(pointSize: 18, weight: .regular, scale: .default)), style: .plain, target: self, action: #selector(search(sender:)))
  184. navigationItem.rightBarButtonItems = [moreIcon,buttonSearch]
  185. } else {
  186. let buttonSearch = UIBarButtonItem(image: UIImage(systemName: "magnifyingglass", withConfiguration: UIImage.SymbolConfiguration(pointSize: 18, weight: .regular, scale: .default)), style: .plain, target: self, action: #selector(search(sender:)))
  187. navigationItem.rightBarButtonItem = buttonSearch
  188. }
  189. }
  190. @objc func search(sender: UIBarButtonItem) {
  191. self.isSearching = true
  192. if self.reffId != nil {
  193. self.deleteReplyView()
  194. }
  195. DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) {
  196. let cancelButton = UIBarButtonItem(title: "Cancel".localized(), style: .plain, target: self, action: #selector(self.cancelAction))
  197. if !self.isHistoryCC {
  198. self.navigationItem.rightBarButtonItems = nil
  199. }
  200. self.navigationItem.rightBarButtonItem = cancelButton
  201. self.changeAppBar()
  202. self.addMultipleSelectSession()
  203. }
  204. }
  205. private func getOfficialGroup() {
  206. let query = "SELECT group_id, f_name, official, image_id FROM GROUPZ where group_type = 1 AND official = 1"
  207. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  208. if let cursorData = Database.shared.getRecords(fmdb: fmdb, query: query) {
  209. if cursorData.next() {
  210. dataGroup["group_id"] = cursorData.string(forColumnIndex: 0)
  211. dataTopic["chat_id"] = ""
  212. dataGroup["f_name"] = cursorData.string(forColumnIndex: 1)
  213. dataGroup["image_id"] = cursorData.string(forColumnIndex: 3)
  214. dataGroup["official"] = cursorData.string(forColumnIndex: 2)
  215. }
  216. cursorData.close()
  217. }
  218. })
  219. }
  220. func loadData() {
  221. if (unique_l_pin != "") {
  222. dataDates.removeAll()
  223. dataGroup.removeAll()
  224. dataTopic.removeAll()
  225. dataMessages.removeAll()
  226. tableChatView.reloadData()
  227. currentIndexpath = nil
  228. reffId = nil
  229. getDataGroup(unique_l_pin: unique_l_pin)
  230. }
  231. if removed {
  232. removed = false
  233. containerActionGroup.removeConstraints(containerActionGroup.constraints)
  234. containerActionGroup.removeFromSuperview()
  235. setRightButtonItem()
  236. }
  237. if !isHistoryCC {
  238. UserDefaults.standard.set([dataGroup["group_id"], dataTopic["chat_id"]], forKey: "inEditorGroup")
  239. if dataTopic["chat_id"] as! String == "" {
  240. UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [dataGroup["group_id"] as! String])
  241. sendTyping(l_pin: dataGroup["group_id"] as! String)
  242. } else {
  243. UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [dataTopic["chat_id"] as! String])
  244. sendTyping(l_pin: dataTopic["chat_id"] as! String)
  245. }
  246. } else {
  247. getOfficialGroup()
  248. disableEditor()
  249. }
  250. if fromNotification {
  251. let imageButton = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 44))
  252. imageButton.image = UIImage(systemName: "chevron.backward")?.withTintColor(.white)
  253. imageButton.contentMode = .right
  254. let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didTapExit))
  255. imageButton.isUserInteractionEnabled = true
  256. imageButton.addGestureRecognizer(tapGestureRecognizer)
  257. let leftItem = UIBarButtonItem(customView: imageButton)
  258. self.navigationItem.leftBarButtonItem = leftItem
  259. }
  260. changeAppBar()
  261. getData()
  262. getCounter()
  263. if counter > 0 {
  264. markerCounter = dataMessages[dataMessages.count - counter]["message_id"] as? String
  265. }
  266. tableChatView.alpha = 0
  267. tableChatView.delegate = self
  268. tableChatView.dataSource = self
  269. tableChatView.reloadData()
  270. if counter != 0 {
  271. if dataMessages.firstIndex(where: {$0["message_id"] as? String == markerCounter} ) != 0 {
  272. DispatchQueue.main.async {
  273. let data = self.dataMessages.filter({ $0["message_id"] as? String == self.markerCounter })
  274. let section = self.dataDates.firstIndex(of: data[0]["chat_date"] as! String)
  275. let row = self.dataMessages.filter({$0["chat_date"] as! String == data[0]["chat_date"] as! String}).firstIndex(where: { $0["message_id"] as? String == self.markerCounter})
  276. self.tableChatView.scrollToRow(at: IndexPath(row: row!, section: section!), at: .bottom, animated: false)
  277. }
  278. } else {
  279. tableChatView.scrollToTop()
  280. }
  281. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [self] in
  282. if currentIndexpath == nil && counter != 0 {
  283. let idMe = UserDefaults.standard.string(forKey: "me") as String?
  284. if let idx = dataMessages.firstIndex(where: { $0["message_id"] as? String == markerCounter}) {
  285. for i in idx..<dataMessages.count {
  286. if dataMessages[i]["f_pin"] as? String != idMe {
  287. sendReadMessageStatus(chat_id: self.dataTopic["chat_id"] as! String, f_pin: dataMessages[i]["f_pin"] as! String, message_scope_id: "4", message_id: dataMessages[i]["message_id"] as! String)
  288. }
  289. }
  290. counter = 0
  291. updateCounter(counter: counter)
  292. }
  293. }
  294. }
  295. } else {
  296. tableChatView.scrollToBottom(isAnimated: false)
  297. }
  298. tableChatView.keyboardDismissMode = .interactive
  299. let tapGesture = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
  300. tapGesture.cancelsTouchesInView = false
  301. tableChatView.addGestureRecognizer(tapGesture)
  302. UIView.animate(withDuration: 0.5, animations: {
  303. self.tableChatView.alpha = 1.0
  304. })
  305. }
  306. func getDataProfile(f_pin: String, message_id: String) -> [String: String]{
  307. var data: [String: String] = [:]
  308. Database().database?.inTransaction({ fmdb, rollback in
  309. if let c = Database().getRecords(fmdb: fmdb, query: "select first_name || ' ' || last_name, image_id from BUDDY where f_pin = '\(f_pin)'"), c.next() {
  310. data["name"] = c.string(forColumnIndex: 0)!.trimmingCharacters(in: .whitespacesAndNewlines)
  311. data["image_id"] = c.string(forColumnIndex: 1)!
  312. c.close()
  313. }
  314. else if let c = Database().getRecords(fmdb: fmdb, query: "select first_name || ' ' || last_name, thumb_id from GROUPZ_MEMBER where f_pin = '\(f_pin)' AND group_id = '\(dataGroup["group_id"]!!)'"), c.next() {
  315. data["name"] = c.string(forColumnIndex: 0)!.trimmingCharacters(in: .whitespacesAndNewlines)
  316. data["image_id"] = c.string(forColumnIndex: 1)!
  317. c.close()
  318. } else if let c = Database().getRecords(fmdb: fmdb, query: "select f_display_name from MESSAGE where message_id = '\(message_id)'"), c.next() {
  319. data["name"] = c.string(forColumnIndex: 0)!
  320. data["image_id"] = ""
  321. c.close()
  322. } else {
  323. data["name"] = "Unknown".localized()
  324. }
  325. })
  326. return data
  327. }
  328. private func getDataGroup(unique_l_pin: String) {
  329. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  330. if let cursorGroup = Database.shared.getRecords(fmdb: fmdb, query: "SELECT group_id, f_name, image_id, official, parent FROM GROUPZ WHERE group_id='\(unique_l_pin)'"), cursorGroup.next() {
  331. dataGroup["group_id"] = cursorGroup.string(forColumnIndex: 0)
  332. dataGroup["f_name"] = cursorGroup.string(forColumnIndex: 1)
  333. dataGroup["image_id"] = cursorGroup.string(forColumnIndex: 2)
  334. dataGroup["official"] = cursorGroup.string(forColumnIndex: 3)
  335. dataGroup["parent"] = cursorGroup.string(forColumnIndex: 4)
  336. dataTopic["title"] = "Lounge".localized()
  337. dataTopic["chat_id"] = ""
  338. cursorGroup.close()
  339. } else if let cursorTopic = Database.shared.getRecords(fmdb: fmdb, query: "SELECT group_id, title FROM DISCUSSION_FORUM where chat_id = '\(unique_l_pin)'"), cursorTopic.next() {
  340. dataGroup["group_id"] = cursorTopic.string(forColumnIndex: 0)
  341. dataTopic["title"] = cursorTopic.string(forColumnIndex: 1)
  342. dataTopic["chat_id"] = unique_l_pin
  343. cursorTopic.close()
  344. if let cursorGroup = Database.shared.getRecords(fmdb: fmdb, query: "SELECT f_name, image_id, official, parent FROM GROUPZ where group_id = '\(dataGroup["group_id"] as! String)'"), cursorGroup.next() {
  345. dataGroup["f_name"] = cursorGroup.string(forColumnIndex: 0)
  346. dataGroup["image_id"] = cursorGroup.string(forColumnIndex: 1)
  347. dataGroup["official"] = cursorGroup.string(forColumnIndex: 2)
  348. dataGroup["parent"] = cursorGroup.string(forColumnIndex: 3)
  349. cursorGroup.close()
  350. }
  351. }
  352. })
  353. }
  354. private func getData() {
  355. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  356. var query = "SELECT message_id, f_pin, l_pin, message_scope_id, server_date, status, message_text, audio_id, video_id, image_id, thumb_id, read_receipts, chat_id, file_id, attachment_flag, reff_id, lock, is_stared, blog_id FROM MESSAGE where chat_id='' AND l_pin='\(dataGroup["group_id"] as! String)' order by server_date asc"
  357. if isHistoryCC {
  358. query = "SELECT message_id, f_pin, l_pin, message_scope_id, server_date, status, message_text, audio_id, video_id, image_id, thumb_id, read_receipts, chat_id, file_id, attachment_flag, reff_id, lock, is_stared FROM MESSAGE where call_center_id='\(complaintId)' order by server_date asc"
  359. } else if (dataTopic["chat_id"] as! String != "") {
  360. query = "SELECT message_id, f_pin, l_pin, message_scope_id, server_date, status, message_text, audio_id, video_id, image_id, thumb_id, read_receipts, chat_id, file_id, attachment_flag, reff_id, lock, is_stared FROM MESSAGE where chat_id='\(dataTopic["chat_id"] as! String)' order by server_date asc"
  361. }
  362. if let cursorData = Database.shared.getRecords(fmdb: fmdb, query: query) {
  363. while cursorData.next() {
  364. var row: [String: Any?] = [:]
  365. row["message_id"] = cursorData.string(forColumnIndex: 0)
  366. row["f_pin"] = cursorData.string(forColumnIndex: 1)
  367. row["l_pin"] = cursorData.string(forColumnIndex: 2)
  368. row["message_scope_id"] = cursorData.string(forColumnIndex: 3)
  369. row["server_date"] = cursorData.string(forColumnIndex: 4)
  370. row["status"] = cursorData.string(forColumnIndex: 5)
  371. row["message_text"] = cursorData.string(forColumnIndex: 6)
  372. row["audio_id"] = cursorData.string(forColumnIndex: 7)
  373. row["video_id"] = cursorData.string(forColumnIndex: 8)
  374. row["image_id"] = cursorData.string(forColumnIndex: 9)
  375. row["thumb_id"] = cursorData.string(forColumnIndex: 10)
  376. row["read_receipts"] = cursorData.string(forColumnIndex: 11)
  377. row["chat_id"] = cursorData.string(forColumnIndex: 12)
  378. row["file_id"] = cursorData.string(forColumnIndex: 13)
  379. row["attachment_flag"] = cursorData.string(forColumnIndex: 14)
  380. row["reff_id"] = cursorData.string(forColumnIndex: 15)
  381. row["lock"] = cursorData.string(forColumnIndex: 16)
  382. row["is_stared"] = cursorData.string(forColumnIndex: 17)
  383. row["blog_id"] = cursorData.string(forColumnIndex: 18)
  384. row["isSelected"] = false
  385. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  386. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  387. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  388. if let dirPath = paths.first {
  389. let videoURL = URL(fileURLWithPath: dirPath).appendingPathComponent(row["video_id"] as! String)
  390. let fileURL = URL(fileURLWithPath: dirPath).appendingPathComponent(row["file_id"] as! String)
  391. if ((row["video_id"] as! String) != "") {
  392. if FileManager.default.fileExists(atPath: videoURL.path){
  393. row["progress"] = 100.0
  394. } else {
  395. row["progress"] = 0.0
  396. }
  397. } else {
  398. if FileManager.default.fileExists(atPath: fileURL.path){
  399. row["progress"] = 100.0
  400. } else {
  401. row["progress"] = 0.0
  402. }
  403. }
  404. }
  405. row["chat_date"] = chatDate(stringDate: row["server_date"] as! String)
  406. dataMessages.append(row)
  407. }
  408. // if isHistoryCC {
  409. // dataMessages.remove(at: 0)
  410. // }
  411. cursorData.close()
  412. }
  413. })
  414. }
  415. private func getRealStatus(messageId: String) -> String {
  416. var status = "1"
  417. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  418. if let cursorStatus = Database.shared.getRecords(fmdb: fmdb, query: "SELECT status, f_pin FROM MESSAGE_STATUS WHERE message_id='\(messageId)'") {
  419. var listStatus: [Int] = []
  420. while cursorStatus.next() {
  421. listStatus.append(Int(cursorStatus.string(forColumnIndex: 0)!)!)
  422. }
  423. cursorStatus.close()
  424. status = "\(listStatus.min() ?? 2)"
  425. }
  426. })
  427. return status
  428. }
  429. private func chatDate(stringDate: String) -> String {
  430. let date = Date(milliseconds: Int64(stringDate)!)
  431. let calendar = Calendar.current
  432. if (calendar.isDateInToday(date)) {
  433. if !dataDates.contains("Today".localized()){
  434. dataDates.append("Today".localized())
  435. }
  436. return "Today".localized()
  437. } else {
  438. let startOfNow = calendar.startOfDay(for: Date())
  439. let startOfTimeStamp = calendar.startOfDay(for: date)
  440. let components = calendar.dateComponents([.day], from: startOfNow, to: startOfTimeStamp)
  441. let day = -(components.day!)
  442. if day == 1{
  443. if !dataDates.contains("Yesterday".localized()){
  444. dataDates.append("Yesterday".localized())
  445. }
  446. return "Yesterday".localized()
  447. } else if day < 7 {
  448. if !dataDates.contains("\(day) " + "days".localized() + " " + "ago".localized()){
  449. dataDates.append("\(day) " + "days".localized() + " " + "ago".localized())
  450. }
  451. return "\(day) " + "days".localized() + " " + "ago".localized()
  452. } else {
  453. let formatter = DateFormatter()
  454. formatter.dateFormat = "dd MMMM yyyy"
  455. formatter.locale = NSLocale(localeIdentifier: "id") as Locale?
  456. let stringFormat = formatter.string(from: date as Date)
  457. if !dataDates.contains(stringFormat){
  458. dataDates.append(stringFormat)
  459. }
  460. return stringFormat
  461. }
  462. }
  463. }
  464. private func changeAppBar() {
  465. let viewAppBar = UIView()
  466. viewAppBar.frame.size = CGSize(width: self.view.frame.size.width, height: 44)
  467. if !isSearching {
  468. let imageProfile = UIImageView(frame: CGRect(x: 0, y: 7, width: 30, height: 30))
  469. imageProfile.circle()
  470. imageProfile.clipsToBounds = true
  471. viewAppBar.addSubview(imageProfile)
  472. let pictureImage = dataGroup["image_id"]!
  473. if (pictureImage as! String != "" && pictureImage != nil) {
  474. imageProfile.setImage(name: pictureImage! as! String)
  475. imageProfile.contentMode = .scaleAspectFill
  476. } else {
  477. imageProfile.image = UIImage(systemName: "person.3")
  478. imageProfile.contentMode = .scaleAspectFit
  479. imageProfile.backgroundColor = .lightGray
  480. }
  481. let titleNavigation = UILabel(frame: CGRect(x: 35, y: 0, width: viewAppBar.frame.size.width - 150, height: 44))
  482. viewAppBar.addSubview(titleNavigation)
  483. if (dataGroup["official"] as! String == "1") {
  484. if !isHistoryCC {
  485. titleNavigation.set(image: UIImage(named: "ic_official_flag", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withTintColor(.white), with: " \(dataGroup["f_name"]!!) (\(dataTopic["title"]!!))", size: 15, y: -4)
  486. } else {
  487. titleNavigation.text = (dataGroup["f_name"] as? String)! + " " + "Contact Center".localized()
  488. }
  489. } else {
  490. titleNavigation.text = (dataGroup["f_name"] as? String)! + " (\(dataTopic["title"]!!))"
  491. }
  492. titleNavigation.textColor = .white
  493. titleNavigation.font = UIFont.systemFont(ofSize: 12).bold
  494. navigationItem.titleView = viewAppBar
  495. } else {
  496. searchBar = UISearchBar()
  497. searchBar.autocapitalizationType = .none
  498. searchBar.delegate = self
  499. searchBar.searchTextField.tintColor = .mainColor
  500. searchBar.barTintColor = .secondaryColor
  501. searchBar.searchTextField.backgroundColor = .secondaryColor
  502. searchBar.showsCancelButton = false
  503. navigationItem.titleView = searchBar
  504. self.definesPresentationContext = true
  505. }
  506. if copySession || forwardSession || deleteSession || isSearching {
  507. navigationItem.hidesBackButton = true
  508. navigationController?.interactivePopGestureRecognizer?.isEnabled = false
  509. } else {
  510. navigationItem.hidesBackButton = false
  511. navigationController?.interactivePopGestureRecognizer?.isEnabled = true
  512. }
  513. viewAppBar.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(seeProfileTapped)))
  514. }
  515. @objc func onUploadChat(notification: NSNotification) {
  516. let data:[AnyHashable : Any] = notification.userInfo!
  517. var isImage = false
  518. var idx = dataMessages.lastIndex(where: { $0["video_id"] as! String == data["name"] as! String })
  519. if (idx == nil) {
  520. idx = dataMessages.lastIndex(where: { $0["image_id"] as! String == data["name"] as! String })
  521. isImage = true
  522. }
  523. if (idx != nil) {
  524. let section = dataDates.firstIndex(of: dataMessages[idx!]["chat_date"] as! String)
  525. if section == nil {
  526. return
  527. }
  528. let row = dataMessages.filter({ $0["chat_date"] as! String == dataDates[section!]}).firstIndex(where: { $0["message_id"] as! String == dataMessages[idx!]["message_id"] as! String})
  529. if row == nil {
  530. return
  531. }
  532. DispatchQueue.main.async {
  533. let indexPath = IndexPath(row: row!, section: section!)
  534. if let cell = self.tableChatView.cellForRow(at: indexPath) {
  535. for view in cell.contentView.subviews {
  536. if !(view is UILabel) && !(view is UIImageView) {
  537. for viewInContainer in view.subviews {
  538. if viewInContainer is UIImageView {
  539. if viewInContainer.subviews.count == 0 {
  540. return
  541. }
  542. var containerView = UIView()
  543. if (isImage) {
  544. containerView = viewInContainer.subviews[0]
  545. } else {
  546. containerView = viewInContainer.subviews[1]
  547. }
  548. let loading = containerView.layer.sublayers![1] as! CAShapeLayer
  549. loading.strokeEnd = CGFloat(data["progress"] as! Double / 100)
  550. if (data["progress"] as! Double == 100.0) {
  551. self.dataMessages[idx!]["progress"] = data["progress"]
  552. self.tableChatView.reloadRows(at: [indexPath], with: .none)
  553. }
  554. }
  555. }
  556. }
  557. }
  558. }
  559. }
  560. } else {
  561. idx = dataMessages.lastIndex(where: { $0["file_id"] as! String == data["name"] as! String })
  562. if (idx != nil) {
  563. DispatchQueue.main.async {
  564. let section = 0
  565. let indexPath = IndexPath(row: idx!, section: section)
  566. if let cell = self.tableChatView.cellForRow(at: indexPath) {
  567. for view in cell.contentView.subviews {
  568. if !(view is UILabel) && !(view is UIImageView) {
  569. for viewSubviews in view.subviews {
  570. if !(viewSubviews is UILabel) {
  571. for viewInContainer in viewSubviews.subviews {
  572. if !(viewInContainer is UILabel) && !(viewInContainer is UIImageView) {
  573. if viewInContainer.layer.sublayers!.count < 2 {
  574. return
  575. }
  576. let loading = viewInContainer.layer.sublayers![1] as! CAShapeLayer
  577. loading.strokeEnd = CGFloat(data["progress"] as! Double / 100)
  578. if (data["progress"] as! Double == 100.0) {
  579. self.dataMessages[idx!]["progress"] = data["progress"]
  580. self.tableChatView.reloadRows(at: [indexPath], with: .none)
  581. }
  582. }
  583. }
  584. }
  585. }
  586. }
  587. }
  588. }
  589. }
  590. }
  591. }
  592. }
  593. @objc func onReceiveMessage(notification: NSNotification) {
  594. DispatchQueue.main.async {
  595. let data:[AnyHashable : Any] = notification.userInfo!
  596. if let dataMessage = data["message"] as? TMessage {
  597. let chatData = dataMessage.mBodies
  598. let group_id = self.dataGroup["group_id"] as! String
  599. let chat_id = self.dataTopic["chat_id"] as! String
  600. if chatData[CoreMessage_TMessageKey.L_PIN] == group_id && (chatData[CoreMessage_TMessageKey.CHAT_ID] ?? "") == chat_id {
  601. var row: [String: Any?] = [:]
  602. row["message_id"] = chatData[CoreMessage_TMessageKey.MESSAGE_ID]
  603. row["f_pin"] = chatData[CoreMessage_TMessageKey.F_PIN]
  604. row["l_pin"] = chatData[CoreMessage_TMessageKey.L_PIN]
  605. row["message_scope_id"] = chatData[CoreMessage_TMessageKey.MESSAGE_SCOPE_ID]
  606. row["server_date"] = chatData[CoreMessage_TMessageKey.SERVER_DATE]
  607. row["status"] = chatData[CoreMessage_TMessageKey.STATUS]
  608. row["message_text"] = chatData[CoreMessage_TMessageKey.MESSAGE_TEXT]
  609. if (chatData.keys.contains(CoreMessage_TMessageKey.AUDIO_ID)) {
  610. row["audio_id"] = chatData[CoreMessage_TMessageKey.AUDIO_ID]
  611. } else {
  612. row["audio_id"] = ""
  613. }
  614. if (chatData.keys.contains(CoreMessage_TMessageKey.VIDEO_ID)) {
  615. row["video_id"] = chatData[CoreMessage_TMessageKey.VIDEO_ID]
  616. } else {
  617. row["video_id"] = ""
  618. }
  619. if (chatData.keys.contains(CoreMessage_TMessageKey.IMAGE_ID)) {
  620. row["image_id"] = chatData[CoreMessage_TMessageKey.IMAGE_ID]
  621. } else {
  622. row["image_id"] = ""
  623. }
  624. if (chatData.keys.contains(CoreMessage_TMessageKey.THUMB_ID)) {
  625. row["thumb_id"] = chatData[CoreMessage_TMessageKey.THUMB_ID]
  626. } else {
  627. row["thumb_id"] = ""
  628. }
  629. row["read_receipts"] = 0
  630. row["chat_id"] = ""
  631. if (chatData.keys.contains(CoreMessage_TMessageKey.FILE_ID)) {
  632. row["file_id"] = chatData[CoreMessage_TMessageKey.FILE_ID]
  633. } else {
  634. row["file_id"] = ""
  635. }
  636. row["progress"] = 0.0
  637. row["attachment_flag"] = chatData[CoreMessage_TMessageKey.ATTACHMENT_FLAG]
  638. row["reff_id"] = chatData[CoreMessage_TMessageKey.REF_ID] ?? ""
  639. row["lock"] = ""
  640. row["is_stared"] = "0"
  641. row["isSelected"] = false
  642. if !self.dataDates.contains("Today".localized()){
  643. self.dataDates.append("Today".localized())
  644. self.tableChatView.insertSections(IndexSet(integer: self.dataDates.count - 1), with: .fade)
  645. }
  646. row["chat_date"] = "Today".localized()
  647. row["blog_id"] = chatData[CoreMessage_TMessageKey.BLOG_ID]
  648. self.counter += 1
  649. self.dataMessages.append(row)
  650. self.tableChatView.insertRows(at: [IndexPath(row: self.dataMessages.filter({ $0["chat_date"] as! String == self.dataDates[self.dataDates.count - 1]}).count - 1, section: self.dataDates.count - 1)], with: .fade)
  651. if self.currentIndexpath?.row == (self.dataMessages.count - 2) {
  652. if (self.viewIfLoaded?.window != nil) {
  653. self.sendReadMessageStatus(chat_id: self.dataTopic["chat_id"] as! String, f_pin: chatData[CoreMessage_TMessageKey.F_PIN]!, message_scope_id: chatData[CoreMessage_TMessageKey.MESSAGE_SCOPE_ID]!, message_id: chatData[CoreMessage_TMessageKey.MESSAGE_ID]!)
  654. }
  655. self.tableChatView.scrollToBottom()
  656. if (self.currentIndexpath!.section <= self.dataDates.count - 1 && self.currentIndexpath!.row <= self.dataMessages.filter({ $0["chat_date"] as! String == self.dataDates[self.dataDates.count - 1]}).count - 1) {
  657. self.counter = 0
  658. self.updateCounter(counter: self.counter)
  659. }
  660. if self.markerCounter != nil {
  661. self.markerCounter = nil
  662. }
  663. self.tableChatView.reloadData()
  664. }
  665. else if self.currentIndexpath == nil {
  666. self.counter = 0
  667. self.updateCounter(counter: self.counter)
  668. if (self.viewIfLoaded?.window != nil) {
  669. self.sendReadMessageStatus(chat_id: self.dataTopic["chat_id"] as! String, f_pin: chatData[CoreMessage_TMessageKey.F_PIN]!, message_scope_id: chatData[CoreMessage_TMessageKey.MESSAGE_SCOPE_ID]!, message_id: chatData[CoreMessage_TMessageKey.MESSAGE_ID]!)
  670. }
  671. }
  672. else if self.counter != 0 {
  673. if !self.indicatorCounterBSTB.isDescendant(of: self.view) && self.buttonScrollToBottom.isDescendant(of: self.view) {
  674. self.markerCounter = row["message_id"] as? String
  675. self.addCounterAtButttonScrollToBottom()
  676. self.tableChatView.reloadData()
  677. } else if self.indicatorCounterBSTB.isDescendant(of: self.view) {
  678. self.labelCounter.text = "\(self.counter)"
  679. }
  680. }
  681. }
  682. } else {
  683. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "reloadTabChats"), object: nil, userInfo: nil)
  684. }
  685. }
  686. }
  687. @objc func onStatusChat(notification: NSNotification) {
  688. DispatchQueue.main.async {
  689. let data:[AnyHashable : Any] = notification.userInfo!
  690. if let dataMessage = data["message"] as? TMessage {
  691. let idMe = UserDefaults.standard.string(forKey: "me") as String?
  692. let chatData = dataMessage.mBodies
  693. if (chatData[CoreMessage_TMessageKey.F_PIN] == idMe || chatData[CoreMessage_TMessageKey.L_PIN] == self.dataGroup["group_id"] as? String || chatData[CoreMessage_TMessageKey.F_PIN] == self.dataGroup["group_id"] as? String) && chatData[CoreMessage_TMessageKey.MESSAGE_SCOPE_ID] == "4" {
  694. if (chatData.keys.contains(CoreMessage_TMessageKey.MESSAGE_ID) && !(chatData[CoreMessage_TMessageKey.MESSAGE_ID]!).contains("-2,")) {
  695. let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as! String == chatData[CoreMessage_TMessageKey.MESSAGE_ID]! })
  696. if (idx != nil) {
  697. if (chatData[CoreMessage_TMessageKey.DELETE_MESSAGE_FLAG] == "1") {
  698. self.dataMessages[idx!]["lock"] = "1"
  699. self.dataMessages[idx!]["reff_id"] = ""
  700. let section = self.dataDates.firstIndex(of: self.dataMessages[idx!]["chat_date"] as! String)
  701. let row = self.dataMessages.filter({ $0["chat_date"] as! String == self.dataMessages[idx!]["chat_date"] as! String}).firstIndex(where: { $0["message_id"] as! String == self.dataMessages[idx!]["message_id"] as! String })
  702. if row != nil && section != nil {
  703. self.tableChatView.reloadRows(at: [IndexPath(row: row!, section: section!)], with: .none)
  704. }
  705. if self.reffId != nil && self.reffId == chatData[CoreMessage_TMessageKey.MESSAGE_ID]! {
  706. self.deleteReplyView()
  707. }
  708. } else {
  709. self.dataMessages[idx!]["status"] = chatData[CoreMessage_TMessageKey.STATUS]!
  710. let section = self.dataDates.firstIndex(of: self.dataMessages[idx!]["chat_date"] as! String)
  711. let row = self.dataMessages.filter({ $0["chat_date"] as! String == self.dataMessages[idx!]["chat_date"] as! String}).firstIndex(where: { $0["message_id"] as! String == self.dataMessages[idx!]["message_id"] as! String })
  712. if row != nil && section != nil {
  713. self.tableChatView.reloadRows(at: [IndexPath(row: row!, section: section!)], with: .none)
  714. }
  715. }
  716. }
  717. }
  718. else if (chatData.keys.contains("message_id")) {
  719. let idx = self.dataMessages.firstIndex(where: { "'\($0["message_id"] as! String)'" == chatData["message_id"]! })
  720. if (idx != nil) {
  721. if (chatData[CoreMessage_TMessageKey.DELETE_MESSAGE_FLAG] == "1") {
  722. self.dataMessages[idx!]["lock"] = "1"
  723. self.dataMessages[idx!]["reff_id"] = ""
  724. let section = self.dataDates.firstIndex(of: self.dataMessages[idx!]["chat_date"] as! String)
  725. let row = self.dataMessages.filter({ $0["chat_date"] as! String == self.dataMessages[idx!]["chat_date"] as! String}).firstIndex(where: { $0["message_id"] as! String == self.dataMessages[idx!]["message_id"] as! String })
  726. if row != nil && section != nil {
  727. self.tableChatView.reloadRows(at: [IndexPath(row: row!, section: section!)], with: .none)
  728. }
  729. if self.reffId != nil && self.reffId == chatData["message_id"]! {
  730. self.deleteReplyView()
  731. }
  732. } else {
  733. self.dataMessages[idx!]["status"] = chatData[CoreMessage_TMessageKey.STATUS]!
  734. let section = self.dataDates.firstIndex(of: self.dataMessages[idx!]["chat_date"] as! String)
  735. let row = self.dataMessages.filter({ $0["chat_date"] as! String == self.dataMessages[idx!]["chat_date"] as! String}).firstIndex(where: { $0["message_id"] as! String == self.dataMessages[idx!]["message_id"] as! String })
  736. if row != nil && section != nil {
  737. self.tableChatView.reloadRows(at: [IndexPath(row: row!, section: section!)], with: .none)
  738. }
  739. }
  740. }
  741. }
  742. else {
  743. let messageId = chatData[CoreMessage_TMessageKey.MESSAGE_ID]!.split(separator: ",")[1]
  744. let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as! String == messageId })
  745. if (idx != nil) {
  746. self.dataMessages[idx!]["status"] = chatData[CoreMessage_TMessageKey.STATUS]!
  747. let section = self.dataDates.firstIndex(of: self.dataMessages[idx!]["chat_date"] as! String)
  748. let row = self.dataMessages.filter({ $0["chat_date"] as! String == self.dataMessages[idx!]["chat_date"] as! String}).firstIndex(where: { $0["message_id"] as! String == self.dataMessages[idx!]["message_id"] as! String })
  749. if row != nil && section != nil {
  750. self.tableChatView.reloadRows(at: [IndexPath(row: row!, section: section!)], with: .none)
  751. }
  752. }
  753. }
  754. }
  755. }
  756. }
  757. }
  758. @objc func onMemberTopic(notification: NSNotification) {
  759. let data:[AnyHashable : Any] = notification.userInfo!
  760. DispatchQueue.main.async { [self] in
  761. if data["member"] == nil || data["code"] as! String == CoreMessage_TMessageCode.EXIT_GROUP && data["member"] as! String == UserDefaults.standard.string(forKey: "me")! && data["groupId"] as! String == self.dataGroup["group_id"] as! String && !containerActionGroup.isDescendant(of: self.view) {
  762. dismissKeyboard()
  763. let labelKicked = UILabel()
  764. if data["member"] == nil && data["code"] as! String == CoreMessage_TMessageCode.DELETE_CHAT && data["topicId"] as! String == dataTopic["chat_id"] as! String {
  765. labelKicked.text = "This topic has been deleted".localized()
  766. } else if data["member"] != nil && data["member"] as! String == data["f_pin"] as! String {
  767. labelKicked.text = "You have left this group".localized()
  768. } else if data["member"] != nil {
  769. labelKicked.text = "You have been removed from this group".localized()
  770. } else if data["code"] as! String == CoreMessage_TMessageCode.UPDATE_CHAT {
  771. dataGroup.removeAll()
  772. dataTopic.removeAll()
  773. getDataGroup(unique_l_pin: unique_l_pin)
  774. changeAppBar()
  775. return
  776. } else {
  777. return
  778. }
  779. removed = true
  780. navigationItem.rightBarButtonItem = nil
  781. view.addSubview(containerActionGroup)
  782. containerActionGroup.translatesAutoresizingMaskIntoConstraints = false
  783. NSLayoutConstraint.activate([
  784. containerActionGroup.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
  785. containerActionGroup.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
  786. containerActionGroup.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
  787. containerActionGroup.heightAnchor.constraint(equalToConstant: 120)
  788. ])
  789. containerActionGroup.backgroundColor = .secondaryColor.withAlphaComponent(0.8)
  790. containerActionGroup.addSubview(labelKicked)
  791. labelKicked.translatesAutoresizingMaskIntoConstraints = false
  792. NSLayoutConstraint.activate([
  793. labelKicked.centerYAnchor.constraint(equalTo: containerActionGroup.centerYAnchor),
  794. labelKicked.centerXAnchor.constraint(equalTo: containerActionGroup.centerXAnchor),
  795. ])
  796. labelKicked.textColor = .black
  797. labelKicked.font = UIFont.systemFont(ofSize: 12).bold
  798. if contactChatNav.viewIfLoaded?.window != nil {
  799. contactChatNav.dismiss(animated: true)
  800. }
  801. cancelAction()
  802. }
  803. }
  804. }
  805. @objc func onGroup(notification: NSNotification) {
  806. let data:[AnyHashable : Any] = notification.userInfo!
  807. if data["code"] as! String == "A010" && data["groupId"] as! String == self.dataGroup["group_id"] as! String {
  808. DispatchQueue.main.async {
  809. Database().database?.inTransaction({ fmdb, rollback in
  810. if let c = Database().getRecords(fmdb: fmdb, query: "select f_name, image_id from GROUPZ where group_id = '\(self.dataGroup["group_id"]!!)'"), c.next() {
  811. self.dataGroup["f_name"] = c.string(forColumnIndex: 0)!.trimmingCharacters(in: .whitespacesAndNewlines)
  812. self.dataGroup["image_id"] = c.string(forColumnIndex: 1)!
  813. c.close()
  814. }
  815. })
  816. self.changeAppBar()
  817. }
  818. }
  819. }
  820. @IBAction func voiceTapped(_ sender: UIButton) {
  821. if (self.constraintBottomAttachment.constant != 0.0) {
  822. constraintBottomAttachment.constant = 0.0
  823. self.viewSticker.removeConstraints(self.viewSticker.constraints)
  824. self.viewSticker.removeFromSuperview()
  825. }
  826. }
  827. @IBAction func imageTapped(_ sender: UIButton) {
  828. if (self.constraintBottomAttachment.constant != 0.0) {
  829. constraintBottomAttachment.constant = 0.0
  830. self.viewSticker.removeConstraints(self.viewSticker.constraints)
  831. self.viewSticker.removeFromSuperview()
  832. }
  833. let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
  834. if let action = self.actionImageVideo(for: "image", title: "Choose Photo".localized()) {
  835. alertController.addAction(action)
  836. }
  837. if let action = self.actionImageVideo(for: "video", title: "Choose Video".localized()) {
  838. alertController.addAction(action)
  839. }
  840. alertController.addAction(UIAlertAction(title: "Cancel".localized(), style: .cancel, handler: nil))
  841. self.present(alertController, animated: true)
  842. }
  843. private func actionImageVideo(for type: String, title: String) -> UIAlertAction? {
  844. return UIAlertAction(title: title, style: .default) { [unowned self] _ in
  845. switch type {
  846. case "image":
  847. imageVideoPicker.present(source: .imageAlbum)
  848. case "video":
  849. imageVideoPicker.present(source: .videoAlbum)
  850. case "imageCamera":
  851. imageVideoPicker.present(source: .imageCamera)
  852. case "videoCamera":
  853. imageVideoPicker.present(source: .videoCamera)
  854. default:
  855. imageVideoPicker.present(source: .imageAlbum)
  856. }
  857. }
  858. }
  859. @IBAction func photoTapped(_ sender: UIButton) {
  860. if (self.constraintBottomAttachment.constant != 0.0) {
  861. constraintBottomAttachment.constant = 0.0
  862. self.viewSticker.removeConstraints(self.viewSticker.constraints)
  863. self.viewSticker.removeFromSuperview()
  864. }
  865. let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
  866. if let action = self.actionImageVideo(for: "imageCamera", title: "Take Photo".localized()) {
  867. alertController.addAction(action)
  868. }
  869. if let action = self.actionImageVideo(for: "videoCamera", title: "Take Video".localized()) {
  870. alertController.addAction(action)
  871. }
  872. alertController.addAction(UIAlertAction(title: "Cancel".localized(), style: .cancel, handler: nil))
  873. self.present(alertController, animated: true)
  874. }
  875. @IBAction func stickerTapped(_ sender: UIButton) {
  876. DispatchQueue.main.async {
  877. if (self.constraintBottomAttachment.constant == 0.0) {
  878. self.constraintBottomAttachment.constant = 200.0
  879. self.view.addSubview(self.viewSticker)
  880. self.viewSticker.translatesAutoresizingMaskIntoConstraints = false
  881. NSLayoutConstraint.activate([
  882. self.viewSticker.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
  883. self.viewSticker.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
  884. self.viewSticker.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
  885. self.viewSticker.heightAnchor.constraint(equalToConstant: 200)
  886. ])
  887. let layout = UICollectionViewFlowLayout()
  888. layout.scrollDirection = .vertical
  889. let collectionSticker = UICollectionView(frame: .zero, collectionViewLayout: layout)
  890. collectionSticker.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cellSticker")
  891. collectionSticker.delegate = self
  892. collectionSticker.dataSource = self
  893. collectionSticker.backgroundColor = .clear
  894. self.viewSticker.addSubview(collectionSticker)
  895. collectionSticker.translatesAutoresizingMaskIntoConstraints = false
  896. NSLayoutConstraint.activate([
  897. collectionSticker.topAnchor.constraint(equalTo: self.viewSticker.topAnchor, constant: 20),
  898. collectionSticker.bottomAnchor.constraint(equalTo: self.viewSticker.bottomAnchor, constant: -20),
  899. collectionSticker.leadingAnchor.constraint(equalTo: self.viewSticker.leadingAnchor, constant: 20),
  900. collectionSticker.trailingAnchor.constraint(equalTo: self.viewSticker.trailingAnchor, constant: -20)
  901. ])
  902. if (self.currentIndexpath != nil) {
  903. DispatchQueue.main.async {
  904. self.tableChatView.scrollToRow(at: IndexPath(row: self.currentIndexpath!.row, section: self.currentIndexpath!.section), at: .none, animated: false)
  905. }
  906. } else {
  907. self.tableChatView.scrollToBottom()
  908. }
  909. } else {
  910. self.constraintBottomAttachment.constant = 0.0
  911. self.viewSticker.removeConstraints(self.viewSticker.constraints)
  912. self.viewSticker.removeFromSuperview()
  913. }
  914. }
  915. }
  916. @IBAction func fileTapped(_ sender: UIButton) {
  917. if (self.constraintBottomAttachment.constant != 0.0) {
  918. constraintBottomAttachment.constant = 0.0
  919. self.viewSticker.removeConstraints(self.viewSticker.constraints)
  920. self.viewSticker.removeFromSuperview()
  921. }
  922. documentPicker.present()
  923. }
  924. @objc func didTapExit() {
  925. UserDefaults.standard.removeObject(forKey: "inEditorGroup")
  926. NotificationCenter.default.removeObserver(self)
  927. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "refreshView"), object: nil, userInfo: nil)
  928. self.dismiss(animated: true, completion: nil)
  929. }
  930. @objc func profilePersonTapped(_ sender: ObjectGesture) {
  931. if isHistoryCC {
  932. return
  933. }
  934. let idMe = UserDefaults.standard.string(forKey: "me") as String?
  935. if sender.message_id == idMe {
  936. let controller = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "profileView") as! ProfileViewController
  937. controller.data = sender.message_id
  938. controller.flag = .me
  939. navigationController?.show(controller, sender: nil)
  940. } else {
  941. let data = User.getData(pin: sender.message_id)
  942. if data != nil {
  943. let controller = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "profileView") as! ProfileViewController
  944. controller.flag = .friend
  945. controller.user = data
  946. controller.name = data!.fullName
  947. controller.data = sender.message_id
  948. controller.picture = data!.thumb
  949. self.navigationController?.show(controller, sender: nil)
  950. } else {
  951. let dataUser = getDataProfile(f_pin: sender.message_id, message_id: "")
  952. let controller = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "profileView") as! ProfileViewController
  953. controller.flag = .invite
  954. controller.user = nil
  955. controller.name = dataUser["name"]!
  956. controller.data = sender.message_id
  957. controller.picture = dataUser["image_id"]!
  958. self.navigationController?.show(controller, sender: nil)
  959. }
  960. }
  961. }
  962. @objc func seeProfileTapped() {
  963. if isHistoryCC || removed || copySession || forwardSession || deleteSession || (dataGroup["official"] as? String == "1" && (dataGroup["parent"] as? String)!.isEmpty) {
  964. return
  965. }
  966. dismissKeyboard()
  967. let controller = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "groupDetailView") as! GroupDetailViewController
  968. controller.data = dataGroup["group_id"] as! String
  969. controller.checkReadMessage = {
  970. if self.currentIndexpath == nil {
  971. var listData = self.dataMessages
  972. listData = listData.filter({$0["status"] as! String != "4" && $0["status"] as! String != "8"})
  973. if listData.count != 0 {
  974. let idMe = UserDefaults.standard.string(forKey: "me") as String?
  975. for i in 0...listData.count - 1 {
  976. if listData[i]["f_pin"] as? String != idMe {
  977. self.sendReadMessageStatus(chat_id: self.dataTopic["chat_id"] as! String, f_pin: listData[i]["f_pin"] as! String, message_scope_id: "4", message_id: listData[i]["message_id"] as! String)
  978. }
  979. }
  980. }
  981. } else {
  982. let dataMessages = self.dataMessages.filter({ $0["chat_date"] as! String == self.dataDates[self.currentIndexpath!.section] })
  983. var listData = dataMessages
  984. listData = listData.filter({$0["status"] as! String != "4" && $0["status"] as! String != "8"})
  985. if listData.count != 0 {
  986. let idMe = UserDefaults.standard.string(forKey: "me") as String?
  987. for i in 0...listData.count - 1 {
  988. if listData[i]["f_pin"] as? String != idMe {
  989. self.sendReadMessageStatus(chat_id: self.dataTopic["chat_id"] as! String, f_pin: listData[i]["f_pin"] as! String, message_scope_id: "4", message_id: listData[i]["message_id"] as! String)
  990. }
  991. }
  992. }
  993. }
  994. }
  995. navigationController?.show(controller, sender: nil)
  996. }
  997. @objc func dismissKeyboard() {
  998. if isSearching {
  999. searchBar.resignFirstResponder()
  1000. } else {
  1001. textFieldSend.resignFirstResponder() // dismiss keyoard
  1002. if (self.constraintBottomAttachment.constant != 0.0) {
  1003. constraintBottomAttachment.constant = 0.0
  1004. self.viewSticker.removeConstraints(self.viewSticker.constraints)
  1005. self.viewSticker.removeFromSuperview()
  1006. }
  1007. }
  1008. }
  1009. @objc func keyboardWillShow(notification: NSNotification) {
  1010. if self.viewIfLoaded?.window != nil {
  1011. if (self.constraintBottomAttachment.constant != 0.0) {
  1012. self.constraintBottomAttachment.constant = 0.0
  1013. self.viewSticker.removeConstraints(self.viewSticker.constraints)
  1014. self.viewSticker.removeFromSuperview()
  1015. }
  1016. let info:NSDictionary = notification.userInfo! as NSDictionary
  1017. let keyboardSize = (info[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
  1018. let keyboardHeight: CGFloat = keyboardSize.height
  1019. let duration: CGFloat = info[UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber as! CGFloat
  1020. if self.constraintViewTextField.constant != keyboardHeight - 60 {
  1021. self.constraintViewTextField.constant = keyboardHeight - 60
  1022. if isSearching {
  1023. self.constraintViewTextField.constant = self.constraintViewTextField.constant + 60
  1024. self.constraintBottomContainerMultpileSelectSession.constant = -keyboardHeight
  1025. }
  1026. UIView.animate(withDuration: TimeInterval(duration), animations: {
  1027. self.view.layoutIfNeeded()
  1028. })
  1029. if isSearching {
  1030. self.tableChatView.scrollToBottom()
  1031. } else {
  1032. if (self.currentIndexpath != nil) {
  1033. self.tableChatView.scrollToRow(at: IndexPath(row: self.currentIndexpath!.row, section: self.currentIndexpath!.section), at: .none, animated: false)
  1034. } else {
  1035. self.tableChatView.scrollToBottom()
  1036. }
  1037. }
  1038. }
  1039. }
  1040. }
  1041. @objc func keyboardWillHide(notification: NSNotification) {
  1042. if self.viewIfLoaded?.window != nil {
  1043. let info:NSDictionary = notification.userInfo! as NSDictionary
  1044. let duration: CGFloat = info[UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber as! CGFloat
  1045. self.constraintViewTextField.constant = 0
  1046. self.constraintBottomContainerMultpileSelectSession.constant = 0
  1047. UIView.animate(withDuration: TimeInterval(duration), animations: {
  1048. self.view.layoutIfNeeded()
  1049. })
  1050. }
  1051. }
  1052. @objc func showChooserACKConfidential() {
  1053. let alertController = UIAlertController(title: "Message Mode".localized(), message: "Select".localized() + " " + "Message Mode".localized(), preferredStyle: .actionSheet)
  1054. let imageAck = resizeImage(image: UIImage(named: "ack_icon", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!, targetSize: CGSize(width: 30, height: 30)).withRenderingMode(.alwaysOriginal)
  1055. let ackAction = UIAlertAction(title: "Confirmation Message".localized(), style: .default, handler: { (UIAlertAction) in
  1056. if !self.isAck {
  1057. self.isAck = true
  1058. self.buttonAckConfidential.setImage(imageAck, for: .normal)
  1059. }
  1060. })
  1061. ackAction.setValue(imageAck, forKey: "image")
  1062. alertController.addAction(ackAction)
  1063. alertController.addAction(UIAlertAction(title: "Cancel".localized(), style: .cancel, handler: { (UIAlertAction) in
  1064. self.isAck = false
  1065. self.buttonAckConfidential.setImage(UIImage(systemName: "gearshape.fill", withConfiguration: UIImage.SymbolConfiguration(scale: .large))?.withTintColor(.white).withRenderingMode(.alwaysTemplate), for: .normal)
  1066. }))
  1067. self.present(alertController, animated: true, completion: nil)
  1068. }
  1069. public func setAckConfidential(isAck: Bool, isConfidential: Bool) {
  1070. self.isAck = isAck
  1071. let imageAck = resizeImage(image: UIImage(named: "ack_icon", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!, targetSize: CGSize(width: 30, height: 30)).withRenderingMode(.alwaysOriginal)
  1072. if isAck {
  1073. buttonAckConfidential.setImage(imageAck, for: .normal)
  1074. } else {
  1075. self.buttonAckConfidential.setImage(UIImage(systemName: "gearshape.fill", withConfiguration: UIImage.SymbolConfiguration(scale: .large))?.withTintColor(.white).withRenderingMode(.alwaysTemplate), for: .normal)
  1076. }
  1077. }
  1078. @objc func sendTapped() {
  1079. sendChat(message_text: textFieldSend.text!, viewController: self)
  1080. }
  1081. private func sendChat(message_scope_id:String = "4", status:String = "2", message_text:String = "", credential:String = "0", attachment_flag: String = "0", ex_blog_id: String = "", message_large_text: String = "", ex_format: String = "", image_id: String = "", audio_id: String = "", video_id: String = "", file_id: String = "", thumb_id: String = "", reff_id: String = "", read_receipts: String = "", is_call_center: String = "0", call_center_id: String = "", viewController: UIViewController) {
  1082. if viewController is EditorGroup && file_id == "" && dataMessageForward == nil {
  1083. if ((textFieldSend.text!.trimmingCharacters(in: .whitespacesAndNewlines) == "Send message".localized() && textFieldSend.textColor == UIColor.lightGray && attachment_flag != "11") || textFieldSend.text!.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ) {
  1084. dismissKeyboard()
  1085. viewController.showToast(message: "Type Messages".localized(), font: UIFont.systemFont(ofSize: 12, weight: .medium), controller: self)
  1086. if (textFieldSend.text!.trimmingCharacters(in: .whitespacesAndNewlines) != "Send message".localized()) {
  1087. textFieldSend.text = ""
  1088. }
  1089. if (self.heightTextFieldSend.constant != 40) {
  1090. self.heightTextFieldSend.constant = 40
  1091. }
  1092. return
  1093. }
  1094. }
  1095. var reff_id = reff_id
  1096. if (reffId != nil) {
  1097. reff_id = reffId!
  1098. }
  1099. let message_text = message_text.trimmingCharacters(in: .whitespacesAndNewlines)
  1100. let idMe = UserDefaults.standard.string(forKey: "me") as String?
  1101. var opposite_pin = self.dataGroup["group_id"] as! String
  1102. if (self.dataTopic["chat_id"] as! String != "") {
  1103. opposite_pin = self.dataTopic["chat_id"] as! String
  1104. }
  1105. var read_receipts = read_receipts
  1106. if isAck {
  1107. read_receipts = "8"
  1108. }
  1109. let message = CoreMessage_TMessageBank.sendMessage(l_pin: dataGroup["group_id"] as! String, message_scope_id: message_scope_id, status: status, message_text: message_text, credential: credential, attachment_flag: attachment_flag, ex_blog_id: ex_blog_id, message_large_text: message_large_text, ex_format: ex_format, image_id: image_id, audio_id: audio_id, video_id: video_id, file_id: file_id, thumb_id: thumb_id, reff_id: reff_id, read_receipts: read_receipts, chat_id: dataTopic["chat_id"] as! String, is_call_center: is_call_center, call_center_id: call_center_id, opposite_pin: opposite_pin)
  1110. Nexilis.addQueueMessage(message: message)
  1111. let messageId = String(message.mBodies[CoreMessage_TMessageKey.MESSAGE_ID]!)
  1112. var row: [String: Any?] = [:]
  1113. row["message_id"] = messageId
  1114. row["f_pin"] = idMe
  1115. row["l_pin"] = dataGroup["group_id"]!!
  1116. row["message_scope_id"] = message_scope_id
  1117. row["server_date"] = "\(Date().currentTimeMillis())"
  1118. row["status"] = status
  1119. row["message_text"] = message_text
  1120. row["audio_id"] = audio_id
  1121. row["video_id"] = video_id
  1122. row["image_id"] = image_id
  1123. row["thumb_id"] = thumb_id
  1124. row["read_receipts"] = read_receipts
  1125. row["chat_id"] = dataTopic["chat_id"]!!
  1126. row["file_id"] = file_id
  1127. row["attachment_flag"] = attachment_flag
  1128. row["reff_id"] = reff_id
  1129. row["progress"] = 0.0
  1130. row["lock"] = "0"
  1131. row["is_stared"] = "0"
  1132. row["isSelected"] = false
  1133. if !dataDates.contains("Today".localized()){
  1134. dataDates.append("Today".localized())
  1135. tableChatView.insertSections(IndexSet(integer: dataDates.count - 1), with: .fade)
  1136. }
  1137. row["chat_date"] = "Today".localized()
  1138. dataMessages.append(row)
  1139. tableChatView.insertRows(at: [IndexPath(row: dataMessages.filter({ $0["chat_date"] as! String == dataDates[dataDates.count - 1]}).count - 1, section: dataDates.count - 1)], with: .fade)
  1140. if textFieldSend.text!.trimmingCharacters(in: .whitespacesAndNewlines) != "Send message".localized() && textFieldSend.textColor != UIColor.lightGray && constraintViewTextField.constant == 0 {
  1141. textFieldSend.text = "Send message".localized()
  1142. textFieldSend.textColor = UIColor.lightGray
  1143. } else if constraintViewTextField.constant != 0 {
  1144. textFieldSend.text = ""
  1145. heightTextFieldSend.constant = 40
  1146. }
  1147. deleteReplyView()
  1148. deleteLinkPreview()
  1149. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1150. self.tableChatView.scrollToBottom()
  1151. if self.markerCounter != nil {
  1152. self.markerCounter = nil
  1153. self.tableChatView.reloadData()
  1154. }
  1155. }
  1156. }
  1157. private func getCounter() {
  1158. Database().database?.inTransaction({ fmdb, rollback in
  1159. var l_pin = self.dataGroup["group_id"]!!
  1160. if (self.dataTopic["chat_id"] as! String != "") {
  1161. l_pin = self.dataTopic["chat_id"] as! String
  1162. }
  1163. if let c = Database().getRecords(fmdb: fmdb, query: "SELECT counter FROM MESSAGE_SUMMARY where l_pin='\(l_pin)'"), c.next() {
  1164. counter = Int(c.int(forColumnIndex: 0))
  1165. c.close()
  1166. }
  1167. })
  1168. }
  1169. private func updateCounter(counter: Int) {
  1170. DispatchQueue.global().async {
  1171. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1172. var l_pin = self.dataGroup["group_id"]!!
  1173. if (self.dataTopic["chat_id"] as! String != "") {
  1174. l_pin = self.dataTopic["chat_id"] as! String
  1175. }
  1176. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE_SUMMARY", cvalues: [
  1177. "counter" : "\(counter)"
  1178. ], _where: "l_pin = '\(l_pin)'")
  1179. })
  1180. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "reloadTabChats"), object: nil, userInfo: nil)
  1181. }
  1182. }
  1183. private func disableEditor() {
  1184. view.addSubview(containerAction)
  1185. containerAction.translatesAutoresizingMaskIntoConstraints = false
  1186. NSLayoutConstraint.activate([
  1187. containerAction.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
  1188. containerAction.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
  1189. containerAction.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
  1190. containerAction.heightAnchor.constraint(equalToConstant: 120)
  1191. ])
  1192. containerAction.backgroundColor = .secondaryColor.withAlphaComponent(0.8)
  1193. let labelDisable = UILabel()
  1194. containerAction.addSubview(labelDisable)
  1195. labelDisable.translatesAutoresizingMaskIntoConstraints = false
  1196. NSLayoutConstraint.activate([
  1197. labelDisable.centerYAnchor.constraint(equalTo: containerAction.centerYAnchor),
  1198. labelDisable.centerXAnchor.constraint(equalTo: containerAction.centerXAnchor),
  1199. ])
  1200. labelDisable.textColor = .black
  1201. labelDisable.font = UIFont.systemFont(ofSize: 12).bold
  1202. labelDisable.text = "Call Center Session has ended".localized()
  1203. }
  1204. private func addButtonScrollToBottom() {
  1205. self.view.addSubview(buttonScrollToBottom)
  1206. buttonScrollToBottom.translatesAutoresizingMaskIntoConstraints = false
  1207. NSLayoutConstraint.activate([
  1208. buttonScrollToBottom.bottomAnchor.constraint(equalTo: buttonSendChat.topAnchor, constant: -50),
  1209. buttonScrollToBottom.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
  1210. buttonScrollToBottom.widthAnchor.constraint(equalToConstant: 60),
  1211. buttonScrollToBottom.heightAnchor.constraint(equalToConstant: 30.0)
  1212. ])
  1213. buttonScrollToBottom.backgroundColor = .greenColor
  1214. buttonScrollToBottom.setImage(UIImage(systemName: "chevron.down.circle"), for: .normal)
  1215. buttonScrollToBottom.imageView?.contentMode = .scaleAspectFit
  1216. buttonScrollToBottom.imageView?.tintColor = .white
  1217. buttonScrollToBottom.contentVerticalAlignment = .fill
  1218. buttonScrollToBottom.contentHorizontalAlignment = .fill
  1219. buttonScrollToBottom.imageEdgeInsets.top = 2.0
  1220. buttonScrollToBottom.imageEdgeInsets.bottom = 2.0
  1221. buttonScrollToBottom.layer.cornerRadius = 10.0
  1222. buttonScrollToBottom.layer.maskedCorners = [.layerMinXMinYCorner, .layerMinXMaxYCorner]
  1223. buttonScrollToBottom.clipsToBounds = true
  1224. buttonScrollToBottom.addTarget(self, action: #selector(scrollTobottomAction), for: .touchUpInside)
  1225. }
  1226. private func addCounterAtButttonScrollToBottom() {
  1227. self.view.addSubview(indicatorCounterBSTB)
  1228. indicatorCounterBSTB.translatesAutoresizingMaskIntoConstraints = false
  1229. indicatorCounterBSTB.backgroundColor = .systemRed
  1230. indicatorCounterBSTB.layer.cornerRadius = 7.5
  1231. indicatorCounterBSTB.clipsToBounds = true
  1232. indicatorCounterBSTB.layer.borderWidth = 0.5
  1233. indicatorCounterBSTB.layer.borderColor = UIColor.secondaryColor.cgColor
  1234. NSLayoutConstraint.activate([
  1235. indicatorCounterBSTB.bottomAnchor.constraint(equalTo: buttonScrollToBottom.topAnchor, constant: 5),
  1236. indicatorCounterBSTB.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -50),
  1237. indicatorCounterBSTB.widthAnchor.constraint(greaterThanOrEqualToConstant: 15),
  1238. indicatorCounterBSTB.heightAnchor.constraint(equalToConstant: 15)
  1239. ])
  1240. indicatorCounterBSTB.addSubview(labelCounter)
  1241. labelCounter.translatesAutoresizingMaskIntoConstraints = false
  1242. NSLayoutConstraint.activate([
  1243. labelCounter.leadingAnchor.constraint(equalTo: indicatorCounterBSTB.leadingAnchor, constant: 2),
  1244. labelCounter.trailingAnchor.constraint(equalTo: indicatorCounterBSTB.trailingAnchor, constant: -2),
  1245. labelCounter.centerXAnchor.constraint(equalTo: indicatorCounterBSTB.centerXAnchor),
  1246. ])
  1247. labelCounter.font = UIFont.systemFont(ofSize: 11)
  1248. labelCounter.text = "\(counter)"
  1249. labelCounter.textColor = .secondaryColor
  1250. labelCounter.textAlignment = .center
  1251. }
  1252. @objc func scrollTobottomAction() {
  1253. tableChatView.scrollToBottom()
  1254. DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) { [self] in
  1255. if buttonScrollToBottom.isDescendant(of: self.view) {
  1256. buttonScrollToBottom.removeConstraints(buttonScrollToBottom.constraints)
  1257. buttonScrollToBottom.removeFromSuperview()
  1258. if indicatorCounterBSTB.isDescendant(of: self.view) {
  1259. indicatorCounterBSTB.removeConstraints(indicatorCounterBSTB.constraints)
  1260. indicatorCounterBSTB.removeFromSuperview()
  1261. }
  1262. }
  1263. }
  1264. }
  1265. private func sendReadMessageStatus(chat_id: String, f_pin: String, message_scope_id: String, message_id: String) {
  1266. let message = CoreMessage_TMessageBank.getUpdateRead(p_chat_id: chat_id, p_f_pin: f_pin, p_scope_id: message_scope_id, qty: 1)
  1267. let fPin = message.getBody(key: CoreMessage_TMessageKey.F_PIN)
  1268. let scope = message.getBody(key: CoreMessage_TMessageKey.SCOPE_ID)
  1269. message.mBodies[CoreMessage_TMessageKey.SERVER_DATE] = String(Date().currentTimeMillis())
  1270. if (fPin.elementsEqual("-999") || scope.elementsEqual("16") || scope.elementsEqual("15")){
  1271. return
  1272. }
  1273. DispatchQueue.global().async {
  1274. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1275. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE", cvalues: [
  1276. "status" : "4"
  1277. ], _where: "message_id = '\(message_id)'")
  1278. })
  1279. message.mStatus = CoreMessage_TMessageUtil.getTID()
  1280. message.mBodies[CoreMessage_TMessageKey.L_PIN] = f_pin
  1281. message.mBodies[CoreMessage_TMessageKey.MESSAGE_ID] = "-2,\(message_id)"
  1282. _ = Nexilis.write(message: message)
  1283. }
  1284. if let index = dataMessages.firstIndex(where: {$0["message_id"] as? String == message_id}) {
  1285. dataMessages[index]["status"] = "4"
  1286. let auto = UserDefaults.standard.bool(forKey: "autoDownload")
  1287. if auto {
  1288. if dataMessages[index]["image_id"] as? String != nil && !((dataMessages[index]["image_id"] as? String)!.isEmpty) {
  1289. Download().start(forKey:dataMessages[index]["image_id"] as! String) { (name, progress) in
  1290. guard progress == 100 else {
  1291. return
  1292. }
  1293. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  1294. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  1295. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  1296. if let dirPath = paths.first {
  1297. let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(self.dataMessages[index]["image_id"] as! String)
  1298. let image = UIImage(contentsOfFile: imageURL.path)
  1299. let save = UserDefaults.standard.bool(forKey: "saveToGallery")
  1300. if save {
  1301. UIImageWriteToSavedPhotosAlbum(image!, nil, nil, nil)
  1302. }
  1303. }
  1304. DispatchQueue.main.async { [self] in
  1305. let section = self.dataDates.firstIndex(of: dataMessages[index]["chat_date"] as! String)
  1306. let row = self.dataMessages.filter({$0["chat_date"] as! String == dataMessages[index]["chat_date"] as! String}).firstIndex(where: { $0["message_id"] as? String == message_id})
  1307. if row != nil && section != nil{
  1308. tableChatView.reloadRows(at: [IndexPath(row: row!, section: section!)], with: .automatic)
  1309. }
  1310. }
  1311. }
  1312. } else if dataMessages[index]["video_id"] as? String != nil && !((dataMessages[index]["video_id"] as? String)!.isEmpty){
  1313. let section = dataDates.firstIndex(of: dataMessages[index]["chat_date"] as! String)
  1314. let row = dataMessages.filter({$0["chat_date"] as! String == dataMessages[index]["chat_date"] as! String}).firstIndex(where: { $0["message_id"] as? String == message_id})
  1315. if row != nil && section != nil{
  1316. let indexPath = IndexPath(row: row!, section: section!)
  1317. if let cell = tableChatView.cellForRow(at: indexPath) {
  1318. for view in cell.contentView.subviews {
  1319. if view is UIImageView {
  1320. let objectTap = ObjectGesture()
  1321. objectTap.video_id = dataMessages[index]["video_id"] as! String
  1322. objectTap.imageView = view as! UIImageView
  1323. objectTap.indexPath = indexPath
  1324. contentMessageTapped(objectTap)
  1325. break
  1326. }
  1327. }
  1328. }
  1329. }
  1330. }
  1331. }
  1332. }
  1333. }
  1334. private func sendTyping(l_pin: String, isTyping: Bool = false) {
  1335. DispatchQueue.global().async {
  1336. let tmessage = CoreMessage_TMessageBank.getUpdateTypingStatus(p_opposite: l_pin, p_scope: "4", p_status: isTyping ? "3": "4")
  1337. _ = Nexilis.write(message: tmessage)
  1338. }
  1339. }
  1340. private func checkNewMessage(tableView: UITableView) {
  1341. currentIndexpath = tableView.indexPathsForVisibleRows?.last
  1342. if currentIndexpath != nil {
  1343. let dataMessages = dataMessages.filter({ $0["chat_date"] as! String == dataDates[currentIndexpath!.section] })
  1344. if dataMessages.count == 0 {
  1345. return
  1346. }
  1347. if currentIndexpath!.section == dataDates.count - 1 && currentIndexpath!.row != dataMessages.count - 1 && currentIndexpath!.row != dataMessages.count - 2 && !buttonScrollToBottom.isDescendant(of: self.view) {
  1348. addButtonScrollToBottom()
  1349. addCounterAtButttonScrollToBottom()
  1350. } else if currentIndexpath!.section == dataDates.count - 1 && currentIndexpath!.row == dataMessages.count - 1 {
  1351. if buttonScrollToBottom.isDescendant(of: self.view) {
  1352. buttonScrollToBottom.removeConstraints(buttonScrollToBottom.constraints)
  1353. buttonScrollToBottom.removeFromSuperview()
  1354. if indicatorCounterBSTB.isDescendant(of: self.view) {
  1355. indicatorCounterBSTB.removeConstraints(indicatorCounterBSTB.constraints)
  1356. indicatorCounterBSTB.removeFromSuperview()
  1357. }
  1358. }
  1359. }
  1360. if dataMessages.count - 1 < currentIndexpath!.row {
  1361. return
  1362. }
  1363. var listData = dataMessages[0...currentIndexpath!.row]
  1364. listData = listData.filter({$0["status"] as! String != "4" && $0["status"] as! String != "8"})
  1365. if listData.count != 0 {
  1366. let idMe = UserDefaults.standard.string(forKey: "me") as String?
  1367. for i in 0...listData.count - 1 {
  1368. if listData[i]["f_pin"] as? String != idMe {
  1369. sendReadMessageStatus(chat_id: self.dataTopic["chat_id"] as! String, f_pin: listData[i]["f_pin"] as! String, message_scope_id: "4", message_id: listData[i]["message_id"] as! String)
  1370. }
  1371. }
  1372. }
  1373. }
  1374. if counter == 0 && indicatorCounterBSTB.isDescendant(of: self.view) {
  1375. indicatorCounterBSTB.removeConstraints(indicatorCounterBSTB.constraints)
  1376. indicatorCounterBSTB.removeFromSuperview()
  1377. } else if counter != 0 && currentIndexpath != nil {
  1378. let dataFilter = dataMessages.filter({ $0["chat_date"] as! String == dataDates[currentIndexpath!.section] })
  1379. if dataFilter.count == 0 {
  1380. return
  1381. }
  1382. let idx = dataMessages.firstIndex(where: { $0["message_id"] as! String == dataFilter[currentIndexpath!.row]["message_id"] as! String})
  1383. if idx == nil {
  1384. return
  1385. }
  1386. if (dataMessages.count - counter) <= idx! {
  1387. let countUpdate = idx! - (dataMessages.count - counter)
  1388. counter = counter - (countUpdate + 1)
  1389. if indicatorCounterBSTB.isDescendant(of: self.view) {
  1390. labelCounter.text = "\(counter)"
  1391. }
  1392. updateCounter(counter: counter)
  1393. }
  1394. }
  1395. }
  1396. }
  1397. extension EditorGroup: ImageVideoPickerDelegate, PreviewAttachmentImageVideoDelegate {
  1398. public func didSelect(imagevideo: Any?) {
  1399. if (imagevideo != nil) {
  1400. let imageVideoData = imagevideo as! [UIImagePickerController.InfoKey: Any]
  1401. let previewImageVC = PreviewAttachmentImageVideo(nibName: "PreviewAttachmentImageVideo", bundle: Bundle.resourceBundle(for: Nexilis.self))
  1402. previewImageVC.imageVideoData = imageVideoData
  1403. if (textFieldSend.textColor != .lightGray) {
  1404. previewImageVC.currentTextTextField = textFieldSend.text
  1405. }
  1406. previewImageVC.modalPresentationStyle = .custom
  1407. previewImageVC.delegate = self
  1408. previewImageVC.isGroup = true
  1409. previewImageVC.isAck = self.isAck
  1410. self.present(previewImageVC, animated: true, completion: nil)
  1411. }
  1412. }
  1413. func sendChatFromPreviewImage(message_text: String, attachment_flag: String, image_id: String, video_id: String, thumb_id: String, viewController: UIViewController) {
  1414. sendChat(message_text: message_text, attachment_flag: attachment_flag, image_id: image_id, video_id: video_id, thumb_id: thumb_id, viewController: viewController)
  1415. }
  1416. }
  1417. extension EditorGroup: UIDocumentPickerDelegate, DocumentPickerDelegate, QLPreviewControllerDataSource {
  1418. public func didSelectDocument(document: Any?) {
  1419. if (document != nil) {
  1420. self.previewItem = (document as! [URL])[0] as NSURL
  1421. let previewController = QLPreviewController()
  1422. let navController = UINavigationController(rootViewController: previewController)
  1423. let leftBarButton = navigationQLPreviewDocument(title: "Cancel".localized(), style: .plain, target: self, action: #selector(cancelDocumentPreview))
  1424. let rightBarButton = navigationQLPreviewDocument(title: "Send".localized(), style: .done, target: self, action: #selector(sendDocument))
  1425. // leftBarButton.tintColor = .white
  1426. // rightBarButton.tintColor = .white
  1427. leftBarButton.navigation = navController
  1428. rightBarButton.navigation = navController
  1429. // navController.navigationBar.barTintColor = .mainColor
  1430. navController.navigationBar.isTranslucent = false
  1431. previewController.navigationItem.leftBarButtonItem = leftBarButton
  1432. previewController.navigationItem.rightBarButtonItem = rightBarButton
  1433. previewController.dataSource = self
  1434. previewController.modalPresentationStyle = .pageSheet
  1435. self.present(navController, animated: true, completion: nil)
  1436. }
  1437. }
  1438. @objc private func cancelDocumentPreview(sender: navigationQLPreviewDocument) {
  1439. sender.navigation.dismiss(animated: true, completion: nil)
  1440. }
  1441. @objc private func sendDocument(sender: navigationQLPreviewDocument) {
  1442. sender.navigation.dismiss(animated: true, completion: nil)
  1443. do {
  1444. let dataFile = try Data(contentsOf: self.previewItem! as URL)
  1445. let urlFile = self.previewItem?.absoluteString
  1446. var originaFileName = (urlFile! as NSString).lastPathComponent
  1447. originaFileName = NSString(string: originaFileName).removingPercentEncoding!
  1448. let renamedNameFile = "Qmera_doc_" + "\(Date().currentTimeMillis())_" + originaFileName
  1449. let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
  1450. let fileURL = documentsDirectory.appendingPathComponent(renamedNameFile)
  1451. if !FileManager.default.fileExists(atPath: fileURL.path) {
  1452. do {
  1453. try dataFile.write(to: fileURL)
  1454. print("file saved")
  1455. } catch {
  1456. print("error saving file:", error)
  1457. }
  1458. }
  1459. sendChat(message_text: "\(originaFileName)|", attachment_flag: "6", file_id: renamedNameFile, viewController: self)
  1460. } catch {
  1461. }
  1462. }
  1463. }
  1464. extension EditorGroup: UITextViewDelegate {
  1465. public func textViewDidChange(_ textView: UITextView) {
  1466. if allowTyping {
  1467. allowTyping = false
  1468. if dataTopic["chat_id"] as! String == "" {
  1469. UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [dataGroup["group_id"] as! String])
  1470. sendTyping(l_pin: dataGroup["group_id"] as! String)
  1471. } else {
  1472. UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [dataTopic["chat_id"] as! String])
  1473. sendTyping(l_pin: dataTopic["chat_id"] as! String)
  1474. }
  1475. DispatchQueue.main.asyncAfter(deadline: .now() + 4, execute: {
  1476. self.allowTyping = true
  1477. })
  1478. }
  1479. if let selectedRange = textView.selectedTextRange {
  1480. let cursorPosition = textView.offset(from: textView.beginningOfDocument, to: selectedRange.start)
  1481. let beforeCursor = textView.text.substring(from: cursorPosition - cursorPosition, to: cursorPosition - 1).split(separator: " ").last
  1482. let afterCursor = textView.text.substring(from: cursorPosition, to: textView.text.count - 1).split(separator: " ").first
  1483. var firstCount = 0
  1484. var lastCount = textView.text.count
  1485. if beforeCursor != nil {
  1486. firstCount = cursorPosition - beforeCursor!.count - 1
  1487. if firstCount == -1 {
  1488. firstCount = 0
  1489. }
  1490. if beforeCursor!.lowercased().checkStartWithLink() {
  1491. if textView.text.split(separator: " ").count > 1 && self.containerLink.isDescendant(of: self.viewTextfield) {
  1492. } else {
  1493. if ((beforeCursor!.lowercased().starts(with: "www.") && beforeCursor!.lowercased().split(separator: ".").count >= 3) || (!beforeCursor!.lowercased().starts(with: "www.") && beforeCursor!.lowercased().split(separator: ".").count >= 2)) && beforeCursor!.lowercased().split(separator: ".").last!.count >= 2 {
  1494. checkLink(text: beforeCursor!.lowercased())
  1495. } else {
  1496. deleteLinkPreview()
  1497. }
  1498. }
  1499. }
  1500. }
  1501. if afterCursor != nil {
  1502. if beforeCursor == nil {
  1503. lastCount = afterCursor!.count + 2
  1504. } else {
  1505. lastCount = beforeCursor!.count + afterCursor!.count + 2
  1506. }
  1507. if afterCursor!.lowercased().checkStartWithLink() {
  1508. if textView.text.split(separator: " ").count > 1 && self.containerLink.isDescendant(of: self.viewTextfield) {
  1509. } else {
  1510. if ((afterCursor!.lowercased().starts(with: "www.") && afterCursor!.lowercased().split(separator: ".").count >= 3) || afterCursor!.lowercased().split(separator: ".").count >= 2) && afterCursor!.lowercased().split(separator: ".").last!.count >= 2 {
  1511. checkLink(text: afterCursor!.lowercased())
  1512. } else {
  1513. deleteLinkPreview()
  1514. }
  1515. }
  1516. }
  1517. }
  1518. if textView.text.contains("*") || textView.text.contains("_") || textView.text.contains("^") || textView.text.contains("~") {
  1519. textView.preserveCursorPosition(withChanges: { _ in
  1520. textView.attributedText = textView.text.richText(isEditing: true, first: firstCount, last: lastCount)
  1521. return .preserveCursor
  1522. })
  1523. }
  1524. }
  1525. }
  1526. private func checkLink(text: String) {
  1527. var stringURl = text
  1528. if stringURl.starts(with: "www.") {
  1529. stringURl = "https://" + stringURl.replacingOccurrences(of: "www.", with: "")
  1530. }
  1531. var dataURL = ""
  1532. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1533. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "select data_link from LINK_PREVIEW where link='\(stringURl)'") {
  1534. while cursor.next() {
  1535. if let data = cursor.string(forColumnIndex: 0) {
  1536. dataURL = data
  1537. }
  1538. }
  1539. cursor.close()
  1540. }
  1541. })
  1542. if !dataURL.isEmpty {
  1543. if let data = try! JSONSerialization.jsonObject(with: dataURL.data(using: String.Encoding.utf8)!, options: []) as? [String: Any] {
  1544. let title = data["title"] as! String
  1545. let description = data["description"] as! String
  1546. let imageUrl = data["imageUrl"] as? String
  1547. self.buildPreviewLink(imageUrl: imageUrl, title: title, description: description, stringURl: text)
  1548. }
  1549. } else {
  1550. let urlData = URL(string: stringURl)!
  1551. Readability.parse(url: urlData, completion: { data in
  1552. self.deleteLinkPreview()
  1553. if data != nil {
  1554. let title = data!.title
  1555. let description = data!.description
  1556. let imageUrl = data!.topImage
  1557. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1558. do {
  1559. var dataJson: [String: Any] = [:]
  1560. dataJson["title"] = title
  1561. dataJson["description"] = description
  1562. dataJson["imageUrl"] = imageUrl
  1563. guard let json = String(data: try! JSONSerialization.data(withJSONObject: dataJson, options: []), encoding: String.Encoding.utf8) else {
  1564. return
  1565. }
  1566. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "LINK_PREVIEW", cvalues: [
  1567. "id" : "\(Date().currentTimeMillis().toHex())",
  1568. "link" : stringURl,
  1569. "data_link" : json,
  1570. "retry": 0
  1571. ], replace: true)
  1572. } catch {
  1573. rollback.pointee = true
  1574. print(error)
  1575. }
  1576. })
  1577. self.buildPreviewLink(imageUrl: imageUrl, title: title, description: description, stringURl: text)
  1578. }
  1579. })
  1580. }
  1581. }
  1582. private func buildPreviewLink(imageUrl: String?, title: String, description: String?, stringURl: String) {
  1583. UIView.animate(withDuration: 0.25, delay: 0.0, options: .curveEaseInOut, animations: {
  1584. self.constraintTopTextField.constant = self.constraintTopTextField.constant + 80
  1585. }, completion: nil)
  1586. self.viewTextfield.addSubview(self.containerLink)
  1587. self.containerLink.translatesAutoresizingMaskIntoConstraints = false
  1588. self.containerLink.leadingAnchor.constraint(equalTo: self.viewTextfield.leadingAnchor).isActive = true
  1589. self.containerLink.bottomAnchor.constraint(equalTo: self.textFieldSend.topAnchor).isActive = true
  1590. self.containerLink.trailingAnchor.constraint(equalTo: self.viewTextfield.trailingAnchor).isActive = true
  1591. self.containerLink.heightAnchor.constraint(equalToConstant: 80.0).isActive = true
  1592. self.containerLink.backgroundColor = .secondaryColor
  1593. if self.reffId != nil {
  1594. self.bottomAnchorPreviewReply.isActive = false
  1595. self.bottomAnchorPreviewReply = self.containerPreviewReply.bottomAnchor.constraint(equalTo: self.containerLink.topAnchor)
  1596. self.bottomAnchorPreviewReply.isActive = true
  1597. }
  1598. let imagePreview = UIImageView()
  1599. if imageUrl != nil {
  1600. self.containerLink.addSubview(imagePreview)
  1601. imagePreview.translatesAutoresizingMaskIntoConstraints = false
  1602. imagePreview.leadingAnchor.constraint(equalTo: self.containerLink.leadingAnchor).isActive = true
  1603. imagePreview.bottomAnchor.constraint(equalTo: self.containerLink.bottomAnchor).isActive = true
  1604. imagePreview.topAnchor.constraint(equalTo: self.containerLink.topAnchor).isActive = true
  1605. imagePreview.widthAnchor.constraint(equalToConstant: 80.0).isActive = true
  1606. if !imageUrl!.starts(with: "https://") {
  1607. imagePreview.loadImageAsync(with: "https://www.google.be" + imageUrl!)
  1608. } else {
  1609. imagePreview.loadImageAsync(with: imageUrl)
  1610. }
  1611. imagePreview.contentMode = .scaleAspectFit
  1612. }
  1613. let titlePreview = UILabel()
  1614. self.containerLink.addSubview(titlePreview)
  1615. titlePreview.translatesAutoresizingMaskIntoConstraints = false
  1616. if imageUrl != nil {
  1617. titlePreview.leadingAnchor.constraint(equalTo: imagePreview.trailingAnchor, constant: 5.0).isActive = true
  1618. } else {
  1619. titlePreview.leadingAnchor.constraint(equalTo: self.containerLink.leadingAnchor, constant: 5.0).isActive = true
  1620. }
  1621. titlePreview.topAnchor.constraint(equalTo: self.containerLink.topAnchor, constant: 25.0).isActive = true
  1622. titlePreview.trailingAnchor.constraint(equalTo: self.containerLink.trailingAnchor, constant: -80.0).isActive = true
  1623. titlePreview.text = title
  1624. titlePreview.font = UIFont.systemFont(ofSize: 14.0, weight: .bold)
  1625. titlePreview.textColor = .black
  1626. let descPreview = UILabel()
  1627. self.containerLink.addSubview(descPreview)
  1628. descPreview.translatesAutoresizingMaskIntoConstraints = false
  1629. if imageUrl != nil {
  1630. descPreview.leadingAnchor.constraint(equalTo: imagePreview.trailingAnchor, constant: 5.0).isActive = true
  1631. } else {
  1632. descPreview.leadingAnchor.constraint(equalTo: self.containerLink.leadingAnchor, constant: 5.0).isActive = true
  1633. }
  1634. descPreview.topAnchor.constraint(equalTo: titlePreview.bottomAnchor).isActive = true
  1635. descPreview.trailingAnchor.constraint(equalTo: self.containerLink.trailingAnchor, constant: -80.0).isActive = true
  1636. descPreview.text = description
  1637. descPreview.font = UIFont.systemFont(ofSize: 12.0)
  1638. descPreview.textColor = .gray
  1639. descPreview.numberOfLines = 1
  1640. let linkPreview = UILabel()
  1641. self.containerLink.addSubview(linkPreview)
  1642. linkPreview.translatesAutoresizingMaskIntoConstraints = false
  1643. if imageUrl != nil {
  1644. linkPreview.leadingAnchor.constraint(equalTo: imagePreview.trailingAnchor, constant: 5.0).isActive = true
  1645. } else {
  1646. linkPreview.leadingAnchor.constraint(equalTo: self.containerLink.leadingAnchor, constant: 5.0).isActive = true
  1647. }
  1648. linkPreview.topAnchor.constraint(equalTo: descPreview.bottomAnchor, constant: 8.0).isActive = true
  1649. linkPreview.trailingAnchor.constraint(equalTo: self.containerLink.trailingAnchor, constant: -80.0).isActive = true
  1650. linkPreview.text = stringURl
  1651. linkPreview.font = UIFont.systemFont(ofSize: 10.0)
  1652. linkPreview.textColor = .gray
  1653. linkPreview.numberOfLines = 1
  1654. let cancelPreview = UIButton(type: .custom)
  1655. self.containerLink.addSubview(cancelPreview)
  1656. cancelPreview.translatesAutoresizingMaskIntoConstraints = false
  1657. cancelPreview.trailingAnchor.constraint(equalTo: self.containerLink.trailingAnchor, constant: -10).isActive = true
  1658. cancelPreview.centerYAnchor.constraint(equalTo: self.containerLink.centerYAnchor).isActive = true
  1659. cancelPreview.setImage(UIImage(systemName: "xmark.circle" , withConfiguration: UIImage.SymbolConfiguration(pointSize: 20, weight: .regular, scale: .default)), for: .normal)
  1660. cancelPreview.addTarget(nil, action: #selector(self.deleteLinkPreview), for: .touchUpInside)
  1661. cancelPreview.backgroundColor = .clear
  1662. cancelPreview.tintColor = .mainColor
  1663. }
  1664. public func textViewDidBeginEditing(_ textView: UITextView) {
  1665. if textView.textColor == UIColor.lightGray {
  1666. textView.text = nil
  1667. textView.textColor = UIColor.black
  1668. }
  1669. }
  1670. public func textViewDidEndEditing(_ textView: UITextView) {
  1671. if textView.text.isEmpty {
  1672. textView.text = "Send message".localized()
  1673. textView.textColor = UIColor.lightGray
  1674. }
  1675. }
  1676. public override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
  1677. if action == #selector(UIResponderStandardEditActions.paste(_:)) && (UIPasteboard.general.image != nil) {
  1678. return true
  1679. }
  1680. return super.canPerformAction(action, withSender: sender)
  1681. }
  1682. public override func paste(_ sender: Any?) {
  1683. if UIPasteboard.general.image != nil {
  1684. let previewImageVC = PreviewAttachmentImageVideo(nibName: "PreviewAttachmentImageVideo", bundle: Bundle.resourceBundle(for: Nexilis.self))
  1685. previewImageVC.image = UIPasteboard.general.image
  1686. previewImageVC.fromCopy = true
  1687. previewImageVC.currentTextTextField = textFieldSend.text
  1688. previewImageVC.modalPresentationStyle = .custom
  1689. previewImageVC.delegate = self
  1690. self.present(previewImageVC, animated: true, completion: nil)
  1691. }
  1692. }
  1693. public func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
  1694. let cursorPosition = textView.caretRect(for: self.textFieldSend.selectedTextRange!.start).origin
  1695. let currentLine = Int(cursorPosition.y / self.textFieldSend.font!.lineHeight)
  1696. UIView.animate(withDuration: 0.3) {
  1697. if currentLine == 0 && text != "\n"{
  1698. self.heightTextFieldSend.constant = 40
  1699. } else if currentLine < 4 {
  1700. DispatchQueue.main.async {
  1701. if (self.currentIndexpath != nil) {
  1702. self.tableChatView.scrollToRow(at: IndexPath(row: self.currentIndexpath!.row, section: self.currentIndexpath!.section), at: .none, animated: false)
  1703. }
  1704. }
  1705. if (text == "\n" && self.textFieldSend.text.count > 0) {
  1706. self.heightTextFieldSend.constant = self.textFieldSend.contentSize.height + 18
  1707. }
  1708. else if (self.textFieldSend.text.count > 0) {
  1709. self.heightTextFieldSend.constant = self.textFieldSend.contentSize.height
  1710. }
  1711. let txt = textView.text
  1712. let txtRange = Range(range, in: txt!)
  1713. let subString: Substring = txt![txtRange!]
  1714. if subString == "\n" {
  1715. self.heightTextFieldSend.constant = self.textFieldSend.contentSize.height - 18
  1716. if (self.heightTextFieldSend.constant <= 50 && self.heightTextFieldSend.constant >= 40) {
  1717. self.heightTextFieldSend.constant = 40
  1718. }
  1719. }
  1720. }
  1721. let countBreakLine = text.split(separator: "\n").count
  1722. if countBreakLine > 1 && self.heightTextFieldSend.constant != CGFloat(40 + (countBreakLine * 18)) {
  1723. self.heightTextFieldSend.constant = CGFloat(40 + (countBreakLine * 18))
  1724. }
  1725. }
  1726. if (self.textFieldSend.text.count == 0) {
  1727. return text != "\n"
  1728. }
  1729. return true
  1730. }
  1731. }
  1732. extension EditorGroup: UIContextMenuInteractionDelegate {
  1733. public func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
  1734. if textFieldSend.isFirstResponder {
  1735. textFieldSend.resignFirstResponder()
  1736. }
  1737. let indexPath = self.tableChatView.indexPathForRow(at: interaction.view!.convert(location, to: self.tableChatView))
  1738. let dataMessages = self.dataMessages.filter({ $0["chat_date"] as! String == dataDates[indexPath!.section]})
  1739. var star: UIAction
  1740. if (dataMessages[indexPath!.row]["is_stared"] as! String == "0") {
  1741. star = UIAction(title: "Star".localized(), image: UIImage(systemName: "star.fill"), handler: {(_) in
  1742. if self.removed {
  1743. return
  1744. }
  1745. DispatchQueue.global().async {
  1746. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1747. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE", cvalues: [
  1748. "is_stared" : 1
  1749. ], _where: "message_id = '\(dataMessages[indexPath!.row]["message_id"] as! String)'")
  1750. })
  1751. }
  1752. let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as! String == dataMessages[indexPath!.row]["message_id"] as! String})
  1753. if idx != nil{
  1754. self.dataMessages[idx!]["is_stared"] = "1"
  1755. }
  1756. self.tableChatView.reloadRows(at: [indexPath!], with: .none)
  1757. })
  1758. } else {
  1759. star = UIAction(title: "Unstar".localized(), image: UIImage(systemName: "star.fill"), handler: {(_) in
  1760. if self.removed {
  1761. return
  1762. }
  1763. DispatchQueue.global().async {
  1764. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1765. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE", cvalues: [
  1766. "is_stared" : 0
  1767. ], _where: "message_id = '\(dataMessages[indexPath!.row]["message_id"] as! String)'")
  1768. })
  1769. }
  1770. let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as! String == dataMessages[indexPath!.row]["message_id"] as! String})
  1771. if idx != nil{
  1772. self.dataMessages[idx!]["is_stared"] = "0"
  1773. }
  1774. self.tableChatView.reloadRows(at: [indexPath!], with: .none)
  1775. })
  1776. }
  1777. let reply = UIAction(title: "Reply".localized(), image: UIImage(systemName: "arrowshape.turn.up.left.fill"), handler: {(_) in
  1778. if self.removed {
  1779. return
  1780. }
  1781. if self.isSearching {
  1782. self.cancelAction()
  1783. }
  1784. DispatchQueue.main.asyncAfter(deadline: .now() + 0.35, execute: {
  1785. self.handleReply(indexPath: indexPath!)
  1786. })
  1787. })
  1788. let forward = UIAction(title: "Forward".localized(), image: UIImage(systemName: "arrowshape.turn.up.right.fill"), handler: {(_) in
  1789. if self.removed {
  1790. return
  1791. }
  1792. if self.isSearching {
  1793. self.cancelAction()
  1794. }
  1795. if self.reffId != nil {
  1796. self.deleteReplyView()
  1797. }
  1798. DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) {
  1799. self.forwardSession = true
  1800. let cancelButton = UIBarButtonItem(title: "Cancel".localized(), style: .plain, target: self, action: #selector(self.cancelAction))
  1801. if !self.isHistoryCC {
  1802. self.navigationItem.rightBarButtonItems = nil
  1803. }
  1804. self.navigationItem.rightBarButtonItem = cancelButton
  1805. self.changeAppBar()
  1806. let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as? String == dataMessages[indexPath!.row]["message_id"] as? String})
  1807. if idx != nil{
  1808. self.dataMessages[idx!]["isSelected"] = true
  1809. }
  1810. self.addMultipleSelectSession()
  1811. self.tableChatView.reloadData()
  1812. }
  1813. })
  1814. let copy = UIAction(title: "Copy".localized(), image: UIImage(systemName: "doc.on.doc.fill"), handler: {(_) in
  1815. if self.removed {
  1816. return
  1817. }
  1818. if self.isSearching {
  1819. self.cancelAction()
  1820. }
  1821. if self.reffId != nil {
  1822. self.deleteReplyView()
  1823. }
  1824. DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) {
  1825. self.copySession = true
  1826. let cancelButton = UIBarButtonItem(title: "Cancel".localized(), style: .plain, target: self, action: #selector(self.cancelAction))
  1827. if !self.isHistoryCC {
  1828. self.navigationItem.rightBarButtonItems = nil
  1829. }
  1830. self.navigationItem.rightBarButtonItem = cancelButton
  1831. self.changeAppBar()
  1832. let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as? String == dataMessages[indexPath!.row]["message_id"] as? String})
  1833. if idx != nil{
  1834. self.dataMessages[idx!]["isSelected"] = true
  1835. }
  1836. self.addMultipleSelectSession()
  1837. self.tableChatView.reloadData()
  1838. }
  1839. })
  1840. let info = UIAction(title: "Info".localized(), image: UIImage(systemName: "info.circle.fill"), handler: {(_) in
  1841. if self.removed {
  1842. return
  1843. }
  1844. let messageInfoVC = MessageInfo()
  1845. messageInfoVC.data = dataMessages[indexPath!.row]
  1846. messageInfoVC.dataGroup = self.dataGroup
  1847. messageInfoVC.isPersonal = false
  1848. self.navigationController?.pushViewController(messageInfoVC, animated: true)
  1849. })
  1850. let delete = UIAction(title: "Delete".localized(), image: UIImage(systemName: "trash.fill"), attributes: .destructive, handler: {(_) in
  1851. if self.removed {
  1852. return
  1853. }
  1854. if self.isSearching {
  1855. self.cancelAction()
  1856. }
  1857. if self.reffId != nil {
  1858. self.deleteReplyView()
  1859. }
  1860. DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) {
  1861. self.deleteSession = true
  1862. let cancelButton = UIBarButtonItem(title: "Cancel".localized(), style: .plain, target: self, action: #selector(self.cancelAction))
  1863. if !self.isHistoryCC {
  1864. self.navigationItem.rightBarButtonItems = nil
  1865. }
  1866. self.navigationItem.rightBarButtonItem = cancelButton
  1867. self.changeAppBar()
  1868. let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as? String == dataMessages[indexPath!.row]["message_id"] as? String})
  1869. if idx != nil{
  1870. self.dataMessages[idx!]["isSelected"] = true
  1871. }
  1872. self.addMultipleSelectSession()
  1873. self.tableChatView.reloadData()
  1874. }
  1875. })
  1876. var children: [UIMenuElement] = [star, reply, forward, copy, delete]
  1877. // let copyOption = self.copyOption(indexPath: indexPath!)
  1878. let idMe = UserDefaults.standard.string(forKey: "me") as String?
  1879. if (dataMessages[indexPath!.row]["lock"] != nil && dataMessages[indexPath!.row]["lock"] as! String == "1") {
  1880. children = [delete]
  1881. }
  1882. else if dataMessages[indexPath!.row]["f_pin"] as! String == "-999" {
  1883. children = [star, reply ,delete]
  1884. if (dataMessages[indexPath!.row]["f_pin"] as! String) == idMe {
  1885. children.insert(info, at: children.count - 1)
  1886. }
  1887. }
  1888. else if !(dataMessages[indexPath!.row]["image_id"] as! String).isEmpty || !(dataMessages[indexPath!.row]["video_id"] as! String).isEmpty || !(dataMessages[indexPath!.row]["file_id"] as! String).isEmpty || dataMessages[indexPath!.row]["attachment_flag"] as! String == "11" {
  1889. children = [star, reply, forward ,delete]
  1890. if (dataMessages[indexPath!.row]["f_pin"] as! String) == idMe {
  1891. children.insert(info, at: children.count - 1)
  1892. }
  1893. } else {
  1894. if (dataMessages[indexPath!.row]["f_pin"] as! String) == idMe {
  1895. children.insert(info, at: children.count - 1)
  1896. }
  1897. }
  1898. return UIContextMenuConfiguration(identifier: nil,
  1899. previewProvider: nil) { _ in
  1900. UIMenu(title: "", children: children)
  1901. }
  1902. }
  1903. @objc func cancelAction() {
  1904. DispatchQueue.main.async {
  1905. if self.copySession {
  1906. self.copySession = false
  1907. } else if self.forwardSession {
  1908. self.forwardSession = false
  1909. } else if self.deleteSession {
  1910. self.deleteSession = false
  1911. } else if self.isSearching {
  1912. self.countMatchesSearch = 0
  1913. self.isSearching = false
  1914. }
  1915. if self.viewTextfield.isHidden {
  1916. self.viewTextfield.isHidden = false
  1917. }
  1918. if self.viewAttachment.isHidden {
  1919. self.viewAttachment.isHidden = false
  1920. }
  1921. if !self.isSearching {
  1922. self.constraintBottomTableViewWithTextfield.constant = self.constraintBottomTableViewWithTextfield.constant + 70
  1923. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3, execute: {
  1924. if (self.currentIndexpath != nil) {
  1925. self.tableChatView.scrollToRow(at: IndexPath(row: self.currentIndexpath!.row, section: self.currentIndexpath!.section), at: .none, animated: true)
  1926. } else {
  1927. self.tableChatView.scrollToBottom()
  1928. }
  1929. })
  1930. }
  1931. let data = self.dataMessages.filter({ $0["isSelected"] as! Bool == true })
  1932. for i in 0..<data.count {
  1933. let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as! String == data[i]["message_id"] as! String})
  1934. if idx != nil{
  1935. self.dataMessages[idx!]["isSelected"] = false
  1936. }
  1937. }
  1938. self.tableChatView.reloadData()
  1939. self.setRightButtonItem()
  1940. self.changeAppBar()
  1941. self.containerMultpileSelectSession.removeFromSuperview()
  1942. self.checkNewMessage(tableView: self.tableChatView)
  1943. }
  1944. }
  1945. private func addMultipleSelectSession() {
  1946. viewTextfield.isHidden = true
  1947. viewAttachment.isHidden = true
  1948. constraintBottomTableViewWithTextfield.constant = constraintBottomTableViewWithTextfield.constant - 70
  1949. view.addSubview(containerMultpileSelectSession)
  1950. containerMultpileSelectSession.translatesAutoresizingMaskIntoConstraints = false
  1951. constraintBottomContainerMultpileSelectSession = containerMultpileSelectSession.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: 0)
  1952. NSLayoutConstraint.activate([
  1953. containerMultpileSelectSession.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
  1954. containerMultpileSelectSession.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
  1955. constraintBottomContainerMultpileSelectSession,
  1956. containerMultpileSelectSession.heightAnchor.constraint(equalToConstant: 50)
  1957. ])
  1958. containerMultpileSelectSession.backgroundColor = .white
  1959. addSubviewMultipleSession()
  1960. }
  1961. private func addSubviewMultipleSession() {
  1962. let container = UIView()
  1963. containerMultpileSelectSession.addSubview(container)
  1964. container.translatesAutoresizingMaskIntoConstraints = false
  1965. NSLayoutConstraint.activate([
  1966. container.leadingAnchor.constraint(equalTo: containerMultpileSelectSession.leadingAnchor),
  1967. container.trailingAnchor.constraint(equalTo:containerMultpileSelectSession.trailingAnchor),
  1968. container.bottomAnchor.constraint(equalTo: containerMultpileSelectSession.bottomAnchor),
  1969. container.heightAnchor.constraint(equalToConstant: 50)
  1970. ])
  1971. container.layer.shadowOpacity = 0.7
  1972. container.layer.shadowOffset = CGSize(width: 3, height: 3)
  1973. container.layer.shadowRadius = 3.0
  1974. container.layer.shadowColor = UIColor.black.cgColor
  1975. container.backgroundColor = .secondaryColor
  1976. if !isSearching {
  1977. let title = UILabel()
  1978. container.addSubview(title)
  1979. title.translatesAutoresizingMaskIntoConstraints = false
  1980. NSLayoutConstraint.activate([
  1981. title.centerXAnchor.constraint(equalTo: container.centerXAnchor),
  1982. title.centerYAnchor.constraint(equalTo:container.centerYAnchor),
  1983. ])
  1984. let countSelected = dataMessages.filter({ $0["isSelected"] as! Bool == true }).count
  1985. title.text = "\(countSelected) " + "Selected".localized()
  1986. title.textColor = .mainColor
  1987. title.font = UIFont.systemFont(ofSize: 15).bold
  1988. let button = UIImageView()
  1989. container.addSubview(button)
  1990. button.translatesAutoresizingMaskIntoConstraints = false
  1991. NSLayoutConstraint.activate([
  1992. button.leadingAnchor.constraint(equalTo: container.leadingAnchor, constant: 15),
  1993. button.centerYAnchor.constraint(equalTo:container.centerYAnchor),
  1994. button.widthAnchor.constraint(equalToConstant: 30),
  1995. button.heightAnchor.constraint(equalToConstant: 30),
  1996. ])
  1997. if copySession {
  1998. button.image = UIImage(systemName: "doc.on.doc")
  1999. if countSelected == 0{
  2000. button.tintColor = .gray
  2001. } else {
  2002. button.tintColor = .mainColor
  2003. }
  2004. } else if forwardSession {
  2005. button.image = UIImage(systemName: "arrowshape.turn.up.right")
  2006. if countSelected == 0{
  2007. button.tintColor = .gray
  2008. } else {
  2009. button.tintColor = .mainColor
  2010. }
  2011. } else if deleteSession {
  2012. button.image = UIImage(systemName: "trash")
  2013. if countSelected == 0{
  2014. button.tintColor = .gray
  2015. } else {
  2016. button.tintColor = .red
  2017. }
  2018. }
  2019. let buttonGesture = UITapGestureRecognizer(target: self, action: #selector(sessionAction))
  2020. button.isUserInteractionEnabled = true
  2021. button.addGestureRecognizer(buttonGesture)
  2022. } else {
  2023. buttonUp = UIButton()
  2024. container.addSubview(buttonUp)
  2025. buttonUp.translatesAutoresizingMaskIntoConstraints = false
  2026. NSLayoutConstraint.activate([
  2027. buttonUp.leadingAnchor.constraint(equalTo: container.leadingAnchor, constant: 10),
  2028. buttonUp.centerYAnchor.constraint(equalTo:container.centerYAnchor),
  2029. buttonUp.widthAnchor.constraint(equalToConstant: 30),
  2030. buttonUp.heightAnchor.constraint(equalToConstant: 30),
  2031. ])
  2032. buttonUp.addTarget(self, action: #selector(upSearchText), for: .touchUpInside)
  2033. buttonDown = UIButton()
  2034. container.addSubview(buttonDown)
  2035. buttonDown.translatesAutoresizingMaskIntoConstraints = false
  2036. NSLayoutConstraint.activate([
  2037. buttonDown.leadingAnchor.constraint(equalTo: buttonUp.trailingAnchor, constant: 15),
  2038. buttonDown.centerYAnchor.constraint(equalTo:container.centerYAnchor),
  2039. buttonDown.widthAnchor.constraint(equalToConstant: 30),
  2040. buttonDown.heightAnchor.constraint(equalToConstant: 30),
  2041. ])
  2042. buttonDown.addTarget(self, action: #selector(downSearchText), for: .touchUpInside)
  2043. buttonUp.setImage(UIImage(systemName: "chevron.up"), for: .normal)
  2044. buttonUp.tintColor = .gray
  2045. buttonDown.setImage(UIImage(systemName: "chevron.down"), for: .normal)
  2046. buttonDown.tintColor = .gray
  2047. titleSearchMatches = UILabel()
  2048. container.addSubview(titleSearchMatches)
  2049. titleSearchMatches.translatesAutoresizingMaskIntoConstraints = false
  2050. NSLayoutConstraint.activate([
  2051. titleSearchMatches.centerXAnchor.constraint(equalTo: container.centerXAnchor),
  2052. titleSearchMatches.centerYAnchor.constraint(equalTo:container.centerYAnchor),
  2053. ])
  2054. titleSearchMatches.textColor = .mainColor
  2055. titleSearchMatches.font = UIFont.systemFont(ofSize: 15.0).bold
  2056. titleSearchMatches.isHidden = true
  2057. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3, execute: {
  2058. self.searchBar.becomeFirstResponder()
  2059. })
  2060. }
  2061. }
  2062. @objc func upSearchText() {
  2063. scrollToFirstSearchMessage(indexScroll: lastScrollIdxSearch + 1)
  2064. }
  2065. @objc func downSearchText() {
  2066. scrollToFirstSearchMessage(indexScroll: lastScrollIdxSearch - 1)
  2067. }
  2068. @objc func sessionAction() {
  2069. if copySession {
  2070. let dataMessages = self.dataMessages.filter({ $0["isSelected"] as! Bool == true })
  2071. let countSelected = dataMessages.count
  2072. if countSelected == 0 {
  2073. return
  2074. }
  2075. var nameTopic = "Lounge".localized()
  2076. if !dataTopic.isEmpty {
  2077. nameTopic = dataTopic["title"] as! String
  2078. }
  2079. var text = "*^\(dataGroup["f_name"]!!) (\(nameTopic))^*"
  2080. for i in 0..<countSelected {
  2081. let stringDate = (dataMessages[i]["server_date"] as! String)
  2082. let date = Date(milliseconds: Int64(stringDate)!)
  2083. let formatterDate = DateFormatter()
  2084. let formatterTime = DateFormatter()
  2085. formatterDate.dateFormat = "dd/MM/yy"
  2086. formatterDate.locale = NSLocale(localeIdentifier: "id") as Locale?
  2087. formatterTime.dateFormat = "HH:mm"
  2088. formatterTime.locale = NSLocale(localeIdentifier: "id") as Locale?
  2089. let dataProfile = getDataProfile(f_pin: dataMessages[i]["f_pin"] as! String, message_id: dataMessages[i]["message_id"] as! String)
  2090. text = text + "\n\n*[\(formatterDate.string(from: date as Date)) \(formatterTime.string(from: date as Date))] \(dataProfile["name"]!):*\n\(dataMessages[i]["message_text"] as! String)"
  2091. }
  2092. text = text + "\n\n\nchat powered by Nexilis"
  2093. DispatchQueue.main.async {
  2094. UIPasteboard.general.string = text
  2095. self.showToast(message: "Text coppied to clipboard".localized(), font: UIFont.systemFont(ofSize: 12, weight: .medium), controller: self)
  2096. }
  2097. cancelAction()
  2098. } else if forwardSession {
  2099. let dataMessages = self.dataMessages.filter({ $0["isSelected"] as! Bool == true })
  2100. let countSelected = dataMessages.count
  2101. if countSelected == 0 {
  2102. return
  2103. }
  2104. contactChatNav.modalPresentationStyle = .custom
  2105. contactChatNav.navigationBar.tintColor = .white
  2106. contactChatNav.navigationBar.barTintColor = .mainColor
  2107. contactChatNav.navigationBar.isTranslucent = false
  2108. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  2109. contactChatNav.navigationBar.titleTextAttributes = textAttributes
  2110. contactChatNav.view.backgroundColor = .mainColor
  2111. if let controller = contactChatNav.viewControllers.first as? ContactChatViewController {
  2112. controller.isChooser = { [weak self] scope, pin in
  2113. if scope == "3" {
  2114. let editorPersonalVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorPersonalVC") as! EditorPersonal
  2115. editorPersonalVC.unique_l_pin = pin
  2116. editorPersonalVC.dataMessageForward = dataMessages
  2117. self?.navigationController?.replaceAllViewController(with: editorPersonalVC, animated: true)
  2118. } else {
  2119. let editorGroupVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorGroupVC") as! EditorGroup
  2120. editorGroupVC.unique_l_pin = pin
  2121. editorGroupVC.dataMessageForward = dataMessages
  2122. self?.navigationController?.replaceAllViewController(with: editorGroupVC, animated: true)
  2123. }
  2124. }
  2125. }
  2126. self.present(contactChatNav, animated: true, completion: nil)
  2127. } else if deleteSession {
  2128. let dataMessages = self.dataMessages.filter({ $0["isSelected"] as! Bool == true })
  2129. let countSelected = dataMessages.count
  2130. if countSelected == 0 {
  2131. return
  2132. }
  2133. let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
  2134. if let action = self.actionDelete(for: "me", title: "Delete".localized() + " \(countSelected) " + "For Me".localized(), dataMessages: dataMessages) {
  2135. alertController.addAction(action)
  2136. }
  2137. let idMe = UserDefaults.standard.string(forKey: "me") as String?
  2138. let dataFilterFpin = dataMessages.filter({ $0["f_pin"] as? String != idMe})
  2139. let dataFilterLock = dataMessages.filter({ $0["lock"] as? String == "1"})
  2140. if dataFilterFpin.count == 0 && dataFilterLock.count == 0 {
  2141. if let action = self.actionDelete(for: "everyone", title: "Delete".localized() + " \(countSelected) " + "For Everyone".localized(), dataMessages: dataMessages) {
  2142. alertController.addAction(action)
  2143. }
  2144. }
  2145. alertController.addAction(UIAlertAction(title: "Cancel".localized(), style: .cancel, handler: nil))
  2146. self.present(alertController, animated: true)
  2147. }
  2148. }
  2149. private func deleteMessage(l_pin: String, message_id: String, scope: String, type: String, chat: String) {
  2150. let tmessage = CoreMessage_TMessageBank.deleteMessage(l_pin: l_pin, messageId: message_id, scope: scope, type: type, chat: chat)
  2151. Nexilis.addQueueMessage(message: tmessage)
  2152. }
  2153. private func queryMessageReply(message_id: String) -> [String: Any?] {
  2154. var dataQuery: [String: Any] = [:]
  2155. Database().database?.inTransaction({ fmdb, rollback in
  2156. if let c = Database().getRecords(fmdb: fmdb, query: "SELECT message_id, f_pin, message_text, attachment_flag, thumb_id, image_id, video_id, file_id FROM MESSAGE where message_id='\(message_id)'"), c.next() {
  2157. dataQuery["message_id"] = c.string(forColumnIndex: 0)
  2158. dataQuery["f_pin"] = c.string(forColumnIndex: 1)
  2159. dataQuery["message_text"] = c.string(forColumnIndex: 2)
  2160. dataQuery["attachment_flag"] = c.string(forColumnIndex: 3)
  2161. dataQuery["thumb_id"] = c.string(forColumnIndex: 4)
  2162. dataQuery["image_id"] = c.string(forColumnIndex: 5)
  2163. dataQuery["video_id"] = c.string(forColumnIndex: 6)
  2164. dataQuery["file_id"] = c.string(forColumnIndex: 7)
  2165. c.close()
  2166. }
  2167. })
  2168. return dataQuery
  2169. }
  2170. @objc func segmentedControlValueChanged(_ sender: segmentedControllerObject) {
  2171. switch sender.selectedSegmentIndex {
  2172. case 0:
  2173. sender.navigation.viewControllers[0].children[1].view.isHidden = true
  2174. break;
  2175. case 1:
  2176. sender.navigation.viewControllers[0].children[1].view.isHidden = false
  2177. break;
  2178. default:
  2179. break;
  2180. }
  2181. }
  2182. private func copyOption(indexPath: IndexPath) -> UIMenu {
  2183. var ratingButtonTitles = ["Text".localized(), "Image".localized()]
  2184. if (dataMessages[indexPath.row]["message_text"] as! String).isEmpty {
  2185. ratingButtonTitles = ["Image".localized()]
  2186. }
  2187. let dataMessages = self.dataMessages.filter({ $0["chat_date"] as! String == dataDates[indexPath.section]})
  2188. let copyActions = ratingButtonTitles
  2189. .enumerated()
  2190. .map { index, title in
  2191. return UIAction(
  2192. title: title,
  2193. identifier: nil,
  2194. handler: {(_) in
  2195. if (dataMessages[indexPath.row]["message_text"] as! String).isEmpty {
  2196. DispatchQueue.main.async {
  2197. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  2198. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  2199. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  2200. if let dirPath = paths.first {
  2201. let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(dataMessages[indexPath.row]["image_id"] as! String)
  2202. if FileManager.default.fileExists(atPath: imageURL.path) {
  2203. let image = UIImage(contentsOfFile: imageURL.path)
  2204. UIPasteboard.general.image = image
  2205. self.showToast(message: "Image coppied to clipboard".localized(), font: UIFont.systemFont(ofSize: 12, weight: .medium), controller: self)
  2206. }
  2207. }
  2208. }
  2209. return
  2210. }
  2211. if (index == 0) {
  2212. DispatchQueue.main.async {
  2213. UIPasteboard.general.string = dataMessages[indexPath.row]["message_text"] as? String
  2214. self.showToast(message: "Text coppied to clipboard".localized(), font: UIFont.systemFont(ofSize: 12, weight: .medium), controller: self)
  2215. }
  2216. } else {
  2217. DispatchQueue.main.async {
  2218. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  2219. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  2220. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  2221. if let dirPath = paths.first {
  2222. let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(dataMessages[indexPath.row]["image_id"] as! String)
  2223. if FileManager.default.fileExists(atPath: imageURL.path) {
  2224. let image = UIImage(contentsOfFile: imageURL.path)
  2225. UIPasteboard.general.image = image
  2226. self.showToast(message: "Image coppied to clipboard".localized(), font: UIFont.systemFont(ofSize: 12, weight: .medium), controller: self)
  2227. }
  2228. }
  2229. }
  2230. }
  2231. self.dismissKeyboard()
  2232. })
  2233. }
  2234. return UIMenu(
  2235. title: "Copy".localized(),
  2236. image: UIImage(systemName: "doc.on.doc.fill"),
  2237. children: copyActions)
  2238. }
  2239. private func actionDelete(for type: String, title: String, dataMessages: [[String: Any?]]) -> UIAlertAction? {
  2240. return UIAlertAction(title: title, style: .destructive) { [unowned self] _ in
  2241. for i in 0..<dataMessages.count {
  2242. if (type == "me") {
  2243. self.deleteMessage(l_pin: dataGroup["group_id"] as! String, message_id: dataMessages[i]["message_id"] as! String, scope: "4", type: "1", chat: dataTopic["chat_id"] as! String)
  2244. let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as? String == dataMessages[i]["message_id"] as? String})
  2245. if idx != nil {
  2246. self.dataMessages.remove(at: idx!)
  2247. if (idx == self.dataMessages.count - 1) {
  2248. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "reloadTabChats"), object: nil, userInfo: nil)
  2249. }
  2250. for i in 0..<dataDates.count {
  2251. if self.dataMessages.filter({ $0["chat_date"] as! String == dataDates[i] }).count == 0 {
  2252. dataDates.remove(at: i)
  2253. }
  2254. }
  2255. }
  2256. } else {
  2257. self.deleteMessage(l_pin: dataGroup["group_id"] as! String, message_id: dataMessages[i]["message_id"] as! String, scope: "4", type: "2", chat: dataTopic["chat_id"] as! String)
  2258. let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as! String == dataMessages[i]["message_id"] as! String})
  2259. if idx != nil {
  2260. self.dataMessages[idx!]["lock"] = "1"
  2261. self.dataMessages[idx!]["attachment_flag"] = "0"
  2262. self.dataMessages[idx!]["reff_id"] = ""
  2263. }
  2264. }
  2265. cancelAction()
  2266. }
  2267. }
  2268. }
  2269. @objc func deleteReplyView() {
  2270. if self.containerPreviewReply.isDescendant(of: self.viewTextfield) {
  2271. self.containerPreviewReply.subviews.forEach { $0.removeFromSuperview() }
  2272. self.containerPreviewReply.removeConstraints(self.containerPreviewReply.constraints)
  2273. self.containerPreviewReply.removeFromSuperview()
  2274. self.reffId = nil
  2275. UIView.animate(withDuration: 0.25, delay: 0.0, options: .curveEaseInOut, animations: {
  2276. self.constraintTopTextField.constant = self.constraintTopTextField.constant - 50
  2277. }, completion: nil)
  2278. }
  2279. }
  2280. @objc func deleteLinkPreview() {
  2281. if self.containerLink.isDescendant(of: self.viewTextfield) {
  2282. self.containerLink.subviews.forEach { $0.removeFromSuperview() }
  2283. self.containerLink.removeConstraints(self.containerLink.constraints)
  2284. self.containerLink.removeFromSuperview()
  2285. UIView.animate(withDuration: 0.25, delay: 0.0, options: .curveEaseInOut, animations: {
  2286. self.constraintTopTextField.constant = self.constraintTopTextField.constant - 80
  2287. }, completion: nil)
  2288. }
  2289. if self.reffId != nil {
  2290. self.bottomAnchorPreviewReply.isActive = false
  2291. self.bottomAnchorPreviewReply = self.containerPreviewReply.bottomAnchor.constraint(equalTo: self.textFieldSend.topAnchor)
  2292. self.bottomAnchorPreviewReply.isActive = true
  2293. }
  2294. }
  2295. }
  2296. extension EditorGroup: UICollectionViewDelegate, UICollectionViewDataSource {
  2297. public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  2298. return 76
  2299. }
  2300. public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  2301. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellSticker", for: indexPath)
  2302. if (cell.contentView.subviews.count > 0) {
  2303. cell.contentView.subviews[0].removeFromSuperview()
  2304. }
  2305. let imageSticker = UIImageView()
  2306. cell.contentView.addSubview(imageSticker)
  2307. imageSticker.translatesAutoresizingMaskIntoConstraints = false
  2308. NSLayoutConstraint.activate([
  2309. imageSticker.topAnchor.constraint(equalTo: cell.contentView.topAnchor),
  2310. imageSticker.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor),
  2311. imageSticker.leadingAnchor.constraint(equalTo: cell.contentView.leadingAnchor),
  2312. imageSticker.trailingAnchor.constraint(equalTo: cell.contentView.trailingAnchor)
  2313. ])
  2314. imageSticker.image = UIImage(named: stickers[indexPath.row], in: Bundle.resourceBundle(for: Nexilis.self), with: nil)
  2315. return cell
  2316. }
  2317. public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  2318. sendChat(message_text: "sticker/\(stickers[indexPath.row])", attachment_flag: "11", viewController: self)
  2319. constraintBottomAttachment.constant = 0.0
  2320. self.viewSticker.removeConstraints(self.viewSticker.constraints)
  2321. self.viewSticker.removeFromSuperview()
  2322. }
  2323. public func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
  2324. 1
  2325. }
  2326. public func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
  2327. return self.previewItem!
  2328. }
  2329. }
  2330. extension EditorGroup: UITableViewDelegate, UITableViewDataSource {
  2331. // public func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
  2332. // checkNewMessage(tableView: tableView)
  2333. // }
  2334. public func scrollViewDidScroll(_ scrollView: UIScrollView) {
  2335. checkNewMessage(tableView: self.tableChatView)
  2336. }
  2337. public func numberOfSections(in tableView: UITableView) -> Int {
  2338. dataDates.count
  2339. }
  2340. public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  2341. let count = dataMessages.filter({ $0["chat_date"] as! String == dataDates[section] }).count
  2342. return count
  2343. }
  2344. public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
  2345. let containerView = UIView()
  2346. containerView.backgroundColor = .clear
  2347. let dateView = UIView()
  2348. containerView.addSubview(dateView)
  2349. dateView.translatesAutoresizingMaskIntoConstraints = false
  2350. var topAnchor = dateView.topAnchor.constraint(equalTo: containerView.topAnchor)
  2351. if section == 0 {
  2352. topAnchor = dateView.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 10.0)
  2353. }
  2354. NSLayoutConstraint.activate([
  2355. topAnchor,
  2356. dateView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor),
  2357. dateView.centerXAnchor.constraint(equalTo: containerView.centerXAnchor),
  2358. dateView.heightAnchor.constraint(equalToConstant: 30),
  2359. dateView.widthAnchor.constraint(greaterThanOrEqualToConstant: 60)
  2360. ])
  2361. dateView.backgroundColor = .orangeColor
  2362. dateView.layer.cornerRadius = 15.0
  2363. dateView.clipsToBounds = true
  2364. let labelDate = UILabel()
  2365. dateView.addSubview(labelDate)
  2366. labelDate.translatesAutoresizingMaskIntoConstraints = false
  2367. NSLayoutConstraint.activate([
  2368. labelDate.centerYAnchor.constraint(equalTo: dateView.centerYAnchor),
  2369. labelDate.centerXAnchor.constraint(equalTo: dateView.centerXAnchor),
  2370. labelDate.leadingAnchor.constraint(equalTo: dateView.leadingAnchor, constant: 10),
  2371. labelDate.trailingAnchor.constraint(equalTo: dateView.trailingAnchor, constant: -10),
  2372. ])
  2373. labelDate.textAlignment = .center
  2374. labelDate.textColor = .secondaryColor
  2375. labelDate.font = UIFont.systemFont(ofSize: 12, weight: .medium)
  2376. labelDate.text = dataDates[section]
  2377. return containerView
  2378. }
  2379. public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
  2380. if section == 0 {
  2381. return 40
  2382. }
  2383. return 30
  2384. }
  2385. public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  2386. let dataMessages = self.dataMessages.filter({ $0["chat_date"] as! String == dataDates[indexPath.section] })
  2387. if copySession || forwardSession || deleteSession {
  2388. if copySession && dataMessages[indexPath.row]["f_pin"] as! String != "-999" {
  2389. return
  2390. }
  2391. if (dataMessages[indexPath.row]["attachment_flag"] as! String != "0" || dataMessages[indexPath.row]["lock"] as? String == "1") && !forwardSession && !deleteSession {
  2392. return
  2393. }
  2394. let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as! String == dataMessages[indexPath.row]["message_id"] as! String})
  2395. if idx != nil {
  2396. self.dataMessages[idx!]["isSelected"] = !(self.dataMessages[idx!]["isSelected"] as! Bool)
  2397. self.tableChatView.reloadRows(at: [indexPath], with: .none)
  2398. }
  2399. containerMultpileSelectSession.subviews.forEach({ $0.removeFromSuperview() })
  2400. addSubviewMultipleSession()
  2401. return
  2402. }
  2403. if !(dataMessages[indexPath.row]["image_id"] as! String).isEmpty || !(dataMessages[indexPath.row]["video_id"] as! String).isEmpty || !(dataMessages[indexPath.row]["file_id"] as! String).isEmpty {
  2404. var file = dataMessages[indexPath.row]["image_id"] as! String
  2405. if file.isEmpty {
  2406. file = dataMessages[indexPath.row]["video_id"] as! String
  2407. if file.isEmpty {
  2408. file = dataMessages[indexPath.row]["file_id"] as! String
  2409. }
  2410. }
  2411. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  2412. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  2413. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  2414. if let dirPath = paths.first {
  2415. let fileURL = URL(fileURLWithPath: dirPath).appendingPathComponent(file)
  2416. if !FileManager.default.fileExists(atPath: fileURL.path) {
  2417. return
  2418. }
  2419. }
  2420. }
  2421. let message = dataMessages[indexPath.row]
  2422. if let attachmentFlag = message["attachment_flag"], let attachmentFlag = attachmentFlag as? String {
  2423. if attachmentFlag == "27" {
  2424. let streamingController = QmeraCreateStreamingViewController()
  2425. streamingController.isJoin = true
  2426. if let messageText = message["message_text"],
  2427. let messageText = messageText as? String,
  2428. var json = try! JSONSerialization.jsonObject(with: messageText.data(using: String.Encoding.utf8)!, options: []) as? [String: Any] {
  2429. if json["blog"] == nil {
  2430. json["blog"] = message["blog_id"] ?? nil
  2431. }
  2432. streamingController.data = json
  2433. }
  2434. let streamingNav = UINavigationController(rootViewController: streamingController)
  2435. streamingNav.modalPresentationStyle = .custom
  2436. streamingNav.navigationBar.barTintColor = .mainColor
  2437. streamingNav.navigationBar.tintColor = .white
  2438. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  2439. streamingNav.navigationBar.titleTextAttributes = textAttributes
  2440. streamingNav.navigationBar.isTranslucent = false
  2441. navigationController?.present(streamingNav, animated: true, completion: nil)
  2442. }
  2443. }
  2444. }
  2445. public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  2446. let idMe = UserDefaults.standard.string(forKey: "me") as String?
  2447. let dataMessages = dataMessages.filter({$0["chat_date"] as! String == dataDates[indexPath.section]})
  2448. let cellMessage = tableView.dequeueReusableCell(withIdentifier: "cellEditorGroup", for: indexPath as IndexPath)
  2449. cellMessage.backgroundColor = .clear
  2450. cellMessage.selectionStyle = .none
  2451. cellMessage.contentView.subviews.forEach({ $0.removeFromSuperview() })
  2452. let profileMessage = UIImageView()
  2453. profileMessage.frame.size = CGSize(width: 35, height: 35)
  2454. cellMessage.contentView.addSubview(profileMessage)
  2455. profileMessage.translatesAutoresizingMaskIntoConstraints = false
  2456. let tapGestureRecognizer = ObjectGesture(target: self, action: #selector(profilePersonTapped(_:)))
  2457. tapGestureRecognizer.message_id = dataMessages[indexPath.row]["f_pin"] as! String
  2458. profileMessage.isUserInteractionEnabled = true
  2459. profileMessage.addGestureRecognizer(tapGestureRecognizer)
  2460. let containerMessage = UIView()
  2461. if !copySession && !forwardSession && !deleteSession && !isHistoryCC && !removed {
  2462. let interaction = UIContextMenuInteraction(delegate: self)
  2463. containerMessage.addInteraction(interaction)
  2464. containerMessage.isUserInteractionEnabled = true
  2465. }
  2466. let thumbChat = dataMessages[indexPath.row]["thumb_id"] as! String
  2467. let imageChat = dataMessages[indexPath.row]["image_id"] as! String
  2468. let videoChat = dataMessages[indexPath.row]["video_id"] as! String
  2469. let fileChat = dataMessages[indexPath.row]["file_id"] as! String
  2470. let reffChat = dataMessages[indexPath.row]["reff_id"] as! String
  2471. cellMessage.contentView.addSubview(containerMessage)
  2472. containerMessage.translatesAutoresizingMaskIntoConstraints = false
  2473. let timeMessage = UILabel()
  2474. cellMessage.contentView.addSubview(timeMessage)
  2475. timeMessage.translatesAutoresizingMaskIntoConstraints = false
  2476. if (dataMessages[indexPath.row]["read_receipts"] as? String) == "8" {
  2477. timeMessage.bottomAnchor.constraint(equalTo: cellMessage.contentView.bottomAnchor, constant: -40).isActive = true
  2478. } else {
  2479. timeMessage.bottomAnchor.constraint(equalTo: cellMessage.contentView.bottomAnchor, constant: -5).isActive = true
  2480. }
  2481. let messageText = UILabel()
  2482. containerMessage.addSubview(messageText)
  2483. messageText.translatesAutoresizingMaskIntoConstraints = false
  2484. let topMarginText = messageText.topAnchor.constraint(equalTo: containerMessage.topAnchor, constant: 32)
  2485. let dataProfile = getDataProfile(f_pin: dataMessages[indexPath.row]["f_pin"] as! String, message_id: dataMessages[indexPath.row]["message_id"] as! String)
  2486. let statusMessage = UIImageView()
  2487. if (dataMessages[indexPath.row]["attachment_flag"] as? String == "0" && dataMessages[indexPath.row]["lock"] as? String != "1") || forwardSession || deleteSession {
  2488. var showSelectedImage = true
  2489. if (!imageChat.isEmpty || !videoChat.isEmpty || !fileChat.isEmpty) && forwardSession {
  2490. var file = dataMessages[indexPath.row]["image_id"] as! String
  2491. if file.isEmpty {
  2492. file = dataMessages[indexPath.row]["video_id"] as! String
  2493. if file.isEmpty {
  2494. file = dataMessages[indexPath.row]["file_id"] as! String
  2495. }
  2496. }
  2497. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  2498. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  2499. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  2500. if let dirPath = paths.first {
  2501. let fileURL = URL(fileURLWithPath: dirPath).appendingPathComponent(file)
  2502. if !FileManager.default.fileExists(atPath: fileURL.path) {
  2503. showSelectedImage = false
  2504. }
  2505. }
  2506. }
  2507. if dataMessages[indexPath.row]["f_pin"] as! String == "-999" && !deleteSession {
  2508. showSelectedImage = false
  2509. }
  2510. if showSelectedImage {
  2511. let selectedImage = UIImageView()
  2512. cellMessage.contentView.addSubview(selectedImage)
  2513. selectedImage.translatesAutoresizingMaskIntoConstraints = false
  2514. selectedImage.frame.size = CGSize(width: 20, height: 20)
  2515. var leading = selectedImage.leadingAnchor.constraint(equalTo: cellMessage.contentView.leadingAnchor, constant: -20)
  2516. selectedImage.isHidden = true
  2517. if copySession || forwardSession || deleteSession {
  2518. leading = selectedImage.leadingAnchor.constraint(equalTo: cellMessage.contentView.leadingAnchor, constant: 15)
  2519. selectedImage.isHidden = false
  2520. }
  2521. NSLayoutConstraint.activate([
  2522. leading,
  2523. selectedImage.centerYAnchor.constraint(equalTo: cellMessage.contentView.centerYAnchor),
  2524. selectedImage.widthAnchor.constraint(equalToConstant: 20),
  2525. selectedImage.heightAnchor.constraint(equalToConstant: 20)
  2526. ])
  2527. selectedImage.circle()
  2528. selectedImage.layer.borderWidth = 2
  2529. selectedImage.layer.borderColor = UIColor.mainColor.cgColor
  2530. if dataMessages[indexPath.row]["isSelected"] as! Bool {
  2531. selectedImage.image = UIImage(systemName: "checkmark.circle.fill")
  2532. }
  2533. selectedImage.tintColor = .mainColor
  2534. }
  2535. }
  2536. if (dataMessages[indexPath.row]["f_pin"] as? String == idMe) {
  2537. profileMessage.topAnchor.constraint(equalTo: cellMessage.contentView.topAnchor, constant: 5).isActive = true
  2538. profileMessage.trailingAnchor.constraint(equalTo: cellMessage.contentView.trailingAnchor, constant: -15).isActive = true
  2539. profileMessage.heightAnchor.constraint(equalToConstant: 37).isActive = true
  2540. profileMessage.widthAnchor.constraint(equalToConstant: 35).isActive = true
  2541. profileMessage.circle()
  2542. profileMessage.clipsToBounds = true
  2543. profileMessage.backgroundColor = .lightGray
  2544. profileMessage.image = UIImage(systemName: "person")
  2545. profileMessage.tintColor = .white
  2546. profileMessage.contentMode = .scaleAspectFit
  2547. let pictureImage = dataProfile["image_id"]
  2548. if (pictureImage != "" && pictureImage != nil) {
  2549. profileMessage.setImage(name: pictureImage!)
  2550. profileMessage.contentMode = .scaleAspectFill
  2551. }
  2552. containerMessage.topAnchor.constraint(equalTo: cellMessage.contentView.topAnchor, constant: 5).isActive = true
  2553. containerMessage.leadingAnchor.constraint(greaterThanOrEqualTo: cellMessage.contentView.leadingAnchor, constant: 60).isActive = true
  2554. if (dataMessages[indexPath.row]["read_receipts"] as? String) == "8" {
  2555. containerMessage.bottomAnchor.constraint(equalTo: cellMessage.contentView.bottomAnchor, constant: -40).isActive = true
  2556. } else {
  2557. containerMessage.bottomAnchor.constraint(equalTo: cellMessage.contentView.bottomAnchor, constant: -5).isActive = true
  2558. }
  2559. containerMessage.trailingAnchor.constraint(equalTo: profileMessage.leadingAnchor, constant: -5).isActive = true
  2560. containerMessage.widthAnchor.constraint(greaterThanOrEqualToConstant: 46).isActive = true
  2561. containerMessage.layer.cornerRadius = 10.0
  2562. containerMessage.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner, .layerMinXMinYCorner]
  2563. containerMessage.clipsToBounds = true
  2564. timeMessage.trailingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: -8).isActive = true
  2565. if dataMessages[indexPath.row]["lock"] == nil || dataMessages[indexPath.row]["lock"] as! String == "0" {
  2566. cellMessage.contentView.addSubview(statusMessage)
  2567. statusMessage.translatesAutoresizingMaskIntoConstraints = false
  2568. statusMessage.bottomAnchor.constraint(equalTo: timeMessage.topAnchor).isActive = true
  2569. statusMessage.trailingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: -8).isActive = true
  2570. statusMessage.widthAnchor.constraint(equalToConstant: 15).isActive = true
  2571. statusMessage.heightAnchor.constraint(equalToConstant: 15).isActive = true
  2572. let status = getRealStatus(messageId: dataMessages[indexPath.row]["message_id"] as! String)
  2573. if (status == "1" || status == "2" ) {
  2574. statusMessage.image = UIImage(named: "checklist", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withTintColor(UIColor.lightGray)
  2575. } else if (status == "3") {
  2576. statusMessage.image = UIImage(named: "double-checklist", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withTintColor(UIColor.lightGray)
  2577. } else if (status == "8") {
  2578. statusMessage.image = UIImage(named: "message_status_ack", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withRenderingMode(.alwaysOriginal)
  2579. } else {
  2580. statusMessage.image = UIImage(named: "double-checklist", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withTintColor(UIColor.systemBlue)
  2581. }
  2582. }
  2583. let nameSender = UILabel()
  2584. containerMessage.addSubview(nameSender)
  2585. nameSender.translatesAutoresizingMaskIntoConstraints = false
  2586. nameSender.topAnchor.constraint(equalTo: containerMessage.topAnchor, constant: 15).isActive = true
  2587. nameSender.leadingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: 15).isActive = true
  2588. nameSender.trailingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: -15).isActive = true
  2589. nameSender.font = UIFont.systemFont(ofSize: 12).bold
  2590. nameSender.text = dataProfile["name"]
  2591. nameSender.textAlignment = .right
  2592. if (dataMessages[indexPath.row]["attachment_flag"] as? String == "11" && dataMessages[indexPath.row]["reff_id"]as? String == "") {
  2593. containerMessage.backgroundColor = .clear
  2594. nameSender.textColor = .mainColor
  2595. } else {
  2596. containerMessage.backgroundColor = .blueBubbleColor
  2597. nameSender.textColor = .mainColor
  2598. }
  2599. } else {
  2600. if copySession || forwardSession || deleteSession {
  2601. profileMessage.leadingAnchor.constraint(equalTo: cellMessage.contentView.leadingAnchor, constant: 50).isActive = true
  2602. } else {
  2603. profileMessage.leadingAnchor.constraint(equalTo: cellMessage.contentView.leadingAnchor, constant: 15).isActive = true
  2604. }
  2605. profileMessage.heightAnchor.constraint(equalToConstant: 37).isActive = true
  2606. profileMessage.widthAnchor.constraint(equalToConstant: 35).isActive = true
  2607. profileMessage.circle()
  2608. profileMessage.clipsToBounds = true
  2609. profileMessage.backgroundColor = .lightGray
  2610. profileMessage.image = UIImage(systemName: "person")
  2611. profileMessage.tintColor = .white
  2612. profileMessage.contentMode = .scaleAspectFit
  2613. let pictureImage = dataProfile["image_id"]
  2614. if dataMessages[indexPath.row]["f_pin"] as? String == "-999" {
  2615. if Utils.getIconDock() != nil {
  2616. let dataImage = try? Data(contentsOf: URL(string: Utils.getUrlDock()!)!) //make sure your image in this url does exist, otherwise unwrap in a if let check / try-catch
  2617. if dataImage != nil {
  2618. profileMessage.image = UIImage(data: dataImage!)
  2619. }
  2620. } else {
  2621. profileMessage.image = UIImage(named: "pb_button", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)
  2622. }
  2623. profileMessage.contentMode = .scaleAspectFill
  2624. }
  2625. else if (pictureImage != "" && pictureImage != nil) {
  2626. profileMessage.setImage(name: pictureImage!)
  2627. profileMessage.contentMode = .scaleAspectFill
  2628. }
  2629. if markerCounter != nil && dataMessages[indexPath.row]["message_id"] as? String == markerCounter {
  2630. profileMessage.topAnchor.constraint(equalTo: cellMessage.contentView.topAnchor, constant: 35).isActive = true
  2631. containerMessage.topAnchor.constraint(equalTo: cellMessage.contentView.topAnchor, constant: 35).isActive = true
  2632. let newMessagesView = UIView()
  2633. cellMessage.contentView.addSubview(newMessagesView)
  2634. newMessagesView.translatesAutoresizingMaskIntoConstraints = false
  2635. NSLayoutConstraint.activate([
  2636. newMessagesView.topAnchor.constraint(equalTo: newMessagesView.topAnchor),
  2637. newMessagesView.bottomAnchor.constraint(equalTo: containerMessage.topAnchor),
  2638. newMessagesView.centerXAnchor.constraint(equalTo: cellMessage.contentView.centerXAnchor),
  2639. newMessagesView.heightAnchor.constraint(equalToConstant: 30),
  2640. newMessagesView.widthAnchor.constraint(greaterThanOrEqualToConstant: 60)
  2641. ])
  2642. newMessagesView.backgroundColor = .greenColor
  2643. newMessagesView.layer.cornerRadius = 15.0
  2644. newMessagesView.clipsToBounds = true
  2645. let labelNewMessages = UILabel()
  2646. newMessagesView.addSubview(labelNewMessages)
  2647. labelNewMessages.translatesAutoresizingMaskIntoConstraints = false
  2648. NSLayoutConstraint.activate([
  2649. labelNewMessages.centerYAnchor.constraint(equalTo: newMessagesView.centerYAnchor),
  2650. labelNewMessages.centerXAnchor.constraint(equalTo: newMessagesView.centerXAnchor),
  2651. labelNewMessages.leadingAnchor.constraint(equalTo: newMessagesView.leadingAnchor, constant: 10),
  2652. labelNewMessages.trailingAnchor.constraint(equalTo: newMessagesView.trailingAnchor, constant: -10),
  2653. ])
  2654. labelNewMessages.textAlignment = .center
  2655. labelNewMessages.textColor = .secondaryColor
  2656. labelNewMessages.font = UIFont.systemFont(ofSize: 12, weight: .medium)
  2657. labelNewMessages.text = "Unread Messages".localized()
  2658. } else {
  2659. profileMessage.topAnchor.constraint(equalTo: cellMessage.contentView.topAnchor, constant: 5).isActive = true
  2660. containerMessage.topAnchor.constraint(equalTo: cellMessage.contentView.topAnchor, constant: 5).isActive = true
  2661. }
  2662. containerMessage.leadingAnchor.constraint(equalTo: profileMessage.trailingAnchor, constant: 5).isActive = true
  2663. if (dataMessages[indexPath.row]["read_receipts"] as? String) == "8" {
  2664. containerMessage.bottomAnchor.constraint(equalTo: cellMessage.contentView.bottomAnchor, constant: -40).isActive = true
  2665. } else {
  2666. containerMessage.bottomAnchor.constraint(equalTo: cellMessage.contentView.bottomAnchor, constant: -5).isActive = true
  2667. }
  2668. containerMessage.trailingAnchor.constraint(lessThanOrEqualTo: cellMessage.contentView.trailingAnchor, constant: -60).isActive = true
  2669. containerMessage.widthAnchor.constraint(greaterThanOrEqualToConstant: 46).isActive = true
  2670. if dataMessages[indexPath.row]["attachment_flag"] as? String == "11" && dataMessages[indexPath.row]["reff_id"]as? String == "" && (dataMessages[indexPath.row]["lock"] == nil || dataMessages[indexPath.row]["lock"] as! String != "1") {
  2671. containerMessage.backgroundColor = .clear
  2672. } else {
  2673. containerMessage.backgroundColor = .grayColor
  2674. }
  2675. containerMessage.layer.cornerRadius = 10.0
  2676. containerMessage.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMinYCorner, .layerMaxXMaxYCorner]
  2677. containerMessage.clipsToBounds = true
  2678. timeMessage.leadingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: 8).isActive = true
  2679. let nameSender = UILabel()
  2680. containerMessage.addSubview(nameSender)
  2681. nameSender.translatesAutoresizingMaskIntoConstraints = false
  2682. nameSender.topAnchor.constraint(equalTo: containerMessage.topAnchor, constant: 15).isActive = true
  2683. nameSender.leadingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: 15).isActive = true
  2684. nameSender.trailingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: -15).isActive = true
  2685. nameSender.font = UIFont.systemFont(ofSize: 12).bold
  2686. if dataMessages[indexPath.row]["f_pin"] as? String == "-999" {
  2687. nameSender.text = "Bot"
  2688. }
  2689. else {
  2690. nameSender.text = dataProfile["name"]
  2691. }
  2692. nameSender.textAlignment = .left
  2693. nameSender.textColor = .mainColor
  2694. }
  2695. if dataMessages[indexPath.row]["is_stared"] as? String == "1" && (dataMessages[indexPath.row]["lock"] == nil || dataMessages[indexPath.row]["lock"] as! String == "0") {
  2696. let imageStared = UIImageView()
  2697. cellMessage.contentView.addSubview(imageStared)
  2698. imageStared.translatesAutoresizingMaskIntoConstraints = false
  2699. if (dataMessages[indexPath.row]["f_pin"] as? String == idMe) {
  2700. imageStared.bottomAnchor.constraint(equalTo: statusMessage.topAnchor).isActive = true
  2701. imageStared.trailingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: -8).isActive = true
  2702. } else {
  2703. imageStared.bottomAnchor.constraint(equalTo: timeMessage.topAnchor).isActive = true
  2704. imageStared.leadingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: 8).isActive = true
  2705. }
  2706. imageStared.widthAnchor.constraint(equalToConstant: 15).isActive = true
  2707. imageStared.heightAnchor.constraint(equalToConstant: 15).isActive = true
  2708. imageStared.image = UIImage(systemName: "star.fill")
  2709. imageStared.backgroundColor = .clear
  2710. imageStared.tintColor = .systemYellow
  2711. }
  2712. if dataMessages[indexPath.row]["read_receipts"] as? String == "8" {
  2713. let imageAckView = UIImageView()
  2714. var imageAck = UIImage(named: "ack_icon_gray", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withRenderingMode(.alwaysOriginal)
  2715. cellMessage.contentView.addSubview(imageAckView)
  2716. imageAckView.translatesAutoresizingMaskIntoConstraints = false
  2717. imageAckView.widthAnchor.constraint(equalToConstant: 30).isActive = true
  2718. imageAckView.heightAnchor.constraint(equalToConstant: 30).isActive = true
  2719. if (dataMessages[indexPath.row]["f_pin"] as? String == idMe) {
  2720. let status = getRealStatus(messageId: dataMessages[indexPath.row]["message_id"] as! String)
  2721. if status == "8" {
  2722. imageAck = UIImage(named: "ack_icon", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withRenderingMode(.alwaysOriginal)
  2723. }
  2724. imageAckView.topAnchor.constraint(equalTo: containerMessage.bottomAnchor, constant: 5).isActive = true
  2725. imageAckView.trailingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: 30).isActive = true
  2726. } else {
  2727. let status = dataMessages[indexPath.row]["status"] as? String
  2728. if status == "8" {
  2729. imageAck = UIImage(named: "ack_icon", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withRenderingMode(.alwaysOriginal)
  2730. }
  2731. imageAckView.topAnchor.constraint(equalTo: containerMessage.bottomAnchor, constant: 5).isActive = true
  2732. imageAckView.leadingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: -30).isActive = true
  2733. let tap = ObjectGesture(target: self, action: #selector(tapAck(_:)))
  2734. tap.indexPath = indexPath
  2735. imageAckView.addGestureRecognizer(tap)
  2736. imageAckView.isUserInteractionEnabled = true
  2737. }
  2738. imageAckView.image = imageAck
  2739. }
  2740. messageText.numberOfLines = 0
  2741. messageText.lineBreakMode = .byWordWrapping
  2742. containerMessage.addSubview(messageText)
  2743. topMarginText.isActive = true
  2744. if dataMessages[indexPath.row]["attachment_flag"] as! String == "27" || dataMessages[indexPath.row]["attachment_flag"] as! String == "26" {
  2745. messageText.leadingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: 85).isActive = true
  2746. let imageLS = UIImageView()
  2747. containerMessage.addSubview(imageLS)
  2748. imageLS.translatesAutoresizingMaskIntoConstraints = false
  2749. NSLayoutConstraint.activate([
  2750. imageLS.leadingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: 15.0),
  2751. imageLS.trailingAnchor.constraint(equalTo: messageText.leadingAnchor, constant: -10.0),
  2752. imageLS.centerYAnchor.constraint(equalTo: containerMessage.centerYAnchor),
  2753. imageLS.heightAnchor.constraint(equalToConstant: 60.0)
  2754. ])
  2755. if dataMessages[indexPath.row]["attachment_flag"] as! String == "26" {
  2756. imageLS.image = UIImage(named: "pb_seminar_wpr", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)
  2757. } else if dataMessages[indexPath.row]["attachment_flag"] as! String == "27" {
  2758. imageLS.image = UIImage(named: "pb_live_tv", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)
  2759. }
  2760. } else {
  2761. messageText.leadingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: 15).isActive = true
  2762. }
  2763. messageText.bottomAnchor.constraint(equalTo: containerMessage.bottomAnchor, constant: -15).isActive = true
  2764. messageText.trailingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: -15).isActive = true
  2765. if (dataMessages[indexPath.row]["f_pin"] as? String == idMe) {
  2766. messageText.textColor = .black
  2767. } else {
  2768. messageText.textColor = .black
  2769. }
  2770. var textChat = (dataMessages[indexPath.row]["message_text"])! as? String
  2771. if (dataMessages[indexPath.row]["lock"] != nil && (dataMessages[indexPath.row]["lock"])! as? String == "1") {
  2772. if (dataMessages[indexPath.row]["f_pin"] as? String == idMe) {
  2773. textChat = "🚫 _"+"You were deleted this message".localized()+"_"
  2774. } else {
  2775. textChat = "🚫 _"+"This message was deleted".localized()+"_"
  2776. }
  2777. }
  2778. let imageSticker = UIImageView()
  2779. if let attachmentFlag = dataMessages[indexPath.row]["attachment_flag"], let attachmentFlag = attachmentFlag as? String {
  2780. if attachmentFlag == "27" || attachmentFlag == "26", let data = textChat { // live streaming
  2781. if let json = try! JSONSerialization.jsonObject(with: data.data(using: String.Encoding.utf8)!, options: []) as? [String: Any] {
  2782. Database().database?.inTransaction({ fmdb, rollback in
  2783. let title = json["title"] as! String
  2784. let description = json["description"] as! String
  2785. let start = json["time"] as! Int64
  2786. let by = json["by"] as! String
  2787. let textLS = "Live Streaming".localized()
  2788. var type = "*\(textLS)*"
  2789. if attachmentFlag == "26" {
  2790. let textSeminar = "Seminar".localized()
  2791. type = "*\(textSeminar)*"
  2792. }
  2793. if let c = Database().getRecords(fmdb: fmdb, query: "select first_name || ' ' || last_name from BUDDY where f_pin = '\(by)'"), c.next() {
  2794. let name = c.string(forColumnIndex: 0)!
  2795. messageText.attributedText = "\(type) \nTitle: \(title) \nDescription: \(description) \nStart: \(Date(milliseconds: start).format(dateFormat: "dd/MM/yyyy HH:mm")) \nBroadcaster: \(name)".richText()
  2796. c.close()
  2797. } else {
  2798. messageText.attributedText = ("\(type) \nTitle: \(title) \nDescription: \(description) \nStart: \(Date(milliseconds: start).format(dateFormat: "dd/MM/yyyy HH:mm")) \nBroadcaster: " + "Unknown".localized()).richText()
  2799. }
  2800. })
  2801. }
  2802. }
  2803. else if attachmentFlag == "11" && (dataMessages[indexPath.row]["lock"] == nil || dataMessages[indexPath.row]["lock"] as! String != "1") {
  2804. messageText.text = ""
  2805. topMarginText.constant = topMarginText.constant + 100
  2806. containerMessage.addSubview(imageSticker)
  2807. imageSticker.translatesAutoresizingMaskIntoConstraints = false
  2808. if (reffChat == "") {
  2809. imageSticker.topAnchor.constraint(equalTo: containerMessage.topAnchor, constant: 32).isActive = true
  2810. imageSticker.widthAnchor.constraint(equalToConstant: 80).isActive = true
  2811. } else {
  2812. imageSticker.widthAnchor.constraint(greaterThanOrEqualToConstant: 80).isActive = true
  2813. }
  2814. imageSticker.leadingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: 15).isActive = true
  2815. imageSticker.bottomAnchor.constraint(equalTo: messageText.topAnchor, constant: -5).isActive = true
  2816. imageSticker.trailingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: -15).isActive = true
  2817. imageSticker.image = UIImage(named: (textChat?.components(separatedBy: "/")[1])!, in: Bundle.resourceBundle(for: Nexilis.self), with: nil)
  2818. imageSticker.contentMode = .scaleAspectFit
  2819. }
  2820. else {
  2821. messageText.attributedText = textChat!.richText()
  2822. }
  2823. } else {
  2824. messageText.attributedText = textChat!.richText()
  2825. }
  2826. messageText.isUserInteractionEnabled = true
  2827. if !textChat!.isEmpty {
  2828. let listText = textChat!.split(separator: " ")
  2829. for i in 0...listText.count - 1 {
  2830. if listText[i].lowercased().checkStartWithLink() {
  2831. if ((listText[i].lowercased().starts(with: "www.") && listText[i].lowercased().split(separator: ".").count >= 3) || (!listText[i].lowercased().starts(with: "www.") && listText[i].lowercased().split(separator: ".").count >= 2)) && listText[i].lowercased().split(separator: ".").last!.count >= 2 {
  2832. let objectGesture = ObjectGesture(target: self, action: #selector(tapMessageText(_:)))
  2833. objectGesture.message_id = "\(listText[i])"
  2834. messageText.addGestureRecognizer(objectGesture)
  2835. }
  2836. }
  2837. }
  2838. }
  2839. if isSearching && textSearch.count > 1 {
  2840. messageText.attributedText = textChat!.richText(isSearching: true, textSearch: textSearch)
  2841. if textChat!.lowercased().contains(textSearch) {
  2842. countMatchesSearch += 1
  2843. }
  2844. }
  2845. let stringDate = (dataMessages[indexPath.row]["server_date"] as! String)
  2846. let date = Date(milliseconds: Int64(stringDate)!)
  2847. let formatter = DateFormatter()
  2848. formatter.dateFormat = "HH:mm"
  2849. formatter.locale = NSLocale(localeIdentifier: "id") as Locale?
  2850. timeMessage.text = formatter.string(from: date as Date)
  2851. timeMessage.font = UIFont.systemFont(ofSize: 10, weight: .medium)
  2852. timeMessage.textColor = .lightGray
  2853. let imageThumb = UIImageView()
  2854. let containerViewFile = UIView()
  2855. if (thumbChat != "" && (dataMessages[indexPath.row]["lock"] == nil || dataMessages[indexPath.row]["lock"] as! String != "1")) {
  2856. topMarginText.constant = topMarginText.constant + 205
  2857. containerMessage.addSubview(imageThumb)
  2858. imageThumb.translatesAutoresizingMaskIntoConstraints = false
  2859. let data = queryMessageReply(message_id: reffChat)
  2860. if (data.count == 0) {
  2861. imageThumb.topAnchor.constraint(equalTo: containerMessage.topAnchor, constant: 32).isActive = true
  2862. }
  2863. imageThumb.leadingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: 15).isActive = true
  2864. imageThumb.bottomAnchor.constraint(equalTo: messageText.topAnchor, constant: -5).isActive = true
  2865. imageThumb.trailingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: -15).isActive = true
  2866. imageThumb.widthAnchor.constraint(equalToConstant: self.view.frame.size.width * 0.6).isActive = true
  2867. imageThumb.layer.cornerRadius = 5.0
  2868. imageThumb.clipsToBounds = true
  2869. imageThumb.contentMode = .scaleAspectFill
  2870. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  2871. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  2872. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  2873. if let dirPath = paths.first {
  2874. let thumbURL = URL(fileURLWithPath: dirPath).appendingPathComponent(thumbChat)
  2875. let image = UIImage(contentsOfFile: thumbURL.path)
  2876. imageThumb.image = image
  2877. let videoURL = URL(fileURLWithPath: dirPath).appendingPathComponent(videoChat)
  2878. let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(imageChat)
  2879. if !FileManager.default.fileExists(atPath: imageURL.path) || !FileManager.default.fileExists(atPath: videoURL.path){
  2880. let blurEffect = UIBlurEffect(style: UIBlurEffect.Style.light)
  2881. let blurEffectView = UIVisualEffectView(effect: blurEffect)
  2882. blurEffectView.frame = CGRect(x: 0, y: 0, width: imageThumb.frame.size.width, height: imageThumb.frame.size.height)
  2883. blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
  2884. imageThumb.addSubview(blurEffectView)
  2885. if !imageChat.isEmpty {
  2886. let imageDownload = UIImageView(image: UIImage(systemName: "arrow.down.circle.fill", withConfiguration: UIImage.SymbolConfiguration(pointSize: 50, weight: .bold, scale: .default)))
  2887. imageThumb.addSubview(blurEffectView)
  2888. imageThumb.addSubview(imageDownload)
  2889. imageDownload.tintColor = .black.withAlphaComponent(0.3)
  2890. imageDownload.translatesAutoresizingMaskIntoConstraints = false
  2891. imageDownload.centerXAnchor.constraint(equalTo: imageThumb.centerXAnchor).isActive = true
  2892. imageDownload.centerYAnchor.constraint(equalTo: imageThumb.centerYAnchor).isActive = true
  2893. }
  2894. }
  2895. }
  2896. if (videoChat != "") {
  2897. let imagePlay = UIImageView(image: UIImage(systemName: "play.fill", withConfiguration: UIImage.SymbolConfiguration(pointSize: 20, weight: .bold, scale: .default))?.imageWithInsets(insets: UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10))?.withTintColor(.white))
  2898. imagePlay.circle()
  2899. imageThumb.addSubview(imagePlay)
  2900. imagePlay.backgroundColor = .black.withAlphaComponent(0.3)
  2901. imagePlay.translatesAutoresizingMaskIntoConstraints = false
  2902. imagePlay.centerXAnchor.constraint(equalTo: imageThumb.centerXAnchor).isActive = true
  2903. imagePlay.centerYAnchor.constraint(equalTo: imageThumb.centerYAnchor).isActive = true
  2904. }
  2905. if (dataMessages[indexPath.row]["progress"] as! Double != 100.0 && dataMessages[indexPath.row]["f_pin"] as? String == idMe) {
  2906. let container = UIView()
  2907. imageThumb.addSubview(container)
  2908. container.translatesAutoresizingMaskIntoConstraints = false
  2909. container.bottomAnchor.constraint(equalTo: imageThumb.bottomAnchor, constant: -10).isActive = true
  2910. container.leadingAnchor.constraint(equalTo: imageThumb.leadingAnchor, constant: 10).isActive = true
  2911. container.widthAnchor.constraint(equalToConstant: 30).isActive = true
  2912. container.heightAnchor.constraint(equalToConstant: 30).isActive = true
  2913. container.backgroundColor = .white.withAlphaComponent(0.1)
  2914. let circlePath = UIBezierPath(arcCenter: CGPoint(x: 10, y: 20), radius: 15, startAngle: -(.pi / 2), endAngle: .pi * 2, clockwise: true)
  2915. let trackShape = CAShapeLayer()
  2916. trackShape.path = circlePath.cgPath
  2917. trackShape.fillColor = UIColor.black.withAlphaComponent(0.3).cgColor
  2918. trackShape.lineWidth = 3
  2919. trackShape.strokeColor = UIColor.blueBubbleColor.withAlphaComponent(0.3).cgColor
  2920. container.backgroundColor = .clear
  2921. container.layer.addSublayer(trackShape)
  2922. let shapeLoading = CAShapeLayer()
  2923. shapeLoading.path = circlePath.cgPath
  2924. shapeLoading.fillColor = UIColor.clear.cgColor
  2925. shapeLoading.lineWidth = 3
  2926. shapeLoading.strokeEnd = 0
  2927. shapeLoading.strokeColor = UIColor.blueBubbleColor.cgColor
  2928. container.layer.addSublayer(shapeLoading)
  2929. let imageupload = UIImageView(image: UIImage(systemName: "arrow.up", withConfiguration: UIImage.SymbolConfiguration(pointSize: 10, weight: .bold, scale: .default)))
  2930. imageupload.tintColor = .white
  2931. container.addSubview(imageupload)
  2932. imageupload.translatesAutoresizingMaskIntoConstraints = false
  2933. imageupload.bottomAnchor.constraint(equalTo: imageThumb.bottomAnchor, constant: -10).isActive = true
  2934. imageupload.leadingAnchor.constraint(equalTo: imageThumb.leadingAnchor, constant: 10).isActive = true
  2935. imageupload.widthAnchor.constraint(equalToConstant: 20).isActive = true
  2936. imageupload.heightAnchor.constraint(equalToConstant: 20).isActive = true
  2937. }
  2938. if !copySession && !forwardSession && !deleteSession {
  2939. let objectTap = ObjectGesture(target: self, action: #selector(contentMessageTapped(_:)))
  2940. imageThumb.isUserInteractionEnabled = true
  2941. imageThumb.addGestureRecognizer(objectTap)
  2942. objectTap.image_id = imageChat
  2943. objectTap.video_id = videoChat
  2944. objectTap.imageView = imageThumb
  2945. objectTap.indexPath = indexPath
  2946. }
  2947. }
  2948. if (fileChat != "" && (dataMessages[indexPath.row]["lock"] == nil || dataMessages[indexPath.row]["lock"] as! String != "1")) {
  2949. topMarginText.constant = topMarginText.constant + 55
  2950. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  2951. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  2952. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  2953. let arrExtFile = (textChat?.components(separatedBy: "|")[0])?.split(separator: ".")
  2954. let finalExtFile = arrExtFile![arrExtFile!.count - 1]
  2955. if let dirPath = paths.first {
  2956. let fileURL = URL(fileURLWithPath: dirPath).appendingPathComponent(fileChat)
  2957. if let dataFile = try? Data(contentsOf: fileURL) {
  2958. var sizeOfFile = Int(dataFile.count / 1000000)
  2959. if (sizeOfFile < 1) {
  2960. sizeOfFile = Int(dataFile.count / 1000)
  2961. if (finalExtFile.count > 4) {
  2962. messageText.text = "\(sizeOfFile) kB \u{2022} TXT"
  2963. }else {
  2964. messageText.text = "\(sizeOfFile) kB \u{2022} \(finalExtFile.uppercased())"
  2965. }
  2966. } else {
  2967. if (finalExtFile.count > 4) {
  2968. messageText.text = "\(sizeOfFile) MB \u{2022} TXT"
  2969. }else {
  2970. messageText.text = "\(sizeOfFile) MB \u{2022} \(finalExtFile.uppercased())"
  2971. }
  2972. }
  2973. } else {
  2974. messageText.text = ""
  2975. }
  2976. }
  2977. containerMessage.addSubview(containerViewFile)
  2978. containerViewFile.translatesAutoresizingMaskIntoConstraints = false
  2979. let data = queryMessageReply(message_id: reffChat)
  2980. if (data.count == 0) {
  2981. containerViewFile.topAnchor.constraint(equalTo: containerMessage.topAnchor, constant: 32).isActive = true
  2982. }
  2983. containerViewFile.leadingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: 15).isActive = true
  2984. containerViewFile.bottomAnchor.constraint(equalTo:messageText.topAnchor, constant: -5).isActive = true
  2985. containerViewFile.trailingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: -15).isActive = true
  2986. containerViewFile.heightAnchor.constraint(equalToConstant: 50).isActive = true
  2987. containerViewFile.backgroundColor = .black.withAlphaComponent(0.2)
  2988. containerViewFile.layer.cornerRadius = 5.0
  2989. containerViewFile.clipsToBounds = true
  2990. let imageFile = UIImageView(image: UIImage(systemName: "doc.fill", withConfiguration: UIImage.SymbolConfiguration(pointSize: 30, weight: .bold, scale: .default)))
  2991. containerViewFile.addSubview(imageFile)
  2992. let nameFile = UILabel()
  2993. containerViewFile.addSubview(nameFile)
  2994. imageFile.translatesAutoresizingMaskIntoConstraints = false
  2995. imageFile.leadingAnchor.constraint(equalTo: containerViewFile.leadingAnchor, constant: 5).isActive = true
  2996. imageFile.trailingAnchor.constraint(equalTo: nameFile.leadingAnchor, constant: -5).isActive = true
  2997. imageFile.centerYAnchor.constraint(equalTo: containerViewFile.centerYAnchor).isActive = true
  2998. imageFile.widthAnchor.constraint(equalToConstant: 30).isActive = true
  2999. imageFile.heightAnchor.constraint(equalToConstant: 30).isActive = true
  3000. imageFile.tintColor = .docColor
  3001. nameFile.translatesAutoresizingMaskIntoConstraints = false
  3002. nameFile.centerYAnchor.constraint(equalTo: containerViewFile.centerYAnchor).isActive = true
  3003. nameFile.widthAnchor.constraint(lessThanOrEqualToConstant: 200).isActive = true
  3004. nameFile.font = UIFont.systemFont(ofSize: 12, weight: .medium)
  3005. nameFile.textColor = .white
  3006. nameFile.text = textChat?.components(separatedBy: "|")[0]
  3007. if (dataMessages[indexPath.row]["progress"] as! Double != 100.0) {
  3008. let containerLoading = UIView()
  3009. containerViewFile.addSubview(containerLoading)
  3010. containerLoading.translatesAutoresizingMaskIntoConstraints = false
  3011. containerLoading.centerYAnchor.constraint(equalTo: containerViewFile.centerYAnchor).isActive = true
  3012. containerLoading.leadingAnchor.constraint(equalTo: nameFile.trailingAnchor, constant: 5).isActive = true
  3013. containerLoading.trailingAnchor.constraint(equalTo: containerViewFile.trailingAnchor, constant: -5).isActive = true
  3014. containerLoading.widthAnchor.constraint(equalToConstant: 30).isActive = true
  3015. containerLoading.heightAnchor.constraint(equalToConstant: 30).isActive = true
  3016. let circlePath = UIBezierPath(arcCenter: CGPoint(x: 15, y: 15), radius: 10, startAngle: -(.pi / 2), endAngle: .pi * 2, clockwise: true)
  3017. let trackShape = CAShapeLayer()
  3018. trackShape.path = circlePath.cgPath
  3019. trackShape.fillColor = UIColor.clear.cgColor
  3020. trackShape.lineWidth = 5
  3021. trackShape.strokeColor = UIColor.blueBubbleColor.withAlphaComponent(0.3).cgColor
  3022. containerLoading.layer.addSublayer(trackShape)
  3023. let shapeLoading = CAShapeLayer()
  3024. shapeLoading.path = circlePath.cgPath
  3025. shapeLoading.fillColor = UIColor.clear.cgColor
  3026. shapeLoading.lineWidth = 3
  3027. shapeLoading.strokeEnd = 0
  3028. shapeLoading.strokeColor = UIColor.secondaryColor.cgColor
  3029. containerLoading.layer.addSublayer(shapeLoading)
  3030. var imageupload = UIImageView(image: UIImage(systemName: "arrow.up", withConfiguration: UIImage.SymbolConfiguration(pointSize: 10, weight: .bold, scale: .default)))
  3031. if dataMessages[indexPath.row]["f_pin"] as? String != idMe {
  3032. imageupload = UIImageView(image: UIImage(systemName: "arrow.down", withConfiguration: UIImage.SymbolConfiguration(pointSize: 10, weight: .bold, scale: .default)))
  3033. shapeLoading.strokeColor = UIColor.blueBubbleColor.cgColor
  3034. }
  3035. imageupload.tintColor = .white
  3036. containerLoading.addSubview(imageupload)
  3037. imageupload.translatesAutoresizingMaskIntoConstraints = false
  3038. imageupload.centerYAnchor.constraint(equalTo: containerLoading.centerYAnchor).isActive = true
  3039. imageupload.centerXAnchor.constraint(equalTo: containerLoading.centerXAnchor).isActive = true
  3040. } else {
  3041. nameFile.trailingAnchor.constraint(equalTo: containerViewFile.trailingAnchor, constant: -5).isActive = true
  3042. }
  3043. if !copySession && !forwardSession && !deleteSession {
  3044. let objectTap = ObjectGesture(target: self, action: #selector(contentMessageTapped(_:)))
  3045. containerViewFile.addGestureRecognizer(objectTap)
  3046. objectTap.containerFile = containerViewFile
  3047. objectTap.labelFile = nameFile
  3048. objectTap.file_id = fileChat
  3049. objectTap.indexPath = indexPath
  3050. }
  3051. }
  3052. if (reffChat != "") {
  3053. let data = queryMessageReply(message_id: reffChat)
  3054. if data.count != 0 {
  3055. topMarginText.constant = topMarginText.constant + 55
  3056. let containerReply = UIView()
  3057. containerMessage.addSubview(containerReply)
  3058. containerReply.translatesAutoresizingMaskIntoConstraints = false
  3059. containerReply.leadingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: 15).isActive = true
  3060. containerReply.topAnchor.constraint(equalTo: containerMessage.topAnchor, constant: 32).isActive = true
  3061. if thumbChat != "" && (dataMessages[indexPath.row]["lock"] == nil || dataMessages[indexPath.row]["lock"] as! String != "1") {
  3062. containerReply.bottomAnchor.constraint(equalTo: imageThumb.topAnchor, constant: -5).isActive = true
  3063. } else if fileChat != "" && (dataMessages[indexPath.row]["lock"] == nil || dataMessages[indexPath.row]["lock"] as! String != "1") {
  3064. containerReply.bottomAnchor.constraint(equalTo: containerViewFile.topAnchor, constant: -5).isActive = true
  3065. } else if dataMessages[indexPath.row]["attachment_flag"] as? String == "11" && (dataMessages[indexPath.row]["lock"] == nil || dataMessages[indexPath.row]["lock"] as! String != "1") {
  3066. containerReply.bottomAnchor.constraint(equalTo: imageSticker.topAnchor, constant: -5).isActive = true
  3067. } else {
  3068. containerReply.bottomAnchor.constraint(equalTo: messageText.topAnchor, constant: -5).isActive = true
  3069. }
  3070. containerReply.trailingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: -15).isActive = true
  3071. containerReply.heightAnchor.constraint(equalToConstant: 50).isActive = true
  3072. containerReply.backgroundColor = .black.withAlphaComponent(0.2)
  3073. containerReply.layer.cornerRadius = 5
  3074. containerReply.clipsToBounds = true
  3075. let leftReply = UIView()
  3076. containerReply.addSubview(leftReply)
  3077. leftReply.translatesAutoresizingMaskIntoConstraints = false
  3078. leftReply.leadingAnchor.constraint(equalTo: containerReply.leadingAnchor).isActive = true
  3079. leftReply.topAnchor.constraint(equalTo: containerReply.topAnchor).isActive = true
  3080. leftReply.bottomAnchor.constraint(equalTo: containerReply.bottomAnchor).isActive = true
  3081. leftReply.widthAnchor.constraint(equalToConstant: 3).isActive = true
  3082. leftReply.layer.cornerRadius = 5
  3083. leftReply.clipsToBounds = true
  3084. leftReply.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMinXMinYCorner]
  3085. let titleReply = UILabel()
  3086. containerReply.addSubview(titleReply)
  3087. titleReply.translatesAutoresizingMaskIntoConstraints = false
  3088. titleReply.leadingAnchor.constraint(equalTo: leftReply.leadingAnchor, constant: 10).isActive = true
  3089. titleReply.topAnchor.constraint(equalTo: containerReply.topAnchor, constant: 10).isActive = true
  3090. titleReply.trailingAnchor.constraint(lessThanOrEqualTo: containerReply.trailingAnchor, constant: -20).isActive = true
  3091. titleReply.font = UIFont.systemFont(ofSize: 12).bold
  3092. if (data["f_pin"] as? String == idMe) {
  3093. titleReply.text = "You".localized()
  3094. if dataMessages[indexPath.row]["f_pin"] as? String == idMe {
  3095. titleReply.textColor = .white
  3096. leftReply.backgroundColor = .white
  3097. } else {
  3098. titleReply.textColor = .mainColor
  3099. leftReply.backgroundColor = .mainColor
  3100. }
  3101. } else {
  3102. if data["f_pin"] as? String != "-999" {
  3103. let dataProfile = getDataProfile(f_pin: data["f_pin"] as! String, message_id: data["message_id"] as! String)
  3104. titleReply.text = dataProfile["name"]
  3105. } else {
  3106. titleReply.text = "Bot"
  3107. }
  3108. if dataMessages[indexPath.row]["f_pin"] as? String == idMe {
  3109. titleReply.textColor = .white
  3110. leftReply.backgroundColor = .white
  3111. } else {
  3112. titleReply.textColor = .mainColor
  3113. leftReply.backgroundColor = .mainColor
  3114. }
  3115. }
  3116. let contentReply = UILabel()
  3117. containerReply.addSubview(contentReply)
  3118. contentReply.translatesAutoresizingMaskIntoConstraints = false
  3119. contentReply.leadingAnchor.constraint(equalTo: leftReply.leadingAnchor, constant: 10).isActive = true
  3120. contentReply.bottomAnchor.constraint(equalTo: containerReply.bottomAnchor, constant: -10).isActive = true
  3121. contentReply.font = UIFont.systemFont(ofSize: 10)
  3122. let message_text = data["message_text"] as! String
  3123. let attachment_flag = data["attachment_flag"] as! String
  3124. let thumb_chat = data["thumb_id"] as! String
  3125. let image_chat = data["image_id"] as! String
  3126. let video_chat = data["video_id"] as! String
  3127. let file_chat = data["file_id"] as! String
  3128. if (attachment_flag == "0" && thumb_chat == "") {
  3129. contentReply.trailingAnchor.constraint(equalTo: containerReply.trailingAnchor, constant: -20).isActive = true
  3130. contentReply.attributedText = message_text.richText()
  3131. } else if (attachment_flag == "1" || image_chat != "") {
  3132. if (message_text == "") {
  3133. contentReply.text = "📷 Photo".localized()
  3134. } else {
  3135. contentReply.attributedText = message_text.richText()
  3136. }
  3137. } else if (attachment_flag == "2" || video_chat != "") {
  3138. if (message_text == "") {
  3139. contentReply.text = "📹 Video".localized()
  3140. } else {
  3141. contentReply.attributedText = message_text.richText()
  3142. }
  3143. } else if (attachment_flag == "6" || file_chat != ""){
  3144. contentReply.trailingAnchor.constraint(equalTo: containerReply.trailingAnchor, constant: -20).isActive = true
  3145. contentReply.text = "📄 \(message_text.components(separatedBy: "|")[0])"
  3146. } else if (attachment_flag == "11") {
  3147. contentReply.text = "❤️ Sticker"
  3148. } else if attachment_flag == "27" {
  3149. contentReply.trailingAnchor.constraint(equalTo: containerReply.trailingAnchor, constant: -20).isActive = true
  3150. contentReply.text = "📄 " + "Live Streaming".localized()
  3151. } else if attachment_flag == "26" {
  3152. contentReply.trailingAnchor.constraint(equalTo: containerReply.trailingAnchor, constant: -20).isActive = true
  3153. contentReply.text = "📄 " + "Seminar".localized()
  3154. }
  3155. contentReply.textColor = .white.withAlphaComponent(0.8)
  3156. if (attachment_flag == "1" || attachment_flag == "2" || image_chat != "" || video_chat != "") {
  3157. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  3158. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  3159. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  3160. if let dirPath = paths.first {
  3161. let thumbURL = URL(fileURLWithPath: dirPath).appendingPathComponent(thumb_chat)
  3162. let image = UIImage(contentsOfFile: thumbURL.path)
  3163. let imageThumb = UIImageView(image: image)
  3164. containerReply.addSubview(imageThumb)
  3165. imageThumb.layer.cornerRadius = 2.0
  3166. imageThumb.clipsToBounds = true
  3167. imageThumb.contentMode = .scaleAspectFill
  3168. imageThumb.translatesAutoresizingMaskIntoConstraints = false
  3169. imageThumb.trailingAnchor.constraint(equalTo: containerReply.trailingAnchor, constant: -10).isActive = true
  3170. imageThumb.centerYAnchor.constraint(equalTo: containerReply.centerYAnchor).isActive = true
  3171. imageThumb.widthAnchor.constraint(equalToConstant: 30).isActive = true
  3172. imageThumb.heightAnchor.constraint(equalToConstant: 30).isActive = true
  3173. if (attachment_flag == "2") {
  3174. let imagePlay = UIImageView(image: UIImage(systemName: "play.circle.fill"))
  3175. imageThumb.addSubview(imagePlay)
  3176. imagePlay.clipsToBounds = true
  3177. imagePlay.translatesAutoresizingMaskIntoConstraints = false
  3178. imagePlay.centerYAnchor.constraint(equalTo: imageThumb.centerYAnchor).isActive = true
  3179. imagePlay.centerXAnchor.constraint(equalTo: imageThumb.centerXAnchor).isActive = true
  3180. imagePlay.widthAnchor.constraint(equalToConstant: 10).isActive = true
  3181. imagePlay.heightAnchor.constraint(equalToConstant: 10).isActive = true
  3182. imagePlay.tintColor = .white
  3183. }
  3184. titleReply.trailingAnchor.constraint(equalTo: imageThumb.leadingAnchor, constant: -20).isActive = true
  3185. contentReply.trailingAnchor.constraint(equalTo: imageThumb.leadingAnchor, constant: -20).isActive = true
  3186. }
  3187. }
  3188. if (attachment_flag == "11") {
  3189. let imageSticker = UIImageView(image: UIImage(named: (message_text.components(separatedBy: "/")[1]), in: Bundle.resourceBundle(for: Nexilis.self), with: nil))
  3190. containerReply.addSubview(imageSticker)
  3191. imageSticker.layer.cornerRadius = 2.0
  3192. imageSticker.clipsToBounds = true
  3193. imageSticker.translatesAutoresizingMaskIntoConstraints = false
  3194. imageSticker.trailingAnchor.constraint(equalTo: containerReply.trailingAnchor, constant: -10).isActive = true
  3195. imageSticker.centerYAnchor.constraint(equalTo: containerReply.centerYAnchor).isActive = true
  3196. imageSticker.widthAnchor.constraint(equalToConstant: 30).isActive = true
  3197. imageSticker.heightAnchor.constraint(equalToConstant: 30).isActive = true
  3198. titleReply.trailingAnchor.constraint(equalTo: imageSticker.leadingAnchor, constant: -20).isActive = true
  3199. contentReply.trailingAnchor.constraint(equalTo: imageSticker.leadingAnchor, constant: -20).isActive = true
  3200. }
  3201. if !copySession && !forwardSession && !deleteSession {
  3202. let objectTap = ObjectGesture(target: self, action: #selector(contentMessageTapped(_:)))
  3203. containerReply.addGestureRecognizer(objectTap)
  3204. objectTap.indexPath = indexPath
  3205. objectTap.message_id = data["message_id"] as! String
  3206. }
  3207. }
  3208. }
  3209. return cellMessage
  3210. }
  3211. @objc func tapAck(_ sender: ObjectGesture) {
  3212. let indexPath = sender.indexPath
  3213. let dataMessages = self.dataMessages.filter({ $0["chat_date"] as! String == dataDates[indexPath.section]})
  3214. if dataMessages[indexPath.row]["status"] as! String == "8" {
  3215. return
  3216. }
  3217. if !CheckConnection.isConnectedToNetwork() || API.nGetCLXConnState() == 0 {
  3218. let imageView = UIImageView(image: UIImage(systemName: "xmark.circle.fill"))
  3219. imageView.tintColor = .white
  3220. let banner = FloatingNotificationBanner(title: "Check your connection".localized(), subtitle: nil, titleFont: UIFont.systemFont(ofSize: 16), titleColor: nil, titleTextAlign: .left, subtitleFont: nil, subtitleColor: nil, subtitleTextAlign: nil, leftView: imageView, rightView: nil, style: .danger, colors: nil, iconPosition: .center)
  3221. banner.show()
  3222. return
  3223. }
  3224. DispatchQueue.global().async {
  3225. var opposite_pin = self.dataGroup["group_id"] as! String
  3226. if (self.dataTopic["chat_id"] as! String != "") {
  3227. opposite_pin = self.dataTopic["chat_id"] as! String
  3228. }
  3229. let result = Nexilis.write(message: CoreMessage_TMessageBank.getAckLocationMessage(f_pin: dataMessages[indexPath.row]["f_pin"] as! String, message_id: dataMessages[indexPath.row]["message_id"] as! String, l_pin: opposite_pin, server_date: "\(Date().currentTimeMillis())", message_scope_id: dataMessages[indexPath.row]["message_scope_id"] as! String, longitude: "", latitude: "", description: ""))
  3230. if result != nil {
  3231. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  3232. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE", cvalues: [
  3233. "status" : "8"
  3234. ], _where: "message_id = '\(dataMessages[indexPath.row]["message_id"] as! String)'")
  3235. })
  3236. DispatchQueue.main.async {
  3237. if let index = self.dataMessages.firstIndex(where: {$0["message_id"] as? String == dataMessages[indexPath.row]["message_id"] as? String}) {
  3238. self.dataMessages[index]["status"] = "8"
  3239. let section = self.dataDates.firstIndex(of: self.dataMessages[index]["chat_date"] as! String)
  3240. let row = self.dataMessages.filter({$0["chat_date"] as! String == self.dataMessages[index]["chat_date"] as! String}).firstIndex(where: { $0["message_id"] as? String == self.dataMessages[indexPath.row]["message_id"] as? String})
  3241. if row != nil && section != nil {
  3242. self.tableChatView.reloadRows(at: [IndexPath(row: row!, section: section!)], with: .none)
  3243. }
  3244. self.showToast(message: "Confirmation Success.".localized(), font: UIFont.systemFont(ofSize: 12, weight: .medium), controller: self)
  3245. }
  3246. }
  3247. }
  3248. }
  3249. }
  3250. @objc func contentMessageTapped(_ sender: ObjectGesture) {
  3251. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  3252. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  3253. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  3254. if (sender.image_id != "") {
  3255. if let dirPath = paths.first {
  3256. let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(sender.image_id)
  3257. if FileManager.default.fileExists(atPath: imageURL.path) {
  3258. let image = UIImage(contentsOfFile: imageURL.path)
  3259. let previewImageVC = PreviewAttachmentImageVideo(nibName: "PreviewAttachmentImageVideo", bundle: Bundle.resourceBundle(for: Nexilis.self))
  3260. previewImageVC.image = image
  3261. previewImageVC.isHiddenTextField = true
  3262. previewImageVC.modalPresentationStyle = .custom
  3263. previewImageVC.modalTransitionStyle = .crossDissolve
  3264. self.present(previewImageVC, animated: true, completion: nil)
  3265. } else {
  3266. for view in sender.imageView.subviews {
  3267. if view is UIImageView {
  3268. view.removeFromSuperview()
  3269. }
  3270. }
  3271. let activityIndicator = UIActivityIndicatorView(style: .large)
  3272. activityIndicator.color = .mainColor
  3273. activityIndicator.hidesWhenStopped = true
  3274. activityIndicator.center = CGPoint(x:sender.imageView.frame.width/2,
  3275. y: sender.imageView.frame.height/2)
  3276. activityIndicator.startAnimating()
  3277. sender.imageView.addSubview(activityIndicator)
  3278. Download().start(forKey: sender.image_id) { (name, progress) in
  3279. guard progress == 100 else {
  3280. return
  3281. }
  3282. let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(sender.image_id)
  3283. let image = UIImage(contentsOfFile: imageURL.path)
  3284. let save = UserDefaults.standard.bool(forKey: "saveToGallery")
  3285. if save {
  3286. UIImageWriteToSavedPhotosAlbum(image!, nil, nil, nil)
  3287. }
  3288. DispatchQueue.main.async {
  3289. activityIndicator.stopAnimating()
  3290. self.tableChatView.reloadRows(at: [sender.indexPath], with: .none)
  3291. }
  3292. }
  3293. }
  3294. }
  3295. } else if (sender.video_id != "") {
  3296. if let dirPath = paths.first {
  3297. let videoURL = URL(fileURLWithPath: dirPath).appendingPathComponent(sender.video_id)
  3298. if FileManager.default.fileExists(atPath: videoURL.path) {
  3299. let player = AVPlayer(url: videoURL as URL)
  3300. let playerVC = AVPlayerViewController()
  3301. playerVC.modalPresentationStyle = .custom
  3302. playerVC.player = player
  3303. self.present(playerVC, animated: true, completion: nil)
  3304. } else {
  3305. for view in sender.imageView.subviews {
  3306. if view is UIImageView {
  3307. view.removeFromSuperview()
  3308. }
  3309. }
  3310. let container = UIView()
  3311. sender.imageView.addSubview(container)
  3312. container.translatesAutoresizingMaskIntoConstraints = false
  3313. container.centerXAnchor.constraint(equalTo: sender.imageView.centerXAnchor).isActive = true
  3314. container.centerYAnchor.constraint(equalTo: sender.imageView.centerYAnchor).isActive = true
  3315. container.widthAnchor.constraint(equalToConstant: 50).isActive = true
  3316. container.heightAnchor.constraint(equalToConstant: 50).isActive = true
  3317. let circlePath = UIBezierPath(arcCenter: CGPoint(x: 25, y: 25), radius: 20, startAngle: -(.pi / 2), endAngle: .pi * 2, clockwise: true)
  3318. let trackShape = CAShapeLayer()
  3319. trackShape.path = circlePath.cgPath
  3320. trackShape.fillColor = UIColor.clear.cgColor
  3321. trackShape.lineWidth = 10
  3322. trackShape.strokeColor = UIColor.blueBubbleColor.withAlphaComponent(0.3).cgColor
  3323. container.backgroundColor = .clear
  3324. container.layer.addSublayer(trackShape)
  3325. let shapeLoading = CAShapeLayer()
  3326. shapeLoading.path = circlePath.cgPath
  3327. shapeLoading.fillColor = UIColor.clear.cgColor
  3328. shapeLoading.lineWidth = 10
  3329. shapeLoading.strokeEnd = 0
  3330. shapeLoading.strokeColor = UIColor.blueBubbleColor.cgColor
  3331. container.layer.addSublayer(shapeLoading)
  3332. let imageDownload = UIImageView(image: UIImage(systemName: "arrow.down", withConfiguration: UIImage.SymbolConfiguration(pointSize: 10, weight: .bold, scale: .default)))
  3333. imageDownload.tintColor = .white
  3334. container.addSubview(imageDownload)
  3335. imageDownload.translatesAutoresizingMaskIntoConstraints = false
  3336. imageDownload.centerXAnchor.constraint(equalTo: sender.imageView.centerXAnchor).isActive = true
  3337. imageDownload.centerYAnchor.constraint(equalTo: sender.imageView.centerYAnchor).isActive = true
  3338. imageDownload.widthAnchor.constraint(equalToConstant: 30).isActive = true
  3339. imageDownload.heightAnchor.constraint(equalToConstant: 30).isActive = true
  3340. Download().start(forKey: sender.video_id) { (name, progress) in
  3341. DispatchQueue.main.async {
  3342. guard progress == 100 else {
  3343. shapeLoading.strokeEnd = CGFloat(progress / 100)
  3344. return
  3345. }
  3346. let save = UserDefaults.standard.bool(forKey: "saveToGallery")
  3347. if save {
  3348. let videoURL = URL(fileURLWithPath: dirPath).appendingPathComponent(sender.video_id)
  3349. PHPhotoLibrary.shared().performChanges({
  3350. PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: videoURL)
  3351. }) { saved, error in
  3352. }
  3353. }
  3354. let idx = self.dataMessages.firstIndex(where: { $0["video_id"] as! String == sender.video_id})
  3355. if idx != nil {
  3356. self.dataMessages[idx!]["progress"] = progress
  3357. self.tableChatView.reloadRows(at: [sender.indexPath], with: .none)
  3358. }
  3359. }
  3360. }
  3361. }
  3362. }
  3363. } else if (sender.file_id != "") {
  3364. if let dirPath = paths.first {
  3365. let fileURL = URL(fileURLWithPath: dirPath).appendingPathComponent(sender.file_id)
  3366. if FileManager.default.fileExists(atPath: fileURL.path) {
  3367. self.previewItem = fileURL as NSURL
  3368. let previewController = QLPreviewController()
  3369. let rightBarButton = UIBarButtonItem()
  3370. previewController.navigationItem.rightBarButtonItem = rightBarButton
  3371. previewController.dataSource = self
  3372. previewController.modalPresentationStyle = .custom
  3373. self.show(previewController, sender: nil)
  3374. } else {
  3375. for view in sender.containerFile.subviews {
  3376. if !(view is UIImageView) && !(view is UILabel) {
  3377. view.removeFromSuperview()
  3378. }
  3379. }
  3380. let containerLoading = UIView()
  3381. sender.containerFile.addSubview(containerLoading)
  3382. containerLoading.translatesAutoresizingMaskIntoConstraints = false
  3383. containerLoading.centerYAnchor.constraint(equalTo: sender.containerFile.centerYAnchor).isActive = true
  3384. containerLoading.leadingAnchor.constraint(equalTo: sender.labelFile.trailingAnchor, constant: 5).isActive = true
  3385. containerLoading.trailingAnchor.constraint(equalTo: sender.containerFile.trailingAnchor, constant: -5).isActive = true
  3386. containerLoading.widthAnchor.constraint(equalToConstant: 30).isActive = true
  3387. containerLoading.heightAnchor.constraint(equalToConstant: 30).isActive = true
  3388. let circlePath = UIBezierPath(arcCenter: CGPoint(x: 15, y: 15), radius: 10, startAngle: -(.pi / 2), endAngle: .pi * 2, clockwise: true)
  3389. let trackShape = CAShapeLayer()
  3390. trackShape.path = circlePath.cgPath
  3391. trackShape.fillColor = UIColor.clear.cgColor
  3392. trackShape.lineWidth = 5
  3393. trackShape.strokeColor = UIColor.blueBubbleColor.withAlphaComponent(0.3).cgColor
  3394. containerLoading.layer.addSublayer(trackShape)
  3395. let shapeLoading = CAShapeLayer()
  3396. shapeLoading.path = circlePath.cgPath
  3397. shapeLoading.fillColor = UIColor.clear.cgColor
  3398. shapeLoading.lineWidth = 3
  3399. shapeLoading.strokeEnd = 0
  3400. shapeLoading.strokeColor = UIColor.blueBubbleColor.cgColor
  3401. containerLoading.layer.addSublayer(shapeLoading)
  3402. let imageupload = UIImageView(image: UIImage(systemName: "arrow.down", withConfiguration: UIImage.SymbolConfiguration(pointSize: 10, weight: .bold, scale: .default)))
  3403. imageupload.tintColor = .white
  3404. containerLoading.addSubview(imageupload)
  3405. imageupload.translatesAutoresizingMaskIntoConstraints = false
  3406. imageupload.centerYAnchor.constraint(equalTo: containerLoading.centerYAnchor).isActive = true
  3407. imageupload.centerXAnchor.constraint(equalTo: containerLoading.centerXAnchor).isActive = true
  3408. Download().start(forKey: sender.file_id) { (name, progress) in
  3409. DispatchQueue.main.async {
  3410. guard progress == 100 else {
  3411. shapeLoading.strokeEnd = CGFloat(progress / 100)
  3412. return
  3413. }
  3414. let idx = self.dataMessages.firstIndex(where: { $0["file_id"] as! String == sender.file_id})
  3415. if idx != nil {
  3416. self.dataMessages[idx!]["progress"] = progress
  3417. self.tableChatView.reloadRows(at: [sender.indexPath], with: .none)
  3418. }
  3419. }
  3420. }
  3421. }
  3422. }
  3423. } else {
  3424. DispatchQueue.main.async {
  3425. let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as! String == sender.message_id})
  3426. if idx == nil {
  3427. return
  3428. }
  3429. let section = self.dataDates.firstIndex(of: self.dataMessages[idx!]["chat_date"] as! String)
  3430. if section == nil {
  3431. return
  3432. }
  3433. let row = self.dataMessages.filter({ $0["chat_date"] as! String == self.dataDates[section!]}).firstIndex(where: { $0["message_id"] as! String == self.dataMessages[idx!]["message_id"] as! String})
  3434. if row == nil {
  3435. return
  3436. }
  3437. let indexPath = IndexPath(row: row!, section: section!)
  3438. self.tableChatView.scrollToRow(at: indexPath, at: .middle, animated: true)
  3439. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  3440. if let cell = self.tableChatView.cellForRow(at: indexPath) {
  3441. let containerMessage = cell.contentView.subviews[1]
  3442. let idMe = UserDefaults.standard.string(forKey: "me") as String?
  3443. if (self.dataMessages[idx!]["f_pin"] as? String == idMe) {
  3444. containerMessage.backgroundColor = .blueBubbleColor.withAlphaComponent(0.3)
  3445. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  3446. if (self.dataMessages[idx!]["attachment_flag"] as? String == "11") {
  3447. containerMessage.backgroundColor = .clear
  3448. } else {
  3449. containerMessage.backgroundColor = .blueBubbleColor
  3450. }
  3451. }
  3452. } else {
  3453. containerMessage.backgroundColor = .grayColor.withAlphaComponent(0.3)
  3454. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  3455. if (self.dataMessages[idx!]["attachment_flag"] as? String == "11") {
  3456. containerMessage.backgroundColor = .clear
  3457. } else {
  3458. containerMessage.backgroundColor = .grayColor
  3459. }
  3460. }
  3461. }
  3462. }
  3463. }
  3464. }
  3465. }
  3466. }
  3467. @objc func tapMessageText(_ sender: ObjectGesture) {
  3468. var stringURl = sender.message_id.lowercased()
  3469. if stringURl.starts(with: "www.") {
  3470. stringURl = "https://" + stringURl.replacingOccurrences(of: "www.", with: "")
  3471. }
  3472. guard let url = URL(string: stringURl) else { return }
  3473. UIApplication.shared.open(url)
  3474. }
  3475. // public func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
  3476. // if copySession || forwardSession || deleteSession {
  3477. // return nil
  3478. // }
  3479. // let idMe = UserDefaults.standard.string(forKey: "me") as String?
  3480. // if (dataMessages[indexPath.row]["f_pin"] as? String != idMe) {
  3481. // return nil
  3482. // }
  3483. // let messageInfoVC = MessageInfo()
  3484. // self.navigationController?.show(messageInfoVC, sender: nil)
  3485. // return UISwipeActionsConfiguration()
  3486. // }
  3487. //
  3488. // public func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
  3489. // if copySession || forwardSession || deleteSession {
  3490. // return nil
  3491. // }
  3492. // let action = UIContextualAction(style: .normal,
  3493. // title: "") { [weak self] (action, view, completionHandler) in
  3494. // self?.handleReply(indexPath: indexPath)
  3495. // completionHandler(true)
  3496. // }
  3497. // action.backgroundColor = .white
  3498. // action.image = UIImage(systemName: "arrowshape.turn.up.left.fill")?.withTintColor(.black, renderingMode: .alwaysOriginal)
  3499. // return UISwipeActionsConfiguration(actions: [action])
  3500. // }
  3501. private func handleReply(indexPath: IndexPath) {
  3502. self.deleteReplyView()
  3503. self.textFieldSend.becomeFirstResponder()
  3504. self.reffId = dataMessages[indexPath.row]["message_id"] as? String
  3505. UIView.animate(withDuration: 0.25, delay: 0.0, options: .curveEaseInOut, animations: {
  3506. self.constraintTopTextField.constant = self.constraintTopTextField.constant + 50
  3507. }, completion: nil)
  3508. if (self.currentIndexpath != nil) {
  3509. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  3510. self.tableChatView.scrollToRow(at: IndexPath(row: self.currentIndexpath!.row, section: self.currentIndexpath!.section), at: .none, animated: false)
  3511. }
  3512. } else {
  3513. self.tableChatView.scrollToBottom()
  3514. }
  3515. self.viewTextfield.addSubview(self.containerPreviewReply)
  3516. self.containerPreviewReply.translatesAutoresizingMaskIntoConstraints = false
  3517. self.containerPreviewReply.leadingAnchor.constraint(equalTo: self.viewTextfield.leadingAnchor).isActive = true
  3518. self.containerPreviewReply.topAnchor.constraint(equalTo: self.viewTextfield.topAnchor).isActive = true
  3519. if !self.containerLink.isDescendant(of: self.viewTextfield) {
  3520. self.bottomAnchorPreviewReply = self.containerPreviewReply.bottomAnchor.constraint(equalTo: self.textFieldSend.topAnchor)
  3521. } else {
  3522. self.bottomAnchorPreviewReply = self.containerPreviewReply.bottomAnchor.constraint(equalTo: self.containerLink.topAnchor)
  3523. }
  3524. self.bottomAnchorPreviewReply.isActive = true
  3525. self.containerPreviewReply.trailingAnchor.constraint(equalTo: self.viewTextfield.trailingAnchor).isActive = true
  3526. self.containerPreviewReply.backgroundColor = .secondaryColor
  3527. let leftReply = UIView()
  3528. self.containerPreviewReply.addSubview(leftReply)
  3529. leftReply.translatesAutoresizingMaskIntoConstraints = false
  3530. leftReply.leadingAnchor.constraint(equalTo: self.viewTextfield.leadingAnchor).isActive = true
  3531. leftReply.topAnchor.constraint(equalTo: self.containerPreviewReply.topAnchor).isActive = true
  3532. leftReply.bottomAnchor.constraint(equalTo: self.containerPreviewReply.bottomAnchor).isActive = true
  3533. leftReply.widthAnchor.constraint(equalToConstant: 3).isActive = true
  3534. leftReply.backgroundColor = .orangeColor
  3535. let titleReply = UILabel()
  3536. self.containerPreviewReply.addSubview(titleReply)
  3537. titleReply.translatesAutoresizingMaskIntoConstraints = false
  3538. titleReply.leadingAnchor.constraint(equalTo: leftReply.leadingAnchor, constant: 10).isActive = true
  3539. titleReply.topAnchor.constraint(equalTo: self.containerPreviewReply.topAnchor, constant: 10).isActive = true
  3540. titleReply.font = UIFont.systemFont(ofSize: 12).bold
  3541. let idMe = UserDefaults.standard.string(forKey: "me") as String?
  3542. if (dataMessages[indexPath.row]["f_pin"] as? String == idMe) {
  3543. titleReply.text = "You".localized()
  3544. } else {
  3545. if dataMessages[indexPath.row]["f_pin"] as? String != "-999" {
  3546. let dataPerson = self.getDataProfile(f_pin: dataMessages[indexPath.row]["f_pin"] as! String, message_id: dataMessages[indexPath.row]["message_id"] as! String)
  3547. titleReply.text = dataPerson["name"]
  3548. } else {
  3549. titleReply.text = "Bot"
  3550. }
  3551. }
  3552. titleReply.textColor = .orangeColor
  3553. let contentReply = UILabel()
  3554. self.containerPreviewReply.addSubview(contentReply)
  3555. contentReply.translatesAutoresizingMaskIntoConstraints = false
  3556. contentReply.leadingAnchor.constraint(equalTo: leftReply.leadingAnchor, constant: 10).isActive = true
  3557. contentReply.topAnchor.constraint(equalTo: titleReply.bottomAnchor).isActive = true
  3558. contentReply.font = UIFont.systemFont(ofSize: 10)
  3559. let message_text = dataMessages[indexPath.row]["message_text"] as! String
  3560. let attachment_flag = dataMessages[indexPath.row]["attachment_flag"] as! String
  3561. let thumb_chat = dataMessages[indexPath.row]["thumb_id"] as! String
  3562. let image_chat = dataMessages[indexPath.row]["image_id"] as! String
  3563. let video_chat = dataMessages[indexPath.row]["video_id"] as! String
  3564. let file_chat = dataMessages[indexPath.row]["file_id"] as! String
  3565. if (attachment_flag == "0" && thumb_chat == "") {
  3566. contentReply.attributedText = message_text.richText()
  3567. } else if (attachment_flag == "1" || image_chat != "") {
  3568. if (message_text == "") {
  3569. contentReply.text = "📷 Photo".localized()
  3570. } else {
  3571. contentReply.attributedText = message_text.richText()
  3572. }
  3573. } else if (attachment_flag == "2" || video_chat != "") {
  3574. if (message_text == "") {
  3575. contentReply.text = "📹 Video".localized()
  3576. } else {
  3577. contentReply.attributedText = message_text.richText()
  3578. }
  3579. } else if (attachment_flag == "6" || file_chat != ""){
  3580. contentReply.text = "📄 \(message_text.components(separatedBy: "|")[0])"
  3581. } else if (attachment_flag == "11") {
  3582. contentReply.text = "❤️ Sticker"
  3583. } else if attachment_flag == "27" {
  3584. contentReply.text = "📄 " + "Live Streaming".localized()
  3585. } else if attachment_flag == "26" {
  3586. contentReply.text = "📄 " + "Seminar".localized()
  3587. }
  3588. contentReply.textColor = .gray
  3589. let buttonCancelReply = UIButton(type: .custom)
  3590. self.containerPreviewReply.addSubview(buttonCancelReply)
  3591. buttonCancelReply.translatesAutoresizingMaskIntoConstraints = false
  3592. buttonCancelReply.trailingAnchor.constraint(equalTo: self.containerPreviewReply.trailingAnchor, constant: -10).isActive = true
  3593. buttonCancelReply.centerYAnchor.constraint(equalTo: self.containerPreviewReply.centerYAnchor).isActive = true
  3594. buttonCancelReply.setImage(UIImage(systemName: "xmark.circle" , withConfiguration: UIImage.SymbolConfiguration(pointSize: 20, weight: .regular, scale: .default)), for: .normal)
  3595. buttonCancelReply.addTarget(nil, action: #selector(self.deleteReplyView), for: .touchUpInside)
  3596. buttonCancelReply.backgroundColor = .clear
  3597. buttonCancelReply.tintColor = .mainColor
  3598. if (attachment_flag == "1" || attachment_flag == "2" || image_chat != "" || video_chat != "") {
  3599. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  3600. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  3601. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  3602. if let dirPath = paths.first {
  3603. let thumbURL = URL(fileURLWithPath: dirPath).appendingPathComponent(thumb_chat)
  3604. let image = UIImage(contentsOfFile: thumbURL.path)
  3605. let imageThumb = UIImageView(image: image)
  3606. self.containerPreviewReply.addSubview(imageThumb)
  3607. imageThumb.layer.cornerRadius = 2.0
  3608. imageThumb.clipsToBounds = true
  3609. imageThumb.translatesAutoresizingMaskIntoConstraints = false
  3610. imageThumb.trailingAnchor.constraint(equalTo: buttonCancelReply.leadingAnchor, constant: -10).isActive = true
  3611. imageThumb.centerYAnchor.constraint(equalTo: self.containerPreviewReply.centerYAnchor).isActive = true
  3612. imageThumb.widthAnchor.constraint(equalToConstant: 30).isActive = true
  3613. imageThumb.heightAnchor.constraint(equalToConstant: 30).isActive = true
  3614. if (attachment_flag == "2") {
  3615. let imagePlay = UIImageView(image: UIImage(systemName: "play.circle.fill"))
  3616. imageThumb.addSubview(imagePlay)
  3617. imagePlay.clipsToBounds = true
  3618. imagePlay.translatesAutoresizingMaskIntoConstraints = false
  3619. imagePlay.centerYAnchor.constraint(equalTo: imageThumb.centerYAnchor).isActive = true
  3620. imagePlay.centerXAnchor.constraint(equalTo: imageThumb.centerXAnchor).isActive = true
  3621. imagePlay.widthAnchor.constraint(equalToConstant: 10).isActive = true
  3622. imagePlay.heightAnchor.constraint(equalToConstant: 10).isActive = true
  3623. imagePlay.tintColor = .white
  3624. }
  3625. }
  3626. }
  3627. if (attachment_flag == "11") {
  3628. let imageSticker = UIImageView(image: UIImage(named: (message_text.components(separatedBy: "/")[1]), in: Bundle.resourceBundle(for: Nexilis.self), with: nil))
  3629. self.containerPreviewReply.addSubview(imageSticker)
  3630. imageSticker.layer.cornerRadius = 2.0
  3631. imageSticker.clipsToBounds = true
  3632. imageSticker.translatesAutoresizingMaskIntoConstraints = false
  3633. imageSticker.trailingAnchor.constraint(equalTo: buttonCancelReply.leadingAnchor, constant: -10).isActive = true
  3634. imageSticker.centerYAnchor.constraint(equalTo: self.containerPreviewReply.centerYAnchor).isActive = true
  3635. imageSticker.widthAnchor.constraint(equalToConstant: 30).isActive = true
  3636. imageSticker.heightAnchor.constraint(equalToConstant: 30).isActive = true
  3637. }
  3638. }
  3639. func scrollToFirstSearchMessage(indexScroll: Int = 1) {
  3640. if textSearch.count < 2 {
  3641. return
  3642. }
  3643. var lastIndex = 0
  3644. let messageTextForSearch: [[String: Any?]] = self.dataMessages.reversed()
  3645. for idx in 0..<messageTextForSearch.count {
  3646. if (messageTextForSearch[idx]["message_text"] as! String).lowercased().contains(textSearch) {
  3647. lastIndex += 1
  3648. if lastIndex < indexScroll {
  3649. continue
  3650. }
  3651. lastScrollIdxSearch = lastIndex
  3652. let section = self.dataDates.firstIndex(of: messageTextForSearch[idx]["chat_date"] as! String)
  3653. if section == nil {
  3654. return
  3655. }
  3656. let row = self.dataMessages.filter({ $0["chat_date"] as! String == self.dataDates[section!]}).firstIndex(where: { $0["message_id"] as! String == messageTextForSearch[idx]["message_id"] as! String})
  3657. if row == nil {
  3658. return
  3659. }
  3660. let indexPath = IndexPath(row: row!, section: section!)
  3661. self.tableChatView.scrollToRow(at: indexPath, at: .middle, animated: true)
  3662. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  3663. if let cell = self.tableChatView.cellForRow(at: indexPath) {
  3664. let containerMessage = cell.contentView.subviews[1]
  3665. let idMe = UserDefaults.standard.string(forKey: "me") as String?
  3666. if (messageTextForSearch[idx]["f_pin"] as? String == idMe) {
  3667. containerMessage.backgroundColor = .blueBubbleColor.withAlphaComponent(0.3)
  3668. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  3669. if (messageTextForSearch[idx]["attachment_flag"] as? String == "11") {
  3670. containerMessage.backgroundColor = .clear
  3671. } else {
  3672. containerMessage.backgroundColor = .blueBubbleColor
  3673. }
  3674. }
  3675. } else {
  3676. containerMessage.backgroundColor = .grayColor.withAlphaComponent(0.3)
  3677. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  3678. if (messageTextForSearch[idx]["attachment_flag"] as? String == "11") {
  3679. containerMessage.backgroundColor = .clear
  3680. } else {
  3681. containerMessage.backgroundColor = .grayColor
  3682. }
  3683. }
  3684. }
  3685. }
  3686. }
  3687. titleSearchMatches.isHidden = false
  3688. if countMatchesSearch != 0 {
  3689. if countMatchesSearch > 1 {
  3690. titleSearchMatches.text = "\(lastScrollIdxSearch) " + "of".localized() + " \(countMatchesSearch) " + "matches".localized()
  3691. } else {
  3692. titleSearchMatches.text = "\(countMatchesSearch) " + "matches".localized()
  3693. }
  3694. } else {
  3695. titleSearchMatches.text = "Not found".localized()
  3696. }
  3697. if lastScrollIdxSearch == countMatchesSearch || countMatchesSearch == 0 {
  3698. buttonUp.isEnabled = false
  3699. buttonUp.tintColor = .gray
  3700. } else {
  3701. buttonUp.isEnabled = true
  3702. buttonUp.tintColor = .mainColor
  3703. }
  3704. if countMatchesSearch == 0 || lastScrollIdxSearch == 1 || countMatchesSearch == 1 {
  3705. buttonDown.isEnabled = false
  3706. buttonDown.tintColor = .gray
  3707. } else {
  3708. buttonDown.isEnabled = true
  3709. buttonDown.tintColor = .mainColor
  3710. }
  3711. break
  3712. }
  3713. }
  3714. }
  3715. }
  3716. extension EditorGroup: UISearchBarDelegate {
  3717. public func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
  3718. textSearch = searchText
  3719. countMatchesSearch = 0
  3720. titleSearchMatches.isHidden = true
  3721. tableChatView.reloadData()
  3722. scrollToFirstSearchMessage()
  3723. }
  3724. }