EditorGroup.swift 231 KB

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