EditorGroup.swift 230 KB

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