12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556 |
- //
- // EditorGroup.swift
- // Qmera
- //
- // Created by Akhmad Al Qindi Irsyam on 20/09/21.
- //
- import UIKit
- import AVKit
- import AVFoundation
- import QuickLook
- import Photos
- import NotificationBannerSwift
- import nuSDKService
- import SwiftLinkPreview
- public class EditorGroup: UIViewController {
- @IBOutlet var viewButton: UIView!
- @IBOutlet var constraintViewTextField: NSLayoutConstraint!
- @IBOutlet var buttonVoice: UIButton!
- @IBOutlet var buttonSendImage: UIButton!
- @IBOutlet var buttonSendPhoto: UIButton!
- @IBOutlet var buttonSendSticker: UIButton!
- @IBOutlet var buttonSendFile: UIButton!
- @IBOutlet var textFieldSend: UITextView!
- @IBOutlet var heightTextFieldSend: NSLayoutConstraint!
- @IBOutlet var buttonSendChat: UIButton!
- @IBOutlet var tableChatView: UITableView!
- @IBOutlet var constraintTopTextField: NSLayoutConstraint!
- @IBOutlet var constraintBottomAttachment: NSLayoutConstraint!
- @IBOutlet var viewTextfield: UIView!
- @IBOutlet weak var buttonAckConfidential: UIButton!
- @IBOutlet weak var constraintBottomTableViewWithTextfield: NSLayoutConstraint!
- @IBOutlet weak var viewAttachment: UIStackView!
- @IBOutlet weak var tableMention: UITableView!
- @IBOutlet weak var heightTableMention: NSLayoutConstraint!
- @IBOutlet weak var contraintBottomMention: NSLayoutConstraint!
- public var dataGroup: [String: Any?] = [:]
- public var dataTopic: [String: Any?] = [:]
- var dataMessages: [[String: Any?]] = []
- var dataDates: [String] = []
- public var dataMessageForward: [[String: Any?]]?
- var imageVideoPicker: ImageVideoPicker!
- var documentPicker: DocumentPicker!
- var currentIndexpath: IndexPath?
- var previewItem: NSURL?
- var reffId: String?
- var stickers = [String]()
- public var unique_l_pin = ""
- public var fromNotification = false
- var isHistoryCC = false
- var complaintId = ""
- var counter = 0
- var markerCounter: String?
- var buttonScrollToBottom = UIButton()
- let indicatorCounterBSTB = UIView()
- let labelCounter = UILabel()
- let containerActionGroup = UIView()
- var removed = false
- var isAck = false
- var copySession = false
- var forwardSession = false
- var deleteSession = false
- var isSearching = false
- let containerMultpileSelectSession = UIView()
- let viewSticker = UIView()
- let containerLink = UIView()
- let containerPreviewReply = UIView()
- var bottomAnchorPreviewReply = NSLayoutConstraint()
- let containerAction = UIView()
- var allowTyping = true
- let contactChatNav = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "contactChatNav") as! UINavigationController
- var searchBar: UISearchBar!
- var constraintBottomContainerMultpileSelectSession = NSLayoutConstraint()
- var titleSearchMatches: UILabel!
- var textSearch = ""
- var countMatchesSearch = 0
- var lastScrollIdxSearch = 0
- var buttonUp: UIButton!
- var buttonDown: UIButton!
- var keyboardHeightForMention: CGFloat?
- var listMentionWithText:[User] = []
- var listMentionInTextField:[User] = []
- var showingLink = ""
- var isAlwaysHideLinkPreview = false
- var timerCheckLink: Timer?
- var lastPositionCursorMention = 0
- var timerLongPressLink: Timer?
- var lastTouchPoint: CGPoint = .zero
- var isLinkCopied = false
- var touchedSubview = UIView()
- var listViewOnSection: [UIView] = []
-
- public override func viewDidDisappear(_ animated: Bool) {
- if self.isMovingFromParent {
- UserDefaults.standard.removeObject(forKey: "inEditorGroup")
- NotificationCenter.default.removeObserver(self)
- }
- }
-
- public override func viewDidAppear(_ animated: Bool) {
- let navBarAppearance = UINavigationBarAppearance()
- navBarAppearance.configureWithOpaqueBackground()
- navBarAppearance.backgroundColor = UIColor.mainColor
- navigationController?.navigationBar.standardAppearance = navBarAppearance
- navigationController?.navigationBar.scrollEdgeAppearance = navBarAppearance
- navigationController?.navigationBar.isTranslucent = false
- navigationController?.navigationBar.backgroundColor = .mainColor
- navigationController?.navigationBar.tintColor = .white
- navigationController?.navigationBar.overrideUserInterfaceStyle = .dark
- navigationController?.navigationBar.barStyle = .black
- if self.navigationController?.isNavigationBarHidden ?? false {
- self.navigationController?.setNavigationBarHidden(false, animated: false)
- }
- updateProfile()
- let indexPath = tableChatView.indexPathsForVisibleRows?.first
- if indexPath != nil {
- let headerRect = tableChatView.rectForHeader(inSection: indexPath!.section)
- let isPinned = headerRect.origin.y <= tableChatView.contentOffset.y
- if listViewOnSection.count != 0 && listViewOnSection.count - 1 <= indexPath!.section && isPinned {
- let headerView = listViewOnSection[currentIndexpath!.section]
- headerView.isHidden = true
- }
- }
- }
-
- public override func viewDidLoad() {
- super.viewDidLoad()
- // navigationController?.navigationBar.topItem?.title = ""
-
- viewButton.layer.shadowColor = UIColor.gray.cgColor
- viewButton.layer.shadowOpacity = 1
- viewButton.layer.shadowOffset = .zero
- viewButton.layer.shadowRadius = 3
-
- // buttonVoice.setImage(resizeImage(image: UIImage(named: "Voice-Record", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!, targetSize: CGSize(width: 30, height: 30)), for: .normal)
- 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)
- 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)
- 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)
- 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)
-
- 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)
-
- buttonSendChat.circle()
- buttonSendChat.addTarget(self, action: #selector(sendTapped), for: .touchUpInside)
- buttonSendChat.backgroundColor = .mainColor
- buttonAckConfidential.circle()
- buttonAckConfidential.addTarget(self, action: #selector(showChooserACKConfidential), for: .touchUpInside)
- buttonAckConfidential.backgroundColor = .mainColor
- textFieldSend.layer.cornerRadius = textFieldSend.maxCornerRadius()
- textFieldSend.layer.borderWidth = 1.0
- textFieldSend.text = "Send message".localized()
- textFieldSend.textColor = UIColor.lightGray
- textFieldSend.textContainerInset = UIEdgeInsets(top: 12, left: 20, bottom: 11, right: 40)
- textFieldSend.layer.borderColor = UIColor.lightGray.withAlphaComponent(0.5).cgColor
- textFieldSend.font = UIFont.systemFont(ofSize: 12)
- textFieldSend.delegate = self
-
- navigationItem.rightBarButtonItem?.tintColor = UIColor.secondaryColor
-
- imageVideoPicker = ImageVideoPicker(presentationController: self, delegate: self)
- documentPicker = DocumentPicker(presentationController: self, delegate: self)
-
- let fm = FileManager.default
- let path = Bundle.resourcesMediaBundle(for: Nexilis.self).resourcePath!
- let items = try! fm.contentsOfDirectory(atPath: path)
-
- for item in items {
- if item.hasPrefix("sticker") {
- stickers.append(item)
- }
- }
-
- tableChatView.register(UITableViewCell.self, forCellReuseIdentifier: "cellEditorGroup")
-
- loadData()
- setRightButtonItem()
-
- let center: NotificationCenter = NotificationCenter.default
- center.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
- center.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
- center.addObserver(self, selector: #selector(onReceiveMessage(notification:)), name: NSNotification.Name(rawValue: "onReceiveChat"), object: nil)
- center.addObserver(self, selector: #selector(onStatusChat(notification:)), name: NSNotification.Name(rawValue: "onMessageChat"), object: nil)
- center.addObserver(self, selector: #selector(onUploadChat(notification:)), name: NSNotification.Name(rawValue: "onUploadChat"), object: nil)
- center.addObserver(self, selector: #selector(onMemberTopic(notification:)), name: NSNotification.Name(rawValue: "onMember"), object: nil)
- center.addObserver(self, selector: #selector(onGroup(notification:)), name: NSNotification.Name(rawValue: "onGroup"), object: nil)
- center.addObserver(self, selector: #selector(onMemberTopic(notification:)), name: NSNotification.Name(rawValue: "onTopic"), object: nil)
-
- if dataMessageForward != nil {
- for i in 0..<dataMessageForward!.count {
- 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)
- }
- dataMessageForward = nil
- }
- tableMention.register(UITableViewCell.self, forCellReuseIdentifier: "cellMention")
- tableMention.dataSource = self
- tableMention.delegate = self
- tableMention.contentInset = UIEdgeInsets(top: -25, left: 0, bottom: 0, right: 0)
- }
-
- public func afterUnfriend() {
- DispatchQueue.main.async {
- UserDefaults.standard.removeObject(forKey: "inEditorGroup")
- NotificationCenter.default.removeObserver(self)
- }
- }
-
- private func updateProfile() {
- let idMe = UserDefaults.standard.string(forKey: "me") as String?
- DispatchQueue.global().async {
- let message = CoreMessage_TMessageBank.getBatchBuddiesInfos(p_f_pin: idMe!, last_update: 0)
- let _ = Nexilis.write(message: message)
- }
- }
-
- private func setRightButtonItem() {
- navigationItem.rightBarButtonItems = nil
- navigationItem.rightBarButtonItem = nil
- let menu = UIMenu(title: "", children: [
- UIAction(title: "Delete Conversation".localized(), handler: {(_) in
- let alert = UIAlertController(title: "", message: "Are you sure to delete all message in this conversation?".localized(), preferredStyle: .alert)
- alert.addAction(UIAlertAction(title: "Cancel".localized(), style: UIAlertAction.Style.default, handler: nil))
- alert.addAction(UIAlertAction(title: "Delete".localized(), style: .destructive, handler: {(_) in
- var l_pin = self.dataGroup["group_id"] as! String
- Database.shared.database?.inTransaction({ (fmdb, rollback) in
- if (self.dataTopic["chat_id"] as! String != "") {
- l_pin = self.dataTopic["chat_id"] as! String
- }
- _ = 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'")
- _ = Database.shared.deleteRecord(fmdb: fmdb, table: "MESSAGE_SUMMARY", _where: "l_pin='\(l_pin)'")
- if self.fromNotification {
- self.didTapExit()
- } else {
- self.navigationController?.popViewController(animated: true)
- }
- })
- }))
- self.present(alert, animated: true, completion: nil)
- }),
- ])
- if !isHistoryCC {
- let moreIcon = UIBarButtonItem(image: UIImage(systemName: "ellipsis", withConfiguration: UIImage.SymbolConfiguration(pointSize: 18, weight: .regular, scale: .default)), menu: menu)
- let buttonSearch = UIBarButtonItem(image: UIImage(systemName: "magnifyingglass", withConfiguration: UIImage.SymbolConfiguration(pointSize: 18, weight: .regular, scale: .default)), style: .plain, target: self, action: #selector(search(sender:)))
- navigationItem.rightBarButtonItems = [moreIcon,buttonSearch]
- } else {
- let buttonSearch = UIBarButtonItem(image: UIImage(systemName: "magnifyingglass", withConfiguration: UIImage.SymbolConfiguration(pointSize: 18, weight: .regular, scale: .default)), style: .plain, target: self, action: #selector(search(sender:)))
- navigationItem.rightBarButtonItem = buttonSearch
- }
- }
-
- @objc func search(sender: UIBarButtonItem) {
- self.isSearching = true
- if self.reffId != nil {
- self.deleteReplyView()
- }
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) {
- let cancelButton = UIBarButtonItem(title: "Cancel".localized(), style: .plain, target: self, action: #selector(self.cancelAction))
- cancelButton.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.white], for: .normal)
- if !self.isHistoryCC {
- self.navigationItem.rightBarButtonItems = nil
- }
- self.navigationItem.rightBarButtonItem = cancelButton
- self.changeAppBar()
- self.addMultipleSelectSession()
- }
- }
-
- private func getOfficialGroup() {
- let query = "SELECT group_id, f_name, official, image_id FROM GROUPZ where group_type = 1 AND official = 1"
- Database.shared.database?.inTransaction({ (fmdb, rollback) in
- if let cursorData = Database.shared.getRecords(fmdb: fmdb, query: query) {
- if cursorData.next() {
- dataGroup["group_id"] = cursorData.string(forColumnIndex: 0)
- dataTopic["chat_id"] = ""
- dataGroup["f_name"] = cursorData.string(forColumnIndex: 1)
- dataGroup["image_id"] = cursorData.string(forColumnIndex: 3)
- dataGroup["official"] = cursorData.string(forColumnIndex: 2)
- }
- cursorData.close()
- }
- })
- }
-
- func loadData() {
- if (unique_l_pin != "") {
- dataDates.removeAll()
- dataGroup.removeAll()
- dataTopic.removeAll()
- dataMessages.removeAll()
- tableChatView.reloadData()
- currentIndexpath = nil
- reffId = nil
- getDataGroup(unique_l_pin: unique_l_pin)
- }
-
- if removed {
- removed = false
- containerActionGroup.removeConstraints(containerActionGroup.constraints)
- containerActionGroup.removeFromSuperview()
- setRightButtonItem()
- }
-
- if !isHistoryCC {
- UserDefaults.standard.set([dataGroup["group_id"], dataTopic["chat_id"]], forKey: "inEditorGroup")
-
- if dataTopic["chat_id"] as! String == "" {
- UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [dataGroup["group_id"] as! String])
- sendTyping(l_pin: dataGroup["group_id"] as! String)
- } else {
- UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [dataTopic["chat_id"] as! String])
- sendTyping(l_pin: dataTopic["chat_id"] as! String)
- }
- } else {
- getOfficialGroup()
- disableEditor()
- }
-
- if fromNotification {
- let imageButton = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 44))
- imageButton.image = UIImage(systemName: "chevron.backward")?.withTintColor(.white)
- imageButton.contentMode = .right
- let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didTapExit))
- imageButton.isUserInteractionEnabled = true
- imageButton.addGestureRecognizer(tapGestureRecognizer)
- let leftItem = UIBarButtonItem(customView: imageButton)
- self.navigationItem.leftBarButtonItem = leftItem
- }
-
- changeAppBar()
- getData()
- getCounter()
- if counter > 0 {
- markerCounter = dataMessages[dataMessages.count - counter]["message_id"] as? String
- }
-
- tableChatView.alpha = 0
- tableChatView.delegate = self
- tableChatView.dataSource = self
- tableChatView.reloadData()
- if counter != 0 {
- if dataMessages.firstIndex(where: {$0["message_id"] as? String == markerCounter} ) != 0 {
- DispatchQueue.main.async {
- let data = self.dataMessages.filter({ $0["message_id"] as? String == self.markerCounter })
- let section = self.dataDates.firstIndex(of: data[0]["chat_date"] as! String)
- 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})
- self.tableChatView.scrollToRow(at: IndexPath(row: row!, section: section!), at: .bottom, animated: false)
- }
- } else {
- tableChatView.scrollToTop()
- }
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [self] in
- if currentIndexpath == nil && counter != 0 {
- let idMe = UserDefaults.standard.string(forKey: "me") as String?
- if let idx = dataMessages.firstIndex(where: { $0["message_id"] as? String == markerCounter}) {
- for i in idx..<dataMessages.count {
- if dataMessages[i]["f_pin"] as? String != idMe {
- 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)
- }
- }
- counter = 0
- updateCounter(counter: counter)
- }
- }
- }
- } else {
- tableChatView.scrollToBottom(isAnimated: false)
- }
- tableChatView.keyboardDismissMode = .interactive
- let tapGesture = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
- tapGesture.cancelsTouchesInView = false
- tableChatView.addGestureRecognizer(tapGesture)
- UIView.animate(withDuration: 0.5, animations: {
- self.tableChatView.alpha = 1.0
- })
- }
-
- func getDataProfile(f_pin: String, message_id: String) -> [String: String]{
- var data: [String: String] = [:]
- Database().database?.inTransaction({ fmdb, rollback in
- if let c = Database().getRecords(fmdb: fmdb, query: "select first_name || ' ' || last_name, image_id from BUDDY where f_pin = '\(f_pin)'"), c.next() {
- data["name"] = c.string(forColumnIndex: 0)!.trimmingCharacters(in: .whitespacesAndNewlines)
- data["image_id"] = c.string(forColumnIndex: 1)!
- c.close()
- }
- 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() {
- data["name"] = c.string(forColumnIndex: 0)!.trimmingCharacters(in: .whitespacesAndNewlines)
- data["image_id"] = c.string(forColumnIndex: 1)!
- c.close()
- } else if let c = Database().getRecords(fmdb: fmdb, query: "select f_display_name from MESSAGE where message_id = '\(message_id)'"), c.next() {
- data["name"] = c.string(forColumnIndex: 0)!
- data["image_id"] = ""
- c.close()
- } else {
- data["name"] = "Unknown".localized()
- }
- })
- return data
- }
-
- private func getDataGroup(unique_l_pin: String) {
- Database.shared.database?.inTransaction({ (fmdb, rollback) in
- 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() {
- dataGroup["group_id"] = cursorGroup.string(forColumnIndex: 0)
- dataGroup["f_name"] = cursorGroup.string(forColumnIndex: 1)
- dataGroup["image_id"] = cursorGroup.string(forColumnIndex: 2)
- dataGroup["official"] = cursorGroup.string(forColumnIndex: 3)
- dataGroup["parent"] = cursorGroup.string(forColumnIndex: 4)
- dataTopic["title"] = "Lounge".localized()
- dataTopic["chat_id"] = ""
- cursorGroup.close()
- } 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() {
- dataGroup["group_id"] = cursorTopic.string(forColumnIndex: 0)
- dataTopic["title"] = cursorTopic.string(forColumnIndex: 1)
- dataTopic["chat_id"] = unique_l_pin
- cursorTopic.close()
- 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() {
- dataGroup["f_name"] = cursorGroup.string(forColumnIndex: 0)
- dataGroup["image_id"] = cursorGroup.string(forColumnIndex: 1)
- dataGroup["official"] = cursorGroup.string(forColumnIndex: 2)
- dataGroup["parent"] = cursorGroup.string(forColumnIndex: 3)
- cursorGroup.close()
- }
- }
- })
- }
-
- private func getData() {
- Database.shared.database?.inTransaction({ (fmdb, rollback) in
- 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"
- if isHistoryCC {
- 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"
- } else if (dataTopic["chat_id"] as! String != "") {
- 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"
- }
- if let cursorData = Database.shared.getRecords(fmdb: fmdb, query: query) {
- while cursorData.next() {
- var row: [String: Any?] = [:]
- row["message_id"] = cursorData.string(forColumnIndex: 0)
- row["f_pin"] = cursorData.string(forColumnIndex: 1)
- row["l_pin"] = cursorData.string(forColumnIndex: 2)
- row["message_scope_id"] = cursorData.string(forColumnIndex: 3)
- row["server_date"] = cursorData.string(forColumnIndex: 4)
- row["status"] = cursorData.string(forColumnIndex: 5)
- row["message_text"] = cursorData.string(forColumnIndex: 6)
- row["audio_id"] = cursorData.string(forColumnIndex: 7)
- row["video_id"] = cursorData.string(forColumnIndex: 8)
- row["image_id"] = cursorData.string(forColumnIndex: 9)
- row["thumb_id"] = cursorData.string(forColumnIndex: 10)
- row["read_receipts"] = cursorData.string(forColumnIndex: 11)
- row["chat_id"] = cursorData.string(forColumnIndex: 12)
- row["file_id"] = cursorData.string(forColumnIndex: 13)
- row["attachment_flag"] = cursorData.string(forColumnIndex: 14)
- row["reff_id"] = cursorData.string(forColumnIndex: 15)
- row["lock"] = cursorData.string(forColumnIndex: 16)
- row["is_stared"] = cursorData.string(forColumnIndex: 17)
- row["blog_id"] = cursorData.string(forColumnIndex: 18)
- row["isSelected"] = false
- let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
- let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
- let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
- if let dirPath = paths.first {
- let videoURL = URL(fileURLWithPath: dirPath).appendingPathComponent(row["video_id"] as! String)
- let fileURL = URL(fileURLWithPath: dirPath).appendingPathComponent(row["file_id"] as! String)
- if ((row["video_id"] as! String) != "") {
- if FileManager.default.fileExists(atPath: videoURL.path){
- row["progress"] = 100.0
- } else {
- row["progress"] = 0.0
- }
- } else {
- if FileManager.default.fileExists(atPath: fileURL.path){
- row["progress"] = 100.0
- } else {
- row["progress"] = 0.0
- }
- }
- }
- row["chat_date"] = chatDate(stringDate: row["server_date"] as! String)
- dataMessages.append(row)
- }
- // if isHistoryCC {
- // dataMessages.remove(at: 0)
- // }
- cursorData.close()
- }
- })
- }
-
- private func getRealStatus(messageId: String) -> String {
- var status = "1"
- Database.shared.database?.inTransaction({ (fmdb, rollback) in
- if let cursorStatus = Database.shared.getRecords(fmdb: fmdb, query: "SELECT status, f_pin FROM MESSAGE_STATUS WHERE message_id='\(messageId)'") {
- var listStatus: [Int] = []
- while cursorStatus.next() {
- listStatus.append(Int(cursorStatus.string(forColumnIndex: 0)!)!)
- }
- cursorStatus.close()
- status = "\(listStatus.min() ?? 2)"
- }
- })
- return status
- }
-
- private func chatDate(stringDate: String) -> String {
- let date = Date(milliseconds: Int64(stringDate)!)
- let calendar = Calendar.current
- if (calendar.isDateInToday(date)) {
- if !dataDates.contains("Today".localized()){
- dataDates.append("Today".localized())
- }
- return "Today".localized()
- } else {
- let startOfNow = calendar.startOfDay(for: Date())
- let startOfTimeStamp = calendar.startOfDay(for: date)
- let components = calendar.dateComponents([.day], from: startOfNow, to: startOfTimeStamp)
- let day = -(components.day!)
- if day == 1{
- if !dataDates.contains("Yesterday".localized()){
- dataDates.append("Yesterday".localized())
- }
- return "Yesterday".localized()
- } else if day < 7 {
- if !dataDates.contains("\(day) " + "days".localized() + " " + "ago".localized()){
- dataDates.append("\(day) " + "days".localized() + " " + "ago".localized())
- }
- return "\(day) " + "days".localized() + " " + "ago".localized()
- } else {
- let formatter = DateFormatter()
- formatter.dateFormat = "dd MMMM yyyy"
- formatter.locale = NSLocale(localeIdentifier: "id") as Locale?
- let stringFormat = formatter.string(from: date as Date)
- if !dataDates.contains(stringFormat){
- dataDates.append(stringFormat)
- }
- return stringFormat
- }
- }
- }
-
- private func changeAppBar() {
- let viewAppBar = UIView()
- viewAppBar.frame.size = CGSize(width: self.view.frame.size.width, height: 44)
-
- if !isSearching {
- let imageProfile = UIImageView(frame: CGRect(x: 0, y: 7, width: 30, height: 30))
- imageProfile.circle()
- imageProfile.clipsToBounds = true
- viewAppBar.addSubview(imageProfile)
- let pictureImage = dataGroup["image_id"]!
- if (pictureImage as! String != "" && pictureImage != nil) {
- imageProfile.setImage(name: pictureImage! as! String)
- imageProfile.contentMode = .scaleAspectFill
- } else {
- imageProfile.image = UIImage(systemName: "person.3")
- imageProfile.contentMode = .scaleAspectFit
- imageProfile.backgroundColor = .lightGray
- }
- var widthTitle = viewAppBar.frame.size.width - 180
- if isHistoryCC {
- widthTitle = viewAppBar.frame.size.width - 150
- }
- let titleNavigation = UILabel(frame: CGRect(x: 35, y: 0, width: widthTitle, height: 44))
- viewAppBar.addSubview(titleNavigation)
- if (dataGroup["official"] as! String == "1") {
- if !isHistoryCC {
- titleNavigation.set(image: UIImage(named: "ic_official_flag", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!, with: " \(dataGroup["f_name"]!!) (\(dataTopic["title"]!!))", size: 15, y: -4)
- } else {
- titleNavigation.text = (dataGroup["f_name"] as? String)! + " " + "Contact Center".localized()
- }
- } else {
- titleNavigation.text = (dataGroup["f_name"] as? String)! + " (\(dataTopic["title"]!!))"
- }
- titleNavigation.textColor = .white
- titleNavigation.font = UIFont.systemFont(ofSize: 12).bold
-
- navigationItem.titleView = viewAppBar
- } else {
- searchBar = UISearchBar()
- searchBar.autocapitalizationType = .none
- searchBar.delegate = self
- searchBar.searchTextField.tintColor = .mainColor
- searchBar.barTintColor = .secondaryColor
- searchBar.searchTextField.backgroundColor = .secondaryColor
- searchBar.showsCancelButton = false
- searchBar.setMagnifyingGlassColorTo(color: .mainColor)
- navigationItem.titleView = searchBar
- self.definesPresentationContext = true
- }
-
- if copySession || forwardSession || deleteSession || isSearching {
- navigationItem.hidesBackButton = true
- navigationController?.interactivePopGestureRecognizer?.isEnabled = false
- } else {
- navigationItem.hidesBackButton = false
- navigationController?.interactivePopGestureRecognizer?.isEnabled = true
- }
-
- viewAppBar.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(seeProfileTapped)))
- }
-
- @objc func onUploadChat(notification: NSNotification) {
- let data:[AnyHashable : Any] = notification.userInfo!
- var isImage = false
- var idx = dataMessages.lastIndex(where: { $0["video_id"] as! String == data["name"] as! String })
- if (idx == nil) {
- idx = dataMessages.lastIndex(where: { $0["image_id"] as! String == data["name"] as! String })
- isImage = true
- }
- if (idx != nil) {
- let section = dataDates.firstIndex(of: dataMessages[idx!]["chat_date"] as! String)
- if section == nil {
- return
- }
- let row = dataMessages.filter({ $0["chat_date"] as! String == dataDates[section!]}).firstIndex(where: { $0["message_id"] as! String == dataMessages[idx!]["message_id"] as! String})
- if row == nil {
- return
- }
- DispatchQueue.main.async {
- let indexPath = IndexPath(row: row!, section: section!)
- if let cell = self.tableChatView.cellForRow(at: indexPath) {
- for view in cell.contentView.subviews {
- if !(view is UILabel) && !(view is UIImageView) {
- for viewInContainer in view.subviews {
- if viewInContainer is UIImageView {
- if viewInContainer.subviews.count == 0 {
- return
- }
- var containerView = UIView()
- if (isImage) {
- containerView = viewInContainer.subviews[0]
- } else {
- containerView = viewInContainer.subviews[1]
- }
- let loading = containerView.layer.sublayers![1] as! CAShapeLayer
- loading.strokeEnd = CGFloat(data["progress"] as! Double / 100)
- if (data["progress"] as! Double == 100.0) {
- self.dataMessages[idx!]["progress"] = data["progress"]
- self.tableChatView.reloadRows(at: [indexPath], with: .none)
- }
- }
- }
- }
- }
- }
- }
- } else {
- idx = dataMessages.lastIndex(where: { $0["file_id"] as! String == data["name"] as! String })
- if (idx != nil) {
- DispatchQueue.main.async {
- let section = 0
- let indexPath = IndexPath(row: idx!, section: section)
- if let cell = self.tableChatView.cellForRow(at: indexPath) {
- for view in cell.contentView.subviews {
- if !(view is UILabel) && !(view is UIImageView) {
- for viewSubviews in view.subviews {
- if !(viewSubviews is UILabel) {
- for viewInContainer in viewSubviews.subviews {
- if !(viewInContainer is UILabel) && !(viewInContainer is UIImageView) {
- if viewInContainer.layer.sublayers!.count < 2 {
- return
- }
- let loading = viewInContainer.layer.sublayers![1] as! CAShapeLayer
- loading.strokeEnd = CGFloat(data["progress"] as! Double / 100)
- if (data["progress"] as! Double == 100.0) {
- self.dataMessages[idx!]["progress"] = data["progress"]
- self.tableChatView.reloadRows(at: [indexPath], with: .none)
- }
- }
- }
- }
- }
- }
- }
- }
- }
- }
- }
- }
-
- @objc func onReceiveMessage(notification: NSNotification) {
- DispatchQueue.main.async {
- let data:[AnyHashable : Any] = notification.userInfo!
- if let dataMessage = data["message"] as? TMessage {
- let chatData = dataMessage.mBodies
- let group_id = self.dataGroup["group_id"] as! String
- let chat_id = self.dataTopic["chat_id"] as! String
- if chatData[CoreMessage_TMessageKey.L_PIN] == group_id && (chatData[CoreMessage_TMessageKey.CHAT_ID] ?? "") == chat_id {
- var row: [String: Any?] = [:]
- row["message_id"] = chatData[CoreMessage_TMessageKey.MESSAGE_ID]
- row["f_pin"] = chatData[CoreMessage_TMessageKey.F_PIN]
- row["l_pin"] = chatData[CoreMessage_TMessageKey.L_PIN]
- row["message_scope_id"] = chatData[CoreMessage_TMessageKey.MESSAGE_SCOPE_ID]
- row["server_date"] = chatData[CoreMessage_TMessageKey.SERVER_DATE]
- row["status"] = chatData[CoreMessage_TMessageKey.STATUS]
- row["message_text"] = chatData[CoreMessage_TMessageKey.MESSAGE_TEXT]
- if (chatData.keys.contains(CoreMessage_TMessageKey.AUDIO_ID)) {
- row["audio_id"] = chatData[CoreMessage_TMessageKey.AUDIO_ID]
- } else {
- row["audio_id"] = ""
- }
- if (chatData.keys.contains(CoreMessage_TMessageKey.VIDEO_ID)) {
- row["video_id"] = chatData[CoreMessage_TMessageKey.VIDEO_ID]
- } else {
- row["video_id"] = ""
- }
- if (chatData.keys.contains(CoreMessage_TMessageKey.IMAGE_ID)) {
- row["image_id"] = chatData[CoreMessage_TMessageKey.IMAGE_ID]
- } else {
- row["image_id"] = ""
- }
- if (chatData.keys.contains(CoreMessage_TMessageKey.THUMB_ID)) {
- row["thumb_id"] = chatData[CoreMessage_TMessageKey.THUMB_ID]
- } else {
- row["thumb_id"] = ""
- }
- row["read_receipts"] = 0
- row["chat_id"] = ""
- if (chatData.keys.contains(CoreMessage_TMessageKey.FILE_ID)) {
- row["file_id"] = chatData[CoreMessage_TMessageKey.FILE_ID]
- } else {
- row["file_id"] = ""
- }
- row["progress"] = 0.0
- row["attachment_flag"] = chatData[CoreMessage_TMessageKey.ATTACHMENT_FLAG]
- row["reff_id"] = chatData[CoreMessage_TMessageKey.REF_ID] ?? ""
- row["lock"] = ""
- row["is_stared"] = "0"
- row["isSelected"] = false
- if !self.dataDates.contains("Today".localized()){
- self.dataDates.append("Today".localized())
- self.tableChatView.insertSections(IndexSet(integer: self.dataDates.count - 1), with: .fade)
- }
- row["chat_date"] = "Today".localized()
- row["blog_id"] = chatData[CoreMessage_TMessageKey.BLOG_ID]
- self.counter += 1
- self.dataMessages.append(row)
- 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)
- if self.currentIndexpath?.row == (self.dataMessages.count - 2) {
- if (self.viewIfLoaded?.window != nil) {
- 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]!)
- }
- self.tableChatView.scrollToBottom()
- 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) {
- self.counter = 0
- self.updateCounter(counter: self.counter)
- }
- let lastMarkerCounter = self.markerCounter
- if self.markerCounter != nil {
- self.markerCounter = nil
- }
- self.tableChatView.beginUpdates()
- let indexMessage = self.dataMessages.firstIndex(where: { $0["message_id"] as? String == lastMarkerCounter })
- if indexMessage != nil {
- let section = self.dataDates.firstIndex(of: self.dataMessages[indexMessage!]["chat_date"] as! String)
- let row = self.dataMessages.filter({ $0["chat_date"] as! String == self.dataMessages[indexMessage!]["chat_date"] as! String}).firstIndex(where: { $0["message_id"] as? String == self.dataMessages[indexMessage!]["message_id"] as? String })
- if row != nil && section != nil {
- self.tableChatView.reloadRows(at: [IndexPath(row: row!, section: section!)], with: .none)
- }
- }
- self.tableChatView.endUpdates()
- }
- else if self.currentIndexpath == nil {
- self.counter = 0
- self.updateCounter(counter: self.counter)
- if (self.viewIfLoaded?.window != nil) {
- 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]!)
- }
- }
- else if self.counter != 0 {
- if !self.indicatorCounterBSTB.isDescendant(of: self.view) && self.buttonScrollToBottom.isDescendant(of: self.view) {
- self.markerCounter = row["message_id"] as? String
- self.addCounterAtButttonScrollToBottom()
- self.tableChatView.beginUpdates()
- let indexMessage = self.dataMessages.firstIndex(where: { $0["message_id"] as? String == self.markerCounter })
- if indexMessage != nil {
- let section = self.dataDates.firstIndex(of: self.dataMessages[indexMessage!]["chat_date"] as! String)
- let row = self.dataMessages.filter({ $0["chat_date"] as! String == self.dataMessages[indexMessage!]["chat_date"] as! String}).firstIndex(where: { $0["message_id"] as? String == self.dataMessages[indexMessage!]["message_id"] as? String })
- if row != nil && section != nil {
- self.tableChatView.reloadRows(at: [IndexPath(row: row!, section: section!)], with: .none)
- }
- }
- self.tableChatView.endUpdates()
- } else if self.indicatorCounterBSTB.isDescendant(of: self.view) {
- self.labelCounter.text = "\(self.counter)"
- }
- }
- }
- } else {
- NotificationCenter.default.post(name: NSNotification.Name(rawValue: "reloadTabChats"), object: nil, userInfo: nil)
- }
- }
- }
-
- @objc func onStatusChat(notification: NSNotification) {
- DispatchQueue.main.async {
- let data:[AnyHashable : Any] = notification.userInfo!
- if let dataMessage = data["message"] as? TMessage {
- let idMe = UserDefaults.standard.string(forKey: "me") as String?
- let chatData = dataMessage.mBodies
- 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" {
- if (chatData.keys.contains(CoreMessage_TMessageKey.MESSAGE_ID) && !(chatData[CoreMessage_TMessageKey.MESSAGE_ID]!).contains("-2,")) {
- let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as! String == chatData[CoreMessage_TMessageKey.MESSAGE_ID]! })
- if (idx != nil) {
- if (chatData[CoreMessage_TMessageKey.DELETE_MESSAGE_FLAG] == "1") {
- self.dataMessages[idx!]["lock"] = "1"
- self.dataMessages[idx!]["reff_id"] = ""
- let section = self.dataDates.firstIndex(of: self.dataMessages[idx!]["chat_date"] as! String)
- 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 })
- if row != nil && section != nil {
- self.tableChatView.reloadRows(at: [IndexPath(row: row!, section: section!)], with: .none)
- }
- if self.reffId != nil && self.reffId == chatData[CoreMessage_TMessageKey.MESSAGE_ID]! {
- self.deleteReplyView()
- }
- } else {
- self.dataMessages[idx!]["status"] = chatData[CoreMessage_TMessageKey.STATUS]!
- let section = self.dataDates.firstIndex(of: self.dataMessages[idx!]["chat_date"] as! String)
- 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 })
- if row != nil && section != nil {
- self.tableChatView.reloadRows(at: [IndexPath(row: row!, section: section!)], with: .none)
- }
- }
- }
- }
- else if (chatData.keys.contains("message_id")) {
- let idx = self.dataMessages.firstIndex(where: { "'\($0["message_id"] as! String)'" == chatData["message_id"]! })
- if (idx != nil) {
- if (chatData[CoreMessage_TMessageKey.DELETE_MESSAGE_FLAG] == "1") {
- self.dataMessages[idx!]["lock"] = "1"
- self.dataMessages[idx!]["reff_id"] = ""
- let section = self.dataDates.firstIndex(of: self.dataMessages[idx!]["chat_date"] as! String)
- 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 })
- if row != nil && section != nil {
- self.tableChatView.reloadRows(at: [IndexPath(row: row!, section: section!)], with: .none)
- }
- if self.reffId != nil && self.reffId == chatData["message_id"]! {
- self.deleteReplyView()
- }
- } else {
- self.dataMessages[idx!]["status"] = chatData[CoreMessage_TMessageKey.STATUS]!
- let section = self.dataDates.firstIndex(of: self.dataMessages[idx!]["chat_date"] as! String)
- 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 })
- if row != nil && section != nil {
- self.tableChatView.reloadRows(at: [IndexPath(row: row!, section: section!)], with: .none)
- }
- }
- }
- }
- else {
- let messageId = chatData[CoreMessage_TMessageKey.MESSAGE_ID]!.split(separator: ",")[1]
- let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as! String == messageId })
- if (idx != nil) {
- self.dataMessages[idx!]["status"] = chatData[CoreMessage_TMessageKey.STATUS]!
- let section = self.dataDates.firstIndex(of: self.dataMessages[idx!]["chat_date"] as! String)
- 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 })
- if row != nil && section != nil {
- self.tableChatView.reloadRows(at: [IndexPath(row: row!, section: section!)], with: .none)
- }
- }
- }
- }
- }
- }
- }
-
- @objc func onMemberTopic(notification: NSNotification) {
- let data:[AnyHashable : Any] = notification.userInfo!
- DispatchQueue.main.async { [self] in
- 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) {
- dismissKeyboard()
- let labelKicked = UILabel()
- if data["member"] == nil && data["code"] as! String == CoreMessage_TMessageCode.DELETE_CHAT && data["topicId"] as! String == dataTopic["chat_id"] as! String {
- labelKicked.text = "This topic has been deleted".localized()
- } else if data["member"] != nil && data["member"] as! String == data["f_pin"] as! String {
- labelKicked.text = "You have left this group".localized()
- } else if data["member"] != nil {
- labelKicked.text = "You have been removed from this group".localized()
- } else if data["code"] as! String == CoreMessage_TMessageCode.UPDATE_CHAT {
- dataGroup.removeAll()
- dataTopic.removeAll()
- getDataGroup(unique_l_pin: unique_l_pin)
- changeAppBar()
- return
- } else {
- return
- }
- removed = true
- cancelAction()
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.35, execute: { [self] in
- navigationItem.rightBarButtonItem = nil
- view.addSubview(containerActionGroup)
- containerActionGroup.translatesAutoresizingMaskIntoConstraints = false
- NSLayoutConstraint.activate([
- containerActionGroup.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
- containerActionGroup.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
- containerActionGroup.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
- containerActionGroup.heightAnchor.constraint(equalToConstant: 120)
- ])
- containerActionGroup.backgroundColor = .secondaryColor.withAlphaComponent(0.8)
- containerActionGroup.addSubview(labelKicked)
- labelKicked.translatesAutoresizingMaskIntoConstraints = false
- NSLayoutConstraint.activate([
- labelKicked.centerYAnchor.constraint(equalTo: containerActionGroup.centerYAnchor),
- labelKicked.centerXAnchor.constraint(equalTo: containerActionGroup.centerXAnchor),
- ])
- labelKicked.textColor = .black
- labelKicked.font = UIFont.systemFont(ofSize: 12).bold
- if contactChatNav.viewIfLoaded?.window != nil {
- contactChatNav.dismiss(animated: true)
- }
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.35, execute: {
- if self.fromNotification {
- self.didTapExit()
- } else {
- self.navigationController?.popViewController(animated: true)
- }
- })
- })
- }
- }
- }
-
- @objc func onGroup(notification: NSNotification) {
- let data:[AnyHashable : Any] = notification.userInfo!
- if data["code"] as! String == "A010" && data["groupId"] as! String == self.dataGroup["group_id"] as! String {
- DispatchQueue.main.async {
- Database().database?.inTransaction({ fmdb, rollback in
- if let c = Database().getRecords(fmdb: fmdb, query: "select f_name, image_id from GROUPZ where group_id = '\(self.dataGroup["group_id"]!!)'"), c.next() {
- self.dataGroup["f_name"] = c.string(forColumnIndex: 0)!.trimmingCharacters(in: .whitespacesAndNewlines)
- self.dataGroup["image_id"] = c.string(forColumnIndex: 1)!
- c.close()
- }
- })
- self.changeAppBar()
- }
- }
- }
-
- @IBAction func voiceTapped(_ sender: UIButton) {
- if (self.constraintBottomAttachment.constant != 0.0) {
- constraintBottomAttachment.constant = 0.0
- self.viewSticker.removeConstraints(self.viewSticker.constraints)
- self.viewSticker.removeFromSuperview()
- }
- }
-
- @IBAction func imageTapped(_ sender: UIButton) {
- if (self.constraintBottomAttachment.constant != 0.0) {
- constraintBottomAttachment.constant = 0.0
- self.viewSticker.removeConstraints(self.viewSticker.constraints)
- self.viewSticker.removeFromSuperview()
- }
- let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
-
- if let action = self.actionImageVideo(for: "image", title: "Choose Photo".localized()) {
- alertController.addAction(action)
- }
- if let action = self.actionImageVideo(for: "video", title: "Choose Video".localized()) {
- alertController.addAction(action)
- }
- alertController.addAction(UIAlertAction(title: "Cancel".localized(), style: .cancel, handler: nil))
- self.present(alertController, animated: true)
- }
-
- private func actionImageVideo(for type: String, title: String) -> UIAlertAction? {
- return UIAlertAction(title: title, style: .default) { [unowned self] _ in
- switch type {
- case "image":
- imageVideoPicker.present(source: .imageAlbum)
- case "video":
- imageVideoPicker.present(source: .videoAlbum)
- case "imageCamera":
- imageVideoPicker.present(source: .imageCamera)
- case "videoCamera":
- imageVideoPicker.present(source: .videoCamera)
- default:
- imageVideoPicker.present(source: .imageAlbum)
- }
- }
- }
-
- @IBAction func photoTapped(_ sender: UIButton) {
- if (self.constraintBottomAttachment.constant != 0.0) {
- constraintBottomAttachment.constant = 0.0
- self.viewSticker.removeConstraints(self.viewSticker.constraints)
- self.viewSticker.removeFromSuperview()
- }
- let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
-
- if let action = self.actionImageVideo(for: "imageCamera", title: "Take Photo".localized()) {
- alertController.addAction(action)
- }
- if let action = self.actionImageVideo(for: "videoCamera", title: "Take Video".localized()) {
- alertController.addAction(action)
- }
- alertController.addAction(UIAlertAction(title: "Cancel".localized(), style: .cancel, handler: nil))
- self.present(alertController, animated: true)
- }
-
- @IBAction func stickerTapped(_ sender: UIButton) {
- DispatchQueue.main.async {
- if (self.constraintBottomAttachment.constant == 0.0) {
- self.constraintBottomAttachment.constant = 200.0
- self.view.addSubview(self.viewSticker)
- self.viewSticker.translatesAutoresizingMaskIntoConstraints = false
- NSLayoutConstraint.activate([
- self.viewSticker.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
- self.viewSticker.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
- self.viewSticker.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
- self.viewSticker.heightAnchor.constraint(equalToConstant: 200)
- ])
-
- let layout = UICollectionViewFlowLayout()
- layout.scrollDirection = .vertical
- let collectionSticker = UICollectionView(frame: .zero, collectionViewLayout: layout)
- collectionSticker.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cellSticker")
- collectionSticker.delegate = self
- collectionSticker.dataSource = self
- collectionSticker.backgroundColor = .clear
- self.viewSticker.addSubview(collectionSticker)
- collectionSticker.translatesAutoresizingMaskIntoConstraints = false
- NSLayoutConstraint.activate([
- collectionSticker.topAnchor.constraint(equalTo: self.viewSticker.topAnchor, constant: 20),
- collectionSticker.bottomAnchor.constraint(equalTo: self.viewSticker.bottomAnchor, constant: -20),
- collectionSticker.leadingAnchor.constraint(equalTo: self.viewSticker.leadingAnchor, constant: 20),
- collectionSticker.trailingAnchor.constraint(equalTo: self.viewSticker.trailingAnchor, constant: -20)
- ])
- if (self.currentIndexpath != nil) {
- DispatchQueue.main.async {
- self.tableChatView.scrollToRow(at: IndexPath(row: self.currentIndexpath!.row, section: self.currentIndexpath!.section), at: .none, animated: false)
- }
- } else {
- self.tableChatView.scrollToBottom()
- }
- } else {
- self.constraintBottomAttachment.constant = 0.0
- self.viewSticker.removeConstraints(self.viewSticker.constraints)
- self.viewSticker.removeFromSuperview()
- }
- }
- }
-
- @IBAction func fileTapped(_ sender: UIButton) {
- if (self.constraintBottomAttachment.constant != 0.0) {
- constraintBottomAttachment.constant = 0.0
- self.viewSticker.removeConstraints(self.viewSticker.constraints)
- self.viewSticker.removeFromSuperview()
- }
- documentPicker.present()
- }
-
- @objc func didTapExit() {
- UserDefaults.standard.removeObject(forKey: "inEditorGroup")
- NotificationCenter.default.removeObserver(self)
- NotificationCenter.default.post(name: NSNotification.Name(rawValue: "refreshView"), object: nil, userInfo: nil)
- self.dismiss(animated: true, completion: nil)
- }
-
- @objc func profilePersonTapped(_ sender: ObjectGesture) {
- if isHistoryCC {
- return
- }
- let idMe = UserDefaults.standard.string(forKey: "me") as String?
- if sender.message_id == idMe {
- let controller = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "profileView") as! ProfileViewController
- controller.data = sender.message_id
- controller.flag = .me
- navigationController?.show(controller, sender: nil)
- } else {
- let data = User.getDataCanNil(pin: sender.message_id)
- if data != nil {
- let controller = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "profileView") as! ProfileViewController
- controller.flag = .friend
- controller.user = data
- controller.name = data!.fullName
- controller.data = sender.message_id
- controller.picture = data!.thumb
- self.navigationController?.show(controller, sender: nil)
- } else {
- let dataUser = getDataProfile(f_pin: sender.message_id, message_id: "")
- let controller = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "profileView") as! ProfileViewController
- controller.flag = .invite
- controller.user = nil
- controller.name = dataUser["name"]!
- controller.data = sender.message_id
- controller.picture = dataUser["image_id"]!
- self.navigationController?.show(controller, sender: nil)
- }
- }
- }
-
- @objc func seeProfileTapped() {
- if isHistoryCC || removed || copySession || forwardSession || deleteSession || (dataGroup["official"] as? String == "1" && (dataGroup["parent"] as? String)!.isEmpty) {
- return
- }
- dismissKeyboard()
- let controller = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "groupDetailView") as! GroupDetailViewController
- controller.data = dataGroup["group_id"] as! String
- controller.checkReadMessage = {
- if self.currentIndexpath == nil {
- var listData = self.dataMessages
- listData = listData.filter({$0["status"] as! String != "4" && $0["status"] as! String != "8"})
- if listData.count != 0 {
- let idMe = UserDefaults.standard.string(forKey: "me") as String?
- for i in 0...listData.count - 1 {
- if listData[i]["f_pin"] as? String != idMe {
- 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)
- }
- }
- }
- } else {
- let dataMessages = self.dataMessages.filter({ $0["chat_date"] as! String == self.dataDates[self.currentIndexpath!.section] })
- var listData = dataMessages
- listData = listData.filter({$0["status"] as! String != "4" && $0["status"] as! String != "8"})
- if listData.count != 0 {
- let idMe = UserDefaults.standard.string(forKey: "me") as String?
- for i in 0...listData.count - 1 {
- if listData[i]["f_pin"] as? String != idMe {
- 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)
- }
- }
- }
- }
- }
- navigationController?.show(controller, sender: nil)
- }
-
- @objc func dismissKeyboard() {
- if isSearching {
- searchBar.resignFirstResponder()
- } else {
- textFieldSend.resignFirstResponder() // dismiss keyoard
- if (self.constraintBottomAttachment.constant != 0.0) {
- constraintBottomAttachment.constant = 0.0
- self.viewSticker.removeConstraints(self.viewSticker.constraints)
- self.viewSticker.removeFromSuperview()
- }
- }
- }
-
- @objc func keyboardWillShow(notification: NSNotification) {
- if self.viewIfLoaded?.window != nil {
- if (self.constraintBottomAttachment.constant != 0.0) {
- self.constraintBottomAttachment.constant = 0.0
- self.viewSticker.removeConstraints(self.viewSticker.constraints)
- self.viewSticker.removeFromSuperview()
- }
- let info:NSDictionary = notification.userInfo! as NSDictionary
- let keyboardSize = (info[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
-
- let keyboardHeight: CGFloat = keyboardSize.height
-
- let duration: CGFloat = info[UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber as! CGFloat
-
- if self.constraintViewTextField.constant != keyboardHeight - 60 {
- if self.contraintBottomMention.constant > 0 {
- self.contraintBottomMention.constant = self.contraintBottomMention.constant + keyboardHeight - 60
- }
- self.constraintViewTextField.constant = keyboardHeight - 60
- self.keyboardHeightForMention = keyboardHeight
- if isSearching {
- self.constraintViewTextField.constant = self.constraintViewTextField.constant + 60
- self.constraintBottomContainerMultpileSelectSession.constant = -keyboardHeight
- }
- UIView.animate(withDuration: TimeInterval(duration), animations: {
- self.view.layoutIfNeeded()
- })
- if isSearching {
- self.tableChatView.scrollToBottom()
- } else {
- if (self.currentIndexpath != nil) {
- self.tableChatView.scrollToRow(at: IndexPath(row: self.currentIndexpath!.row, section: self.currentIndexpath!.section), at: .none, animated: false)
- } else {
- self.tableChatView.scrollToBottom()
- }
- }
- }
- }
- }
-
- @objc func keyboardWillHide(notification: NSNotification) {
- if self.viewIfLoaded?.window != nil {
- let info:NSDictionary = notification.userInfo! as NSDictionary
- let duration: CGFloat = info[UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber as! CGFloat
-
- self.constraintViewTextField.constant = 0
- self.constraintBottomContainerMultpileSelectSession.constant = 0
- if self.contraintBottomMention.constant > 0 {
- self.contraintBottomMention.constant = self.contraintBottomMention.constant - self.keyboardHeightForMention! + 60
- }
- keyboardHeightForMention = nil
- UIView.animate(withDuration: TimeInterval(duration), animations: {
- self.view.layoutIfNeeded()
- })
- }
- }
-
- @objc func showChooserACKConfidential() {
- let alertController = UIAlertController(title: "Message Mode".localized(), message: "Select".localized() + " " + "Message Mode".localized(), preferredStyle: .actionSheet)
- let imageAck = resizeImage(image: UIImage(named: "ack_icon", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!, targetSize: CGSize(width: 30, height: 30)).withRenderingMode(.alwaysOriginal)
- let ackAction = UIAlertAction(title: "Confirmation Message".localized(), style: .default, handler: { (UIAlertAction) in
- if !self.isAck {
- self.isAck = true
- self.buttonAckConfidential.setImage(imageAck, for: .normal)
- }
- })
- ackAction.setValue(imageAck, forKey: "image")
- alertController.addAction(ackAction)
- alertController.addAction(UIAlertAction(title: "Cancel".localized(), style: .cancel, handler: { (UIAlertAction) in
- self.isAck = false
- self.buttonAckConfidential.setImage(UIImage(systemName: "gearshape.fill", withConfiguration: UIImage.SymbolConfiguration(scale: .large))?.withTintColor(.white).withRenderingMode(.alwaysTemplate), for: .normal)
- }))
- self.present(alertController, animated: true, completion: nil)
- }
-
- public func setAckConfidential(isAck: Bool, isConfidential: Bool) {
- self.isAck = isAck
- let imageAck = resizeImage(image: UIImage(named: "ack_icon", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!, targetSize: CGSize(width: 30, height: 30)).withRenderingMode(.alwaysOriginal)
- if isAck {
- buttonAckConfidential.setImage(imageAck, for: .normal)
- } else {
- self.buttonAckConfidential.setImage(UIImage(systemName: "gearshape.fill", withConfiguration: UIImage.SymbolConfiguration(scale: .large))?.withTintColor(.white).withRenderingMode(.alwaysTemplate), for: .normal)
- }
- }
-
- @objc func sendTapped() {
- sendChat(message_text: textFieldSend.text!, viewController: self)
- }
-
- 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) {
- if viewController is EditorGroup && file_id == "" && dataMessageForward == nil {
- if ((textFieldSend.text!.trimmingCharacters(in: .whitespacesAndNewlines) == "Send message".localized() && textFieldSend.textColor == UIColor.lightGray && attachment_flag != "11") || textFieldSend.text!.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ) {
- dismissKeyboard()
- viewController.showToast(message: "Write Messages".localized(), font: UIFont.systemFont(ofSize: 12, weight: .medium), controller: self)
- if (textFieldSend.text!.trimmingCharacters(in: .whitespacesAndNewlines) != "Send message".localized()) {
- textFieldSend.text = ""
- }
- if (self.heightTextFieldSend.constant != 40) {
- self.heightTextFieldSend.constant = 40
- }
- return
- }
- }
- var reff_id = reff_id
- if (reffId != nil) {
- reff_id = reffId!
- }
- var message_text = message_text.trimmingCharacters(in: .whitespacesAndNewlines)
- let idMe = UserDefaults.standard.string(forKey: "me") as String?
- var opposite_pin = self.dataGroup["group_id"] as! String
- if (self.dataTopic["chat_id"] as! String != "") {
- opposite_pin = self.dataTopic["chat_id"] as! String
- }
- var read_receipts = read_receipts
- if isAck {
- read_receipts = "8"
- }
- if message_text.contains("@") && listMentionInTextField.count > 0 {
- for i in 0..<listMentionInTextField.count {
- let nameWithMention = ("@" + listMentionInTextField[i].firstName + " " + listMentionInTextField[i].lastName).trimmingCharacters(in: .whitespaces)
- let upperBound = Int(listMentionInTextField[i].ex_block!)! - 1
- let lowerBound = Int(listMentionInTextField[i].ex_block!)! - nameWithMention.count
- var afterMention = ""
- if upperBound + 1 != message_text.count && message_text.substring(from: upperBound + 1, to: upperBound + 1) != "\n" && message_text.substring(from: upperBound + 1, to: upperBound + 1) != " " && message_text.substring(from: upperBound + 1, to: upperBound + 1) != "" {
- afterMention = " "
- }
- let stringRange = message_text.index(message_text.startIndex, offsetBy: lowerBound)..<message_text.index(message_text.startIndex, offsetBy: upperBound + 1)
- message_text = message_text.replacingOccurrences(of: nameWithMention, with: "@\(listMentionInTextField[i].pin)" + afterMention, range: stringRange)
- }
- }
- 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)
- Nexilis.addQueueMessage(message: message)
- let messageId = String(message.mBodies[CoreMessage_TMessageKey.MESSAGE_ID]!)
- var row: [String: Any?] = [:]
- row["message_id"] = messageId
- row["f_pin"] = idMe
- row["l_pin"] = dataGroup["group_id"]!!
- row["message_scope_id"] = message_scope_id
- row["server_date"] = "\(Date().currentTimeMillis())"
- row["status"] = status
- row["message_text"] = message_text
- row["audio_id"] = audio_id
- row["video_id"] = video_id
- row["image_id"] = image_id
- row["thumb_id"] = thumb_id
- row["read_receipts"] = read_receipts
- row["chat_id"] = dataTopic["chat_id"]!!
- row["file_id"] = file_id
- row["attachment_flag"] = attachment_flag
- row["reff_id"] = reff_id
- row["progress"] = 0.0
- row["lock"] = "0"
- row["is_stared"] = "0"
- row["isSelected"] = false
- if !dataDates.contains("Today".localized()){
- dataDates.append("Today".localized())
- tableChatView.insertSections(IndexSet(integer: dataDates.count - 1), with: .fade)
- }
- row["chat_date"] = "Today".localized()
- dataMessages.append(row)
- tableChatView.insertRows(at: [IndexPath(row: dataMessages.filter({ $0["chat_date"] as! String == dataDates[dataDates.count - 1]}).count - 1, section: dataDates.count - 1)], with: .fade)
- if textFieldSend.text!.trimmingCharacters(in: .whitespacesAndNewlines) != "Send message".localized() && textFieldSend.textColor != UIColor.lightGray && constraintViewTextField.constant == 0 {
- textFieldSend.text = "Send message".localized()
- textFieldSend.textColor = UIColor.lightGray
- } else if constraintViewTextField.constant != 0 {
- textFieldSend.text = ""
- heightTextFieldSend.constant = 40
- }
- deleteReplyView()
- deleteLinkPreview()
- listMentionInTextField.removeAll()
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
- self.tableChatView.scrollToBottom()
- if self.markerCounter != nil {
- let lastMarkerCounter = self.markerCounter
- self.markerCounter = nil
- self.tableChatView.beginUpdates()
- let indexMessage = self.dataMessages.firstIndex(where: { $0["message_id"] as? String == lastMarkerCounter })
- if indexMessage != nil {
- let section = self.dataDates.firstIndex(of: self.dataMessages[indexMessage!]["chat_date"] as! String)
- let row = self.dataMessages.filter({ $0["chat_date"] as! String == self.dataMessages[indexMessage!]["chat_date"] as! String}).firstIndex(where: { $0["message_id"] as? String == self.dataMessages[indexMessage!]["message_id"] as? String })
- if row != nil && section != nil {
- self.tableChatView.reloadRows(at: [IndexPath(row: row!, section: section!)], with: .none)
- }
- }
- self.tableChatView.endUpdates()
- }
- }
- }
-
- private func getCounter() {
- Database().database?.inTransaction({ fmdb, rollback in
- var l_pin = self.dataGroup["group_id"]!!
- if (self.dataTopic["chat_id"] as! String != "") {
- l_pin = self.dataTopic["chat_id"] as! String
- }
-
- if let c = Database().getRecords(fmdb: fmdb, query: "SELECT counter FROM MESSAGE_SUMMARY where l_pin='\(l_pin)'"), c.next() {
- counter = Int(c.int(forColumnIndex: 0))
- c.close()
- }
- })
- }
-
- private func updateCounter(counter: Int) {
- DispatchQueue.global().async {
- Database.shared.database?.inTransaction({ (fmdb, rollback) in
- var l_pin = self.dataGroup["group_id"]!!
- if (self.dataTopic["chat_id"] as! String != "") {
- l_pin = self.dataTopic["chat_id"] as! String
- }
- _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE_SUMMARY", cvalues: [
- "counter" : "\(counter)"
- ], _where: "l_pin = '\(l_pin)'")
- })
- NotificationCenter.default.post(name: NSNotification.Name(rawValue: "reloadTabChats"), object: nil, userInfo: nil)
- }
-
- }
-
- private func disableEditor() {
- view.addSubview(containerAction)
- containerAction.translatesAutoresizingMaskIntoConstraints = false
- NSLayoutConstraint.activate([
- containerAction.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
- containerAction.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
- containerAction.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
- containerAction.heightAnchor.constraint(equalToConstant: 120)
- ])
- containerAction.backgroundColor = .secondaryColor.withAlphaComponent(0.8)
- let labelDisable = UILabel()
- containerAction.addSubview(labelDisable)
- labelDisable.translatesAutoresizingMaskIntoConstraints = false
- NSLayoutConstraint.activate([
- labelDisable.centerYAnchor.constraint(equalTo: containerAction.centerYAnchor),
- labelDisable.centerXAnchor.constraint(equalTo: containerAction.centerXAnchor),
- ])
- labelDisable.textColor = .black
- labelDisable.font = UIFont.systemFont(ofSize: 12).bold
- labelDisable.text = "Call Center Session has ended".localized()
- }
-
- private func addButtonScrollToBottom() {
- self.view.addSubview(buttonScrollToBottom)
- buttonScrollToBottom.translatesAutoresizingMaskIntoConstraints = false
- NSLayoutConstraint.activate([
- buttonScrollToBottom.bottomAnchor.constraint(equalTo: buttonSendChat.topAnchor, constant: -50),
- buttonScrollToBottom.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
- buttonScrollToBottom.widthAnchor.constraint(equalToConstant: 60),
- buttonScrollToBottom.heightAnchor.constraint(equalToConstant: 30.0)
- ])
- buttonScrollToBottom.backgroundColor = .greenColor
- buttonScrollToBottom.setImage(UIImage(systemName: "chevron.down.circle"), for: .normal)
- buttonScrollToBottom.imageView?.contentMode = .scaleAspectFit
- buttonScrollToBottom.imageView?.tintColor = .white
- buttonScrollToBottom.contentVerticalAlignment = .fill
- buttonScrollToBottom.contentHorizontalAlignment = .fill
- buttonScrollToBottom.imageEdgeInsets.top = 2.0
- buttonScrollToBottom.imageEdgeInsets.bottom = 2.0
- buttonScrollToBottom.layer.cornerRadius = 10.0
- buttonScrollToBottom.layer.maskedCorners = [.layerMinXMinYCorner, .layerMinXMaxYCorner]
- buttonScrollToBottom.clipsToBounds = true
- buttonScrollToBottom.addTarget(self, action: #selector(scrollTobottomAction), for: .touchUpInside)
- }
-
- private func addCounterAtButttonScrollToBottom() {
- self.view.addSubview(indicatorCounterBSTB)
- indicatorCounterBSTB.translatesAutoresizingMaskIntoConstraints = false
- indicatorCounterBSTB.backgroundColor = .systemRed
- indicatorCounterBSTB.layer.cornerRadius = 7.5
- indicatorCounterBSTB.clipsToBounds = true
- indicatorCounterBSTB.layer.borderWidth = 0.5
- indicatorCounterBSTB.layer.borderColor = UIColor.secondaryColor.cgColor
- NSLayoutConstraint.activate([
- indicatorCounterBSTB.bottomAnchor.constraint(equalTo: buttonScrollToBottom.topAnchor, constant: 5),
- indicatorCounterBSTB.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -50),
- indicatorCounterBSTB.widthAnchor.constraint(greaterThanOrEqualToConstant: 15),
- indicatorCounterBSTB.heightAnchor.constraint(equalToConstant: 15)
- ])
-
- indicatorCounterBSTB.addSubview(labelCounter)
- labelCounter.translatesAutoresizingMaskIntoConstraints = false
- NSLayoutConstraint.activate([
- labelCounter.leadingAnchor.constraint(equalTo: indicatorCounterBSTB.leadingAnchor, constant: 2),
- labelCounter.trailingAnchor.constraint(equalTo: indicatorCounterBSTB.trailingAnchor, constant: -2),
- labelCounter.centerXAnchor.constraint(equalTo: indicatorCounterBSTB.centerXAnchor),
- ])
- labelCounter.font = UIFont.systemFont(ofSize: 11)
- labelCounter.text = "\(counter)"
- labelCounter.textColor = .secondaryColor
- labelCounter.textAlignment = .center
- }
-
- @objc func scrollTobottomAction() {
- tableChatView.scrollToBottom()
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) { [self] in
- if buttonScrollToBottom.isDescendant(of: self.view) {
- buttonScrollToBottom.removeConstraints(buttonScrollToBottom.constraints)
- buttonScrollToBottom.removeFromSuperview()
- if indicatorCounterBSTB.isDescendant(of: self.view) {
- indicatorCounterBSTB.removeConstraints(indicatorCounterBSTB.constraints)
- indicatorCounterBSTB.removeFromSuperview()
- }
- }
- }
- }
-
- private func sendReadMessageStatus(chat_id: String, f_pin: String, message_scope_id: String, message_id: String) {
- let message = CoreMessage_TMessageBank.getUpdateRead(p_chat_id: chat_id, p_f_pin: f_pin, p_scope_id: message_scope_id, qty: 1)
- let fPin = message.getBody(key: CoreMessage_TMessageKey.F_PIN)
- let scope = message.getBody(key: CoreMessage_TMessageKey.SCOPE_ID)
- message.mBodies[CoreMessage_TMessageKey.SERVER_DATE] = String(Date().currentTimeMillis())
- if (fPin.elementsEqual("-999") || scope.elementsEqual("16") || scope.elementsEqual("15")){
- return
- }
- DispatchQueue.global().async {
- Database.shared.database?.inTransaction({ (fmdb, rollback) in
- _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE", cvalues: [
- "status" : "4"
- ], _where: "message_id = '\(message_id)'")
- })
- message.mStatus = CoreMessage_TMessageUtil.getTID()
- message.mBodies[CoreMessage_TMessageKey.L_PIN] = f_pin
- message.mBodies[CoreMessage_TMessageKey.MESSAGE_ID] = "-2,\(message_id)"
- _ = Nexilis.write(message: message)
- }
- if let index = dataMessages.firstIndex(where: {$0["message_id"] as? String == message_id}) {
- dataMessages[index]["status"] = "4"
- let auto = UserDefaults.standard.bool(forKey: "autoDownload")
- if auto {
- if dataMessages[index]["image_id"] as? String != nil && !((dataMessages[index]["image_id"] as? String)!.isEmpty) {
- Download().start(forKey:dataMessages[index]["image_id"] as! String) { (name, progress) in
- guard progress == 100 else {
- return
- }
- let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
- let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
- let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
- if let dirPath = paths.first {
- let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(self.dataMessages[index]["image_id"] as! String)
- let image = UIImage(contentsOfFile: imageURL.path)
- let save = UserDefaults.standard.bool(forKey: "saveToGallery")
- if save {
- UIImageWriteToSavedPhotosAlbum(image!, nil, nil, nil)
- }
- }
- DispatchQueue.main.async { [self] in
- let section = self.dataDates.firstIndex(of: dataMessages[index]["chat_date"] as! String)
- 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})
- if row != nil && section != nil{
- tableChatView.reloadRows(at: [IndexPath(row: row!, section: section!)], with: .automatic)
- }
- }
- }
- } else if dataMessages[index]["video_id"] as? String != nil && !((dataMessages[index]["video_id"] as? String)!.isEmpty){
- let section = dataDates.firstIndex(of: dataMessages[index]["chat_date"] as! String)
- let row = dataMessages.filter({$0["chat_date"] as! String == dataMessages[index]["chat_date"] as! String}).firstIndex(where: { $0["message_id"] as? String == message_id})
- if row != nil && section != nil{
- let indexPath = IndexPath(row: row!, section: section!)
- if let cell = tableChatView.cellForRow(at: indexPath) {
- for view in cell.contentView.subviews {
- if view is UIImageView {
- let objectTap = ObjectGesture()
- objectTap.video_id = dataMessages[index]["video_id"] as! String
- objectTap.imageView = view as! UIImageView
- objectTap.indexPath = indexPath
- contentMessageTapped(objectTap)
- break
- }
- }
- }
- }
- }
- }
- }
- }
-
- private func sendTyping(l_pin: String, isTyping: Bool = false) {
- DispatchQueue.global().async {
- let tmessage = CoreMessage_TMessageBank.getUpdateTypingStatus(p_opposite: l_pin, p_scope: "4", p_status: isTyping ? "3": "4")
- _ = Nexilis.write(message: tmessage)
- }
- }
-
- private func checkNewMessage(tableView: UITableView) {
- currentIndexpath = tableView.indexPathsForVisibleRows?.last
- if currentIndexpath != nil {
- let dataMessages = dataMessages.filter({ $0["chat_date"] as! String == dataDates[currentIndexpath!.section] })
- if dataMessages.count == 0 {
- return
- }
- if currentIndexpath!.section == dataDates.count - 1 && currentIndexpath!.row != dataMessages.count - 1 && currentIndexpath!.row != dataMessages.count - 2 && !buttonScrollToBottom.isDescendant(of: self.view) {
- addButtonScrollToBottom()
- addCounterAtButttonScrollToBottom()
- } else if currentIndexpath!.section == dataDates.count - 1 && currentIndexpath!.row == dataMessages.count - 1 {
- if buttonScrollToBottom.isDescendant(of: self.view) {
- buttonScrollToBottom.removeConstraints(buttonScrollToBottom.constraints)
- buttonScrollToBottom.removeFromSuperview()
- if indicatorCounterBSTB.isDescendant(of: self.view) {
- indicatorCounterBSTB.removeConstraints(indicatorCounterBSTB.constraints)
- indicatorCounterBSTB.removeFromSuperview()
- }
- }
- }
- let indexPathFirst = tableChatView.indexPathsForVisibleRows?.first
- if indexPathFirst != nil && listViewOnSection.count != 0 && listViewOnSection.count - 1 <= indexPathFirst!.section{
- let headerView = listViewOnSection[indexPathFirst!.section]
- if headerView.isHidden {
- headerView.isHidden = false
- }
- }
- if dataMessages.count - 1 < currentIndexpath!.row {
- return
- }
- var listData = dataMessages[0...currentIndexpath!.row]
- listData = listData.filter({$0["status"] as! String != "4" && $0["status"] as! String != "8"})
- if listData.count != 0 {
- let idMe = UserDefaults.standard.string(forKey: "me") as String?
- for i in 0...listData.count - 1 {
- if listData[i]["f_pin"] as? String != idMe {
- 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)
- }
- }
- }
- }
- if counter == 0 && indicatorCounterBSTB.isDescendant(of: self.view) {
- indicatorCounterBSTB.removeConstraints(indicatorCounterBSTB.constraints)
- indicatorCounterBSTB.removeFromSuperview()
- } else if counter != 0 && currentIndexpath != nil {
- let dataFilter = dataMessages.filter({ $0["chat_date"] as! String == dataDates[currentIndexpath!.section] })
- if dataFilter.count == 0 {
- return
- }
- let idx = dataMessages.firstIndex(where: { $0["message_id"] as! String == dataFilter[currentIndexpath!.row]["message_id"] as! String})
- if idx == nil {
- return
- }
- if (dataMessages.count - counter) <= idx! {
- let countUpdate = idx! - (dataMessages.count - counter)
- counter = counter - (countUpdate + 1)
- if indicatorCounterBSTB.isDescendant(of: self.view) {
- labelCounter.text = "\(counter)"
- }
- updateCounter(counter: counter)
- }
- }
- }
- }
- extension EditorGroup: ImageVideoPickerDelegate, PreviewAttachmentImageVideoDelegate {
- public func didSelect(imagevideo: Any?) {
- if (imagevideo != nil) {
- let imageVideoData = imagevideo as! [UIImagePickerController.InfoKey: Any]
- let previewImageVC = PreviewAttachmentImageVideo(nibName: "PreviewAttachmentImageVideo", bundle: Bundle.resourceBundle(for: Nexilis.self))
- previewImageVC.imageVideoData = imageVideoData
- if (textFieldSend.textColor != .lightGray) {
- previewImageVC.currentTextTextField = textFieldSend.text
- }
- previewImageVC.modalPresentationStyle = .custom
- previewImageVC.delegate = self
- previewImageVC.isGroup = true
- previewImageVC.isAck = self.isAck
- self.present(previewImageVC, animated: true, completion: nil)
- }
- }
-
- func sendChatFromPreviewImage(message_text: String, attachment_flag: String, image_id: String, video_id: String, thumb_id: String, viewController: UIViewController) {
- sendChat(message_text: message_text, attachment_flag: attachment_flag, image_id: image_id, video_id: video_id, thumb_id: thumb_id, viewController: viewController)
- }
- }
- extension EditorGroup: UIDocumentPickerDelegate, DocumentPickerDelegate, QLPreviewControllerDataSource {
- public func didSelectDocument(document: Any?) {
- if (document != nil) {
- self.previewItem = (document as! [URL])[0] as NSURL
- let previewController = QLPreviewController()
- let navController = UINavigationController(rootViewController: previewController)
- let leftBarButton = navigationQLPreviewDocument(title: "Cancel".localized(), style: .plain, target: self, action: #selector(cancelDocumentPreview))
- let rightBarButton = navigationQLPreviewDocument(title: "Send".localized(), style: .done, target: self, action: #selector(sendDocument))
- // leftBarButton.tintColor = .white
- // rightBarButton.tintColor = .white
- leftBarButton.navigation = navController
- rightBarButton.navigation = navController
- // navController.navigationBar.barTintColor = .mainColor
- navController.navigationBar.isTranslucent = false
- previewController.navigationItem.leftBarButtonItem = leftBarButton
- previewController.navigationItem.rightBarButtonItem = rightBarButton
- previewController.dataSource = self
- previewController.modalPresentationStyle = .pageSheet
-
- self.present(navController, animated: true, completion: nil)
- }
- }
-
- @objc private func cancelDocumentPreview(sender: navigationQLPreviewDocument) {
- sender.navigation.dismiss(animated: true, completion: nil)
- }
-
- @objc private func sendDocument(sender: navigationQLPreviewDocument) {
- sender.navigation.dismiss(animated: true, completion: nil)
- do {
- let dataFile = try Data(contentsOf: self.previewItem! as URL)
- let urlFile = self.previewItem?.absoluteString
- var originaFileName = (urlFile! as NSString).lastPathComponent
- originaFileName = NSString(string: originaFileName).removingPercentEncoding!
- let renamedNameFile = "Qmera_doc_" + "\(Date().currentTimeMillis())_" + originaFileName
- let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
- let fileURL = documentsDirectory.appendingPathComponent(renamedNameFile)
- if !FileManager.default.fileExists(atPath: fileURL.path) {
- do {
- try dataFile.write(to: fileURL)
- //print(("file saved")
- } catch {
- //print(("error saving file:", error)
- }
- }
- sendChat(message_text: "\(originaFileName)|", attachment_flag: "6", file_id: renamedNameFile, viewController: self)
- } catch {
-
- }
- }
- }
- extension EditorGroup: UITextViewDelegate {
- public func textViewDidChangeSelection(_ textView: UITextView) {
- lastPositionCursorMention = textView.selectedRange.location
- let fulltextForMention = textView.text.substring(from: 0, to: lastPositionCursorMention - 1)
- var isShowMention = false
- if lastPositionCursorMention > 0 {
- var listHaveToRemoved: [User] = []
- var continueCheckMention = true
- if listMentionInTextField.count > 0 {
- for i in 0..<listMentionInTextField.count {
- if listMentionInTextField[i].ex_block != nil && !listMentionInTextField[i].ex_block!.isEmpty {
- let nameWithMention = ("@" + listMentionInTextField[i].firstName + " " + listMentionInTextField[i].lastName).trimmingCharacters(in: .whitespaces)
- var rangeLower = Int(listMentionInTextField[i].ex_block!)! - nameWithMention.count
- var rangeUpper = Int(listMentionInTextField[i].ex_block!)!
- if textView.text.substring(from: rangeLower, to: rangeUpper - 1) == nameWithMention {
- if lastPositionCursorMention >= rangeLower + 1 && lastPositionCursorMention <= rangeUpper {
- continueCheckMention = false
- }
- } else {
- if listMentionInTextField[i].ex_offmp!.isEmpty {
- rangeLower = rangeLower + listMentionWithText.count
- rangeUpper = rangeUpper + listMentionWithText.count
- } else {
- rangeLower = rangeLower + (listMentionWithText.count - Int(listMentionInTextField[i].ex_offmp!)!)
- rangeUpper = rangeUpper + (listMentionWithText.count - Int(listMentionInTextField[i].ex_offmp!)!)
- }
- if textView.text.substring(from: rangeLower, to: rangeUpper - 1) == nameWithMention {
- if lastPositionCursorMention >= rangeLower + 1 && lastPositionCursorMention <= rangeUpper {
- continueCheckMention = false
- }
- listMentionInTextField[i].ex_block! = "\(rangeUpper)"
- listMentionInTextField[i].ex_offmp! = "\(textView.text.count)"
- } else {
- listHaveToRemoved.append(listMentionInTextField[i])
- }
- }
- }
- }
- }
- listMentionInTextField.removeAll(where: { listHaveToRemoved.contains($0) })
- if continueCheckMention {
- let splitBreak = fulltextForMention.components(separatedBy: "\n")
- let indexLastBreak = splitBreak.lastIndex(where: { $0.contains("@") })
- if indexLastBreak != nil {
- let splitSpace = splitBreak[indexLastBreak!].components(separatedBy: " ")
- let indexLastMention = splitSpace.lastIndex(where: { $0.substring(from: 0, to: 0) == "@" })
- if indexLastMention != nil && fulltextForMention.substring(from: lastPositionCursorMention - 1, to: lastPositionCursorMention - 1) != " " && fulltextForMention.substring(from: lastPositionCursorMention - 1, to: lastPositionCursorMention - 1) != "\n" {
- let fullTextMention = splitSpace[indexLastMention!]
- showMention(text: fullTextMention.substring(from: 1, to: fullTextMention.count))
- isShowMention = true
- }
- }
- }
- }
- if !isShowMention {
- hideMention()
- }
- let cursorPosition = textView.caretRect(for: self.textFieldSend.selectedTextRange!.start).origin
- let currentLine = Int(cursorPosition.y / self.textFieldSend.font!.lineHeight)
- UIView.animate(withDuration: 0.3) {
- let numberOfLines = textView.textContainer.lineBreakMode == .byWordWrapping ? Int(textView.contentSize.height / textView.font!.lineHeight) - 1 : 1
- if currentLine == 0 && numberOfLines == 1 {
- self.heightTextFieldSend.constant = 40
- } else if self.heightTextFieldSend.constant < 95.0 && currentLine >= 4 {
- self.heightTextFieldSend.constant = 95.0
- } else if currentLine < 4 && numberOfLines < 5 {
- if (self.textFieldSend.text.count > 0 && self.heightTextFieldSend.constant != self.textFieldSend.contentSize.height) {
- self.heightTextFieldSend.constant = self.textFieldSend.contentSize.height
- }
- }
- }
- }
-
- public func textViewDidChange(_ textView: UITextView) {
- if textView.text.count == 0 {
- isAlwaysHideLinkPreview = false
- }
- if allowTyping {
- allowTyping = false
- if dataTopic["chat_id"] as! String == "" {
- UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [dataGroup["group_id"] as! String])
- sendTyping(l_pin: dataGroup["group_id"] as! String)
- } else {
- UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [dataTopic["chat_id"] as! String])
- sendTyping(l_pin: dataTopic["chat_id"] as! String)
- }
- DispatchQueue.main.asyncAfter(deadline: .now() + 4, execute: {
- self.allowTyping = true
- })
- }
- timerCheckLink?.invalidate()
- timerCheckLink = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false, block: {_ in
- self.checkLink(fullText: textView.text)
- })
-
- if listMentionInTextField.count > 0 {
- for j in 0..<listMentionInTextField.count {
- let name = (listMentionInTextField[j].firstName + " " + listMentionInTextField[j].lastName).trimmingCharacters(in: .whitespaces)
- if !textView.text.contains("@\(name)") {
- listMentionInTextField.remove(at: j)
- }
- }
- }
-
- if textView.text.contains("*") || textView.text.contains("_") || textView.text.contains("^") || textView.text.contains("~") || textView.text.contains("@") {
- textView.preserveCursorPosition(withChanges: { _ in
- textView.attributedText = textView.text.richText(isEditing: true, group_id: self.dataGroup["group_id"] as! String, listMentionInTextField: listMentionInTextField)
- return .preserveCursor
- })
- }
- }
-
- private func showMention(text: String) {
- if self.contraintBottomMention.constant < 0 {
- self.contraintBottomMention.constant = 65 + ((self.keyboardHeightForMention != nil) ? self.keyboardHeightForMention! : 0)
- if self.viewTextfield.subviews.contains(self.containerLink) {
- self.contraintBottomMention.constant = self.contraintBottomMention.constant + 80
- }
- if self.viewTextfield.subviews.contains(self.containerPreviewReply) {
- self.contraintBottomMention.constant = self.contraintBottomMention.constant + 50
- }
- UIView.animate(withDuration: 0.5, animations: {
- self.view.layoutIfNeeded()
- })
- }
- listMentionWithText.removeAll()
- Database.shared.database?.inTransaction({ fmdb, rollback in
- let idMe = UserDefaults.standard.string(forKey: "me")!
- if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "SELECT f_pin, first_name || ' ' || ifnull(last_name, '') name FROM GROUPZ_MEMBER where group_id='\(self.dataGroup["group_id"] as! String)' AND f_pin <> '\(idMe)' AND name LIKE '%\(text)%'") {
- while cursor.next() {
- let user = User(pin: "")
- user.pin = cursor.string(forColumnIndex: 0) ?? ""
- user.firstName = cursor.string(forColumnIndex: 1) ?? ""
- if !user.pin.isEmpty {
- let userFromBuddy = User.getDataCanNil(pin: user.pin, fmdb: fmdb)
- if userFromBuddy != nil {
- listMentionWithText.append(userFromBuddy!)
- } else {
- listMentionWithText.append(user)
- }
- }
- }
- cursor.close()
- }
- listMentionWithText.removeAll(where: { listMentionInTextField.contains($0) })
- if listMentionWithText.count > 0 {
- if listMentionWithText.count < 5 {
- self.heightTableMention.constant = CGFloat(44 * listMentionWithText.count)
- } else {
- self.heightTableMention.constant = 44 * 4
- }
- tableMention.reloadData()
- } else {
- self.heightTableMention.constant = 44
- self.hideMention()
- }
- })
- }
-
- private func hideMention() {
- if self.contraintBottomMention.constant > 0 {
- self.contraintBottomMention.constant = 0 - self.heightTableMention.constant
- UIView.animate(withDuration: 0.5, animations: {
- self.view.layoutIfNeeded()
- })
- }
- }
-
- private func checkLink(fullText: String) {
- if !isAlwaysHideLinkPreview {
- var text = ""
- let listTextSplitBreak = fullText.components(separatedBy: "\n")
- let indexFirstLinkSplitBreak = listTextSplitBreak.firstIndex(where: { $0.contains("www.") || $0.contains("http://") || $0.contains("https://") })
- if indexFirstLinkSplitBreak != nil {
- let listTextSplitSpace = listTextSplitBreak[indexFirstLinkSplitBreak!].components(separatedBy: " ")
- let indexFirstLinkSplitSpace = listTextSplitSpace.firstIndex(where: { ($0.starts(with: "www.") && $0.components(separatedBy: ".").count > 2) || ($0.starts(with: "http://") && $0.components(separatedBy: ".").count > 1) || ($0.starts(with: "https://") && $0.components(separatedBy: ".").count > 1) })
- if indexFirstLinkSplitSpace != nil {
- text = listTextSplitSpace[indexFirstLinkSplitSpace!]
- }
- }
- if !text.isEmpty {
- var stringURl = text
- if stringURl.starts(with: "www.") {
- stringURl = "https://" + stringURl.replacingOccurrences(of: "www.", with: "")
- }
- var dataURL = ""
- Database.shared.database?.inTransaction({ (fmdb, rollback) in
- if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "select data_link from LINK_PREVIEW where link='\(text)'") {
- while cursor.next() {
- if let data = cursor.string(forColumnIndex: 0) {
- dataURL = data
- }
- }
- cursor.close()
- }
- })
- if !dataURL.isEmpty {
- if let data = try! JSONSerialization.jsonObject(with: dataURL.data(using: String.Encoding.utf8)!, options: []) as? [String: Any] {
- let title = data["title"] as! String
- let description = data["description"] as! String
- let imageUrl = data["imageUrl"] as? String
- let link = data["link"] as! String
- if self.showingLink != text {
- self.showingLink = text
- self.deleteLinkPreview()
- self.buildPreviewLink(imageUrl: imageUrl, title: title, description: description, stringURl: link)
- }
- }
- } else {
- let slp = SwiftLinkPreview(session: URLSession.shared,
- workQueue: SwiftLinkPreview.defaultWorkQueue,
- responseQueue: DispatchQueue.main,
- cache: DisabledCache.instance)
- let preview = slp.preview(stringURl,
- onSuccess: { result in
- let title = result.title ?? "No Title"
- let description = stringURl.contains("google.com") ? "" : result.description
- let imageUrl = result.image
- Database.shared.database?.inTransaction({ (fmdb, rollback) in
- do {
- var dataJson: [String: Any] = [:]
- dataJson["title"] = title
- dataJson["description"] = description
- dataJson["imageUrl"] = imageUrl
- dataJson["link"] = text
- guard let json = String(data: try! JSONSerialization.data(withJSONObject: dataJson, options: []), encoding: String.Encoding.utf8) else {
- return
- }
- _ = try Database.shared.insertRecord(fmdb: fmdb, table: "LINK_PREVIEW", cvalues: [
- "id" : "\(Date().currentTimeMillis().toHex())",
- "link" : text,
- "data_link" : json,
- "retry": 0
- ], replace: true)
- } catch {
- rollback.pointee = true
- //print(error)
- }
- })
- if self.showingLink != text {
- self.showingLink = text
- self.deleteLinkPreview()
- self.buildPreviewLink(imageUrl: imageUrl, title: title, description: description, stringURl: text)
- }
- },
- onError: { error in
- self.deleteLinkPreview()
- })
- }
- } else {
- deleteLinkPreview()
- }
- }
- }
-
- private func buildPreviewLink(imageUrl: String?, title: String, description: String?, stringURl: String) {
- if !self.viewTextfield.subviews.contains(self.containerLink){
- UIView.animate(withDuration: 0.25, delay: 0.0, options: .curveEaseInOut, animations: {
- self.constraintTopTextField.constant = self.constraintTopTextField.constant + 80
- if self.contraintBottomMention.constant > 0 {
- self.contraintBottomMention.constant = self.contraintBottomMention.constant + 80
- }
- }, completion: nil)
- }
-
- self.viewTextfield.addSubview(self.containerLink)
- self.containerLink.translatesAutoresizingMaskIntoConstraints = false
- self.containerLink.leadingAnchor.constraint(equalTo: self.viewTextfield.leadingAnchor).isActive = true
- self.containerLink.bottomAnchor.constraint(equalTo: self.textFieldSend.topAnchor).isActive = true
- self.containerLink.trailingAnchor.constraint(equalTo: self.viewTextfield.trailingAnchor).isActive = true
- self.containerLink.heightAnchor.constraint(equalToConstant: 80.0).isActive = true
- self.containerLink.backgroundColor = .secondaryColor
-
- if self.reffId != nil {
- self.bottomAnchorPreviewReply.isActive = false
- self.bottomAnchorPreviewReply = self.containerPreviewReply.bottomAnchor.constraint(equalTo: self.containerLink.topAnchor)
- self.bottomAnchorPreviewReply.isActive = true
- }
-
- let imagePreview = UIImageView()
- if imageUrl != nil {
- self.containerLink.addSubview(imagePreview)
- imagePreview.translatesAutoresizingMaskIntoConstraints = false
- imagePreview.leadingAnchor.constraint(equalTo: self.containerLink.leadingAnchor).isActive = true
- imagePreview.bottomAnchor.constraint(equalTo: self.containerLink.bottomAnchor).isActive = true
- imagePreview.topAnchor.constraint(equalTo: self.containerLink.topAnchor).isActive = true
- imagePreview.widthAnchor.constraint(equalToConstant: 80.0).isActive = true
- if !imageUrl!.starts(with: "https://") {
- imagePreview.loadImageAsync(with: "https://www.google.be" + imageUrl!)
- } else {
- imagePreview.loadImageAsync(with: imageUrl)
- }
- imagePreview.contentMode = .scaleAspectFit
- }
-
- let titlePreview = UILabel()
- self.containerLink.addSubview(titlePreview)
- titlePreview.translatesAutoresizingMaskIntoConstraints = false
- if imageUrl != nil {
- titlePreview.leadingAnchor.constraint(equalTo: imagePreview.trailingAnchor, constant: 5.0).isActive = true
- } else {
- titlePreview.leadingAnchor.constraint(equalTo: self.containerLink.leadingAnchor, constant: 5.0).isActive = true
- }
- titlePreview.topAnchor.constraint(equalTo: self.containerLink.topAnchor, constant: 25.0).isActive = true
- titlePreview.trailingAnchor.constraint(equalTo: self.containerLink.trailingAnchor, constant: -80.0).isActive = true
- titlePreview.text = title
- titlePreview.font = UIFont.systemFont(ofSize: 14.0, weight: .bold)
- titlePreview.textColor = .black
-
- let descPreview = UILabel()
- self.containerLink.addSubview(descPreview)
- descPreview.translatesAutoresizingMaskIntoConstraints = false
- if imageUrl != nil {
- descPreview.leadingAnchor.constraint(equalTo: imagePreview.trailingAnchor, constant: 5.0).isActive = true
- } else {
- descPreview.leadingAnchor.constraint(equalTo: self.containerLink.leadingAnchor, constant: 5.0).isActive = true
- }
- descPreview.topAnchor.constraint(equalTo: titlePreview.bottomAnchor).isActive = true
- descPreview.trailingAnchor.constraint(equalTo: self.containerLink.trailingAnchor, constant: -80.0).isActive = true
- descPreview.text = description
- descPreview.font = UIFont.systemFont(ofSize: 12.0)
- descPreview.textColor = .gray
- descPreview.numberOfLines = 1
-
- let linkPreview = UILabel()
- self.containerLink.addSubview(linkPreview)
- linkPreview.translatesAutoresizingMaskIntoConstraints = false
- if imageUrl != nil {
- linkPreview.leadingAnchor.constraint(equalTo: imagePreview.trailingAnchor, constant: 5.0).isActive = true
- } else {
- linkPreview.leadingAnchor.constraint(equalTo: self.containerLink.leadingAnchor, constant: 5.0).isActive = true
- }
- linkPreview.topAnchor.constraint(equalTo: descPreview.bottomAnchor, constant: 8.0).isActive = true
- linkPreview.trailingAnchor.constraint(equalTo: self.containerLink.trailingAnchor, constant: -80.0).isActive = true
- linkPreview.text = stringURl
- linkPreview.font = UIFont.systemFont(ofSize: 10.0)
- linkPreview.textColor = .gray
- linkPreview.numberOfLines = 1
-
- let cancelPreview = UIButton(type: .custom)
- self.containerLink.addSubview(cancelPreview)
- cancelPreview.translatesAutoresizingMaskIntoConstraints = false
- cancelPreview.trailingAnchor.constraint(equalTo: self.containerLink.trailingAnchor, constant: -10).isActive = true
- cancelPreview.centerYAnchor.constraint(equalTo: self.containerLink.centerYAnchor).isActive = true
- cancelPreview.setImage(UIImage(systemName: "xmark.circle" , withConfiguration: UIImage.SymbolConfiguration(pointSize: 20, weight: .regular, scale: .default)), for: .normal)
- cancelPreview.addTarget(nil, action: #selector(self.removeLinkPreviewUntilEmptyTextView), for: .touchUpInside)
- cancelPreview.backgroundColor = .clear
- cancelPreview.tintColor = .mainColor
- }
-
- public func textViewDidBeginEditing(_ textView: UITextView) {
- if textView.textColor == UIColor.lightGray {
- textView.text = nil
- textView.textColor = UIColor.black
- }
- }
-
- public func textViewDidEndEditing(_ textView: UITextView) {
- if textView.text.isEmpty {
- textView.text = "Send message".localized()
- textView.textColor = UIColor.lightGray
- }
- }
-
- public override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
- if action == #selector(UIResponderStandardEditActions.paste(_:)) && (UIPasteboard.general.image != nil) {
- return true
- }
- return super.canPerformAction(action, withSender: sender)
- }
-
- public override func paste(_ sender: Any?) {
- if UIPasteboard.general.image != nil {
- let previewImageVC = PreviewAttachmentImageVideo(nibName: "PreviewAttachmentImageVideo", bundle: Bundle.resourceBundle(for: Nexilis.self))
- previewImageVC.image = UIPasteboard.general.image
- previewImageVC.fromCopy = true
- previewImageVC.currentTextTextField = textFieldSend.text
- previewImageVC.modalPresentationStyle = .custom
- previewImageVC.delegate = self
- self.present(previewImageVC, animated: true, completion: nil)
- }
- }
-
- public func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
- if text.isEmpty {
- if listMentionInTextField.count > 0 {
- for i in 0..<listMentionInTextField.count {
- if lastPositionCursorMention == Int(listMentionInTextField[i].ex_block!)! {
- let fulltextForMention = textFieldSend.text.substring(from: 0, to: lastPositionCursorMention - 1)
- let diff = textFieldSend.text.count - fulltextForMention.count
- var text = textView.text ?? ""
- let nameMention = (listMentionInTextField[i].firstName + " " + listMentionInTextField[i].lastName).trimmingCharacters(in: .whitespaces)
- let rangeReplacement = NSRange(location: lastPositionCursorMention - nameMention.count - 1, length: nameMention.count + 1)
- let replacementText = ""
-
- let copyAttributedText = text.richText(isEditing: true, group_id: self.dataGroup["group_id"] as! String, listMentionInTextField: listMentionInTextField)
- copyAttributedText.removeAttribute(.foregroundColor, range: rangeReplacement)
-
- textFieldSend.attributedText = copyAttributedText
- // Replace the old text with the new text using the replaceSubrange(_:with:) method
- if let startIndex = text.index(text.startIndex, offsetBy: rangeReplacement.location, limitedBy: text.endIndex),
- let endIndex = text.index(startIndex, offsetBy: rangeReplacement.length, limitedBy: text.endIndex) {
- text.replaceSubrange(startIndex..<endIndex, with: replacementText)
- }
-
- listMentionInTextField.remove(at: i)
-
- textFieldSend.attributedText = text.richText(isEditing: true, group_id: self.dataGroup["group_id"] as! String, listMentionInTextField: listMentionInTextField)
-
- let newPosition = textFieldSend.position(from: textFieldSend.beginningOfDocument, offset: textView.text.count - diff)
- textFieldSend.selectedTextRange = textFieldSend.textRange(from: newPosition!, to: newPosition!)
- return false
- }
- }
- }
- }
- if (self.textFieldSend.text.count == 0) {
- return text != "\n"
- }
- return true
- }
- }
- extension EditorGroup: UIContextMenuInteractionDelegate {
- public func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
- if textFieldSend.isFirstResponder {
- textFieldSend.resignFirstResponder()
- }
- let indexPath = self.tableChatView.indexPathForRow(at: interaction.view!.convert(location, to: self.tableChatView))
- let dataMessages = self.dataMessages.filter({ $0["chat_date"] as! String == dataDates[indexPath!.section]})
- var star: UIAction
- if (dataMessages[indexPath!.row]["is_stared"] as! String == "0") {
- star = UIAction(title: "Star".localized(), image: UIImage(systemName: "star.fill"), handler: {(_) in
- if self.removed {
- return
- }
- DispatchQueue.global().async {
- Database.shared.database?.inTransaction({ (fmdb, rollback) in
- _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE", cvalues: [
- "is_stared" : 1
- ], _where: "message_id = '\(dataMessages[indexPath!.row]["message_id"] as! String)'")
- })
- }
- let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as! String == dataMessages[indexPath!.row]["message_id"] as! String})
- if idx != nil{
- self.dataMessages[idx!]["is_stared"] = "1"
- }
- self.tableChatView.reloadRows(at: [indexPath!], with: .none)
- })
- } else {
- star = UIAction(title: "Unstar".localized(), image: UIImage(systemName: "star.fill"), handler: {(_) in
- if self.removed {
- return
- }
- DispatchQueue.global().async {
- Database.shared.database?.inTransaction({ (fmdb, rollback) in
- _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE", cvalues: [
- "is_stared" : 0
- ], _where: "message_id = '\(dataMessages[indexPath!.row]["message_id"] as! String)'")
- })
- }
- let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as! String == dataMessages[indexPath!.row]["message_id"] as! String})
- if idx != nil{
- self.dataMessages[idx!]["is_stared"] = "0"
- }
- self.tableChatView.reloadRows(at: [indexPath!], with: .none)
- })
- }
-
- let reply = UIAction(title: "Reply".localized(), image: UIImage(systemName: "arrowshape.turn.up.left.fill"), handler: {(_) in
- if self.removed {
- return
- }
- if self.isSearching {
- self.cancelAction()
- }
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.35, execute: {
- self.handleReply(indexPath: indexPath!)
- })
- })
- let forward = UIAction(title: "Forward".localized(), image: UIImage(systemName: "arrowshape.turn.up.right.fill"), handler: {(_) in
- if self.removed {
- return
- }
- if self.isSearching {
- self.cancelAction()
- }
- if self.reffId != nil {
- self.deleteReplyView()
- }
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) {
- self.forwardSession = true
- let cancelButton = UIBarButtonItem(title: "Cancel".localized(), style: .plain, target: self, action: #selector(self.cancelAction))
- if !self.isHistoryCC {
- self.navigationItem.rightBarButtonItems = nil
- }
- self.navigationItem.rightBarButtonItem = cancelButton
- self.changeAppBar()
- let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as? String == dataMessages[indexPath!.row]["message_id"] as? String})
- if idx != nil{
- self.dataMessages[idx!]["isSelected"] = true
- }
- self.addMultipleSelectSession()
- self.tableChatView.reloadData()
- }
- })
- let copy = UIAction(title: "Copy".localized(), image: UIImage(systemName: "doc.on.doc.fill"), handler: {(_) in
- if self.removed {
- return
- }
- if self.isSearching {
- self.cancelAction()
- }
- if self.reffId != nil {
- self.deleteReplyView()
- }
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) {
- self.copySession = true
- let cancelButton = UIBarButtonItem(title: "Cancel".localized(), style: .plain, target: self, action: #selector(self.cancelAction))
- if !self.isHistoryCC {
- self.navigationItem.rightBarButtonItems = nil
- }
- self.navigationItem.rightBarButtonItem = cancelButton
- self.changeAppBar()
- let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as? String == dataMessages[indexPath!.row]["message_id"] as? String})
- if idx != nil{
- self.dataMessages[idx!]["isSelected"] = true
- }
- self.addMultipleSelectSession()
- self.tableChatView.reloadData()
- }
- })
- let info = UIAction(title: "Info".localized(), image: UIImage(systemName: "info.circle.fill"), handler: {(_) in
- if self.removed {
- return
- }
- let messageInfoVC = MessageInfo()
- messageInfoVC.data = dataMessages[indexPath!.row]
- messageInfoVC.dataGroup = self.dataGroup
- messageInfoVC.isPersonal = false
- self.navigationController?.pushViewController(messageInfoVC, animated: true)
- })
- let delete = UIAction(title: "Delete".localized(), image: UIImage(systemName: "trash.fill"), attributes: .destructive, handler: {(_) in
- if self.removed {
- return
- }
- if self.isSearching {
- self.cancelAction()
- }
- if self.reffId != nil {
- self.deleteReplyView()
- }
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) {
- self.deleteSession = true
- let cancelButton = UIBarButtonItem(title: "Cancel".localized(), style: .plain, target: self, action: #selector(self.cancelAction))
- if !self.isHistoryCC {
- self.navigationItem.rightBarButtonItems = nil
- }
- self.navigationItem.rightBarButtonItem = cancelButton
- self.changeAppBar()
- let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as? String == dataMessages[indexPath!.row]["message_id"] as? String})
- if idx != nil{
- self.dataMessages[idx!]["isSelected"] = true
- }
- self.addMultipleSelectSession()
- self.tableChatView.reloadData()
- }
- })
-
- var children: [UIMenuElement] = [star, reply, forward, copy, delete]
- // let copyOption = self.copyOption(indexPath: indexPath!)
- let idMe = UserDefaults.standard.string(forKey: "me") as String?
-
- if (dataMessages[indexPath!.row]["lock"] != nil && dataMessages[indexPath!.row]["lock"] as! String == "1") {
- children = [delete]
- }
- else if dataMessages[indexPath!.row]["f_pin"] as! String == "-999" {
- children = [star, reply ,delete]
- if (dataMessages[indexPath!.row]["f_pin"] as! String) == idMe {
- children.insert(info, at: children.count - 1)
- }
- }
- 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" {
- children = [star, reply, forward ,delete]
- if (dataMessages[indexPath!.row]["f_pin"] as! String) == idMe {
- children.insert(info, at: children.count - 1)
- }
- } else {
- if (dataMessages[indexPath!.row]["f_pin"] as! String) == idMe {
- children.insert(info, at: children.count - 1)
- }
- }
-
- return UIContextMenuConfiguration(identifier: nil,
- previewProvider: nil) { _ in
- UIMenu(title: "", children: children)
- }
- }
-
- @objc func cancelAction() {
- DispatchQueue.main.async {
- if self.copySession {
- self.copySession = false
- } else if self.forwardSession {
- self.forwardSession = false
- } else if self.deleteSession {
- self.deleteSession = false
- } else if self.isSearching {
- self.countMatchesSearch = 0
- self.isSearching = false
- }
- if self.viewTextfield.isHidden {
- self.viewTextfield.isHidden = false
- }
- if self.viewAttachment.isHidden {
- self.viewAttachment.isHidden = false
- }
- if self.constraintBottomTableViewWithTextfield.constant == -60.0 {
- self.constraintBottomTableViewWithTextfield.constant = self.constraintBottomTableViewWithTextfield.constant + 70
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.3, execute: {
- if (self.currentIndexpath != nil) {
- self.tableChatView.scrollToRow(at: IndexPath(row: self.currentIndexpath!.row, section: self.currentIndexpath!.section), at: .none, animated: true)
- } else {
- self.tableChatView.scrollToBottom()
- }
- })
- }
- let data = self.dataMessages.filter({ $0["isSelected"] as! Bool == true })
- for i in 0..<data.count {
- let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as! String == data[i]["message_id"] as! String})
- if idx != nil{
- self.dataMessages[idx!]["isSelected"] = false
- }
- }
- self.tableChatView.reloadData()
- self.setRightButtonItem()
- self.changeAppBar()
- self.containerMultpileSelectSession.removeFromSuperview()
- self.checkNewMessage(tableView: self.tableChatView)
- }
- }
-
- private func addMultipleSelectSession() {
- viewTextfield.isHidden = true
- viewAttachment.isHidden = true
- constraintBottomTableViewWithTextfield.constant = constraintBottomTableViewWithTextfield.constant - 70
- view.addSubview(containerMultpileSelectSession)
- containerMultpileSelectSession.translatesAutoresizingMaskIntoConstraints = false
- constraintBottomContainerMultpileSelectSession = containerMultpileSelectSession.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: 0)
- NSLayoutConstraint.activate([
- containerMultpileSelectSession.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
- containerMultpileSelectSession.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
- constraintBottomContainerMultpileSelectSession,
- containerMultpileSelectSession.heightAnchor.constraint(equalToConstant: 50)
- ])
- containerMultpileSelectSession.backgroundColor = .white
- addSubviewMultipleSession()
- }
-
- private func addSubviewMultipleSession() {
- let container = UIView()
- containerMultpileSelectSession.addSubview(container)
- container.translatesAutoresizingMaskIntoConstraints = false
- NSLayoutConstraint.activate([
- container.leadingAnchor.constraint(equalTo: containerMultpileSelectSession.leadingAnchor),
- container.trailingAnchor.constraint(equalTo:containerMultpileSelectSession.trailingAnchor),
- container.bottomAnchor.constraint(equalTo: containerMultpileSelectSession.bottomAnchor),
- container.heightAnchor.constraint(equalToConstant: 50)
- ])
- container.layer.shadowOpacity = 0.7
- container.layer.shadowOffset = CGSize(width: 3, height: 3)
- container.layer.shadowRadius = 3.0
- container.layer.shadowColor = UIColor.black.cgColor
- container.backgroundColor = .secondaryColor
-
- if !isSearching {
- let title = UILabel()
- container.addSubview(title)
- title.translatesAutoresizingMaskIntoConstraints = false
- NSLayoutConstraint.activate([
- title.centerXAnchor.constraint(equalTo: container.centerXAnchor),
- title.centerYAnchor.constraint(equalTo:container.centerYAnchor),
- ])
- let countSelected = dataMessages.filter({ $0["isSelected"] as! Bool == true }).count
- title.text = "\(countSelected) " + "Selected".localized()
- title.textColor = .mainColor
- title.font = UIFont.systemFont(ofSize: 15).bold
-
- let button = UIImageView()
- container.addSubview(button)
- button.translatesAutoresizingMaskIntoConstraints = false
- NSLayoutConstraint.activate([
- button.leadingAnchor.constraint(equalTo: container.leadingAnchor, constant: 15),
- button.centerYAnchor.constraint(equalTo:container.centerYAnchor),
- button.widthAnchor.constraint(equalToConstant: 30),
- button.heightAnchor.constraint(equalToConstant: 30),
- ])
- if copySession {
- button.image = UIImage(systemName: "doc.on.doc")
- if countSelected == 0{
- button.tintColor = .gray
- } else {
- button.tintColor = .mainColor
- }
- } else if forwardSession {
- button.image = UIImage(systemName: "arrowshape.turn.up.right")
- if countSelected == 0{
- button.tintColor = .gray
- } else {
- button.tintColor = .mainColor
- }
- } else if deleteSession {
- button.image = UIImage(systemName: "trash")
- if countSelected == 0{
- button.tintColor = .gray
- } else {
- button.tintColor = .red
- }
- }
- let buttonGesture = UITapGestureRecognizer(target: self, action: #selector(sessionAction))
- button.isUserInteractionEnabled = true
- button.addGestureRecognizer(buttonGesture)
- } else {
- buttonUp = UIButton()
- container.addSubview(buttonUp)
- buttonUp.translatesAutoresizingMaskIntoConstraints = false
- NSLayoutConstraint.activate([
- buttonUp.leadingAnchor.constraint(equalTo: container.leadingAnchor, constant: 10),
- buttonUp.centerYAnchor.constraint(equalTo:container.centerYAnchor),
- buttonUp.widthAnchor.constraint(equalToConstant: 30),
- buttonUp.heightAnchor.constraint(equalToConstant: 30),
- ])
- buttonUp.addTarget(self, action: #selector(upSearchText), for: .touchUpInside)
-
- buttonDown = UIButton()
- container.addSubview(buttonDown)
- buttonDown.translatesAutoresizingMaskIntoConstraints = false
- NSLayoutConstraint.activate([
- buttonDown.leadingAnchor.constraint(equalTo: buttonUp.trailingAnchor, constant: 15),
- buttonDown.centerYAnchor.constraint(equalTo:container.centerYAnchor),
- buttonDown.widthAnchor.constraint(equalToConstant: 30),
- buttonDown.heightAnchor.constraint(equalToConstant: 30),
- ])
- buttonDown.addTarget(self, action: #selector(downSearchText), for: .touchUpInside)
-
- buttonUp.setImage(UIImage(systemName: "chevron.up"), for: .normal)
- buttonUp.tintColor = .gray
-
- buttonDown.setImage(UIImage(systemName: "chevron.down"), for: .normal)
- buttonDown.tintColor = .gray
-
- titleSearchMatches = UILabel()
- container.addSubview(titleSearchMatches)
- titleSearchMatches.translatesAutoresizingMaskIntoConstraints = false
- NSLayoutConstraint.activate([
- titleSearchMatches.centerXAnchor.constraint(equalTo: container.centerXAnchor),
- titleSearchMatches.centerYAnchor.constraint(equalTo:container.centerYAnchor),
- ])
- titleSearchMatches.textColor = .mainColor
- titleSearchMatches.font = UIFont.systemFont(ofSize: 15.0).bold
- titleSearchMatches.isHidden = true
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.3, execute: {
- self.searchBar.becomeFirstResponder()
- })
- }
- }
-
- @objc func upSearchText() {
- scrollToFirstSearchMessage(indexScroll: lastScrollIdxSearch + 1)
- }
-
- @objc func downSearchText() {
- scrollToFirstSearchMessage(indexScroll: lastScrollIdxSearch - 1)
- }
-
- @objc func sessionAction() {
- if copySession {
- let dataMessages = self.dataMessages.filter({ $0["isSelected"] as! Bool == true })
- let countSelected = dataMessages.count
- if countSelected == 0 {
- return
- }
- var nameTopic = "Lounge".localized()
- if !dataTopic.isEmpty {
- nameTopic = dataTopic["title"] as! String
- }
- var text = "*^\(dataGroup["f_name"]!!) (\(nameTopic))^*"
- for i in 0..<countSelected {
- let stringDate = (dataMessages[i]["server_date"] as! String)
- let date = Date(milliseconds: Int64(stringDate)!)
- let formatterDate = DateFormatter()
- let formatterTime = DateFormatter()
- formatterDate.dateFormat = "dd/MM/yy"
- formatterDate.locale = NSLocale(localeIdentifier: "id") as Locale?
- formatterTime.dateFormat = "HH:mm"
- formatterTime.locale = NSLocale(localeIdentifier: "id") as Locale?
- let dataProfile = getDataProfile(f_pin: dataMessages[i]["f_pin"] as! String, message_id: dataMessages[i]["message_id"] as! String)
- 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)"
- }
- text = text + "\n\n\nchat " + "Powered by Nexilis".localized()
- DispatchQueue.main.async {
- UIPasteboard.general.string = text
- self.showToast(message: "Text coppied to clipboard".localized(), font: UIFont.systemFont(ofSize: 12, weight: .medium), controller: self)
- }
- cancelAction()
- } else if forwardSession {
- let dataMessages = self.dataMessages.filter({ $0["isSelected"] as! Bool == true })
- let countSelected = dataMessages.count
- if countSelected == 0 {
- return
- }
- contactChatNav.modalPresentationStyle = .custom
- contactChatNav.navigationBar.tintColor = .white
- contactChatNav.navigationBar.barTintColor = .mainColor
- contactChatNav.navigationBar.isTranslucent = false
- let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
- contactChatNav.navigationBar.titleTextAttributes = textAttributes
- contactChatNav.view.backgroundColor = .mainColor
- if let controller = contactChatNav.viewControllers.first as? ContactChatViewController {
- controller.isChooser = { [weak self] scope, pin in
- if scope == "3" {
- let editorPersonalVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorPersonalVC") as! EditorPersonal
- editorPersonalVC.unique_l_pin = pin
- editorPersonalVC.dataMessageForward = dataMessages
- self?.navigationController?.replaceAllViewController(with: editorPersonalVC, animated: true)
- } else {
- let editorGroupVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorGroupVC") as! EditorGroup
- editorGroupVC.unique_l_pin = pin
- editorGroupVC.dataMessageForward = dataMessages
- self?.navigationController?.replaceAllViewController(with: editorGroupVC, animated: true)
- }
- }
- }
- self.present(contactChatNav, animated: true, completion: nil)
- } else if deleteSession {
- let dataMessages = self.dataMessages.filter({ $0["isSelected"] as! Bool == true })
- let countSelected = dataMessages.count
- if countSelected == 0 {
- return
- }
- let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
-
- if let action = self.actionDelete(for: "me", title: "Delete".localized() + " \(countSelected) " + "For Me".localized(), dataMessages: dataMessages) {
- alertController.addAction(action)
- }
- let idMe = UserDefaults.standard.string(forKey: "me") as String?
- let dataFilterFpin = dataMessages.filter({ $0["f_pin"] as? String != idMe})
- let dataFilterLock = dataMessages.filter({ $0["lock"] as? String == "1"})
- if dataFilterFpin.count == 0 && dataFilterLock.count == 0 {
- if let action = self.actionDelete(for: "everyone", title: "Delete".localized() + " \(countSelected) " + "For Everyone".localized(), dataMessages: dataMessages) {
- alertController.addAction(action)
- }
- }
- alertController.addAction(UIAlertAction(title: "Cancel".localized(), style: .cancel, handler: nil))
- self.present(alertController, animated: true)
- }
- }
-
- private func deleteMessage(l_pin: String, message_id: String, scope: String, type: String, chat: String) {
- let tmessage = CoreMessage_TMessageBank.deleteMessage(l_pin: l_pin, messageId: message_id, scope: scope, type: type, chat: chat)
- Nexilis.addQueueMessage(message: tmessage)
- }
-
- private func queryMessageReply(message_id: String) -> [String: Any?] {
- var dataQuery: [String: Any] = [:]
- Database().database?.inTransaction({ fmdb, rollback in
- 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() {
- dataQuery["message_id"] = c.string(forColumnIndex: 0)
- dataQuery["f_pin"] = c.string(forColumnIndex: 1)
- dataQuery["message_text"] = c.string(forColumnIndex: 2)
- dataQuery["attachment_flag"] = c.string(forColumnIndex: 3)
- dataQuery["thumb_id"] = c.string(forColumnIndex: 4)
- dataQuery["image_id"] = c.string(forColumnIndex: 5)
- dataQuery["video_id"] = c.string(forColumnIndex: 6)
- dataQuery["file_id"] = c.string(forColumnIndex: 7)
- c.close()
- }
- })
- return dataQuery
- }
-
- @objc func segmentedControlValueChanged(_ sender: segmentedControllerObject) {
- switch sender.selectedSegmentIndex {
- case 0:
- sender.navigation.viewControllers[0].children[1].view.isHidden = true
- break;
- case 1:
- sender.navigation.viewControllers[0].children[1].view.isHidden = false
- break;
- default:
- break;
- }
- }
-
- private func copyOption(indexPath: IndexPath) -> UIMenu {
- var ratingButtonTitles = ["Text".localized(), "Image".localized()]
- if (dataMessages[indexPath.row]["message_text"] as! String).isEmpty {
- ratingButtonTitles = ["Image".localized()]
- }
- let dataMessages = self.dataMessages.filter({ $0["chat_date"] as! String == dataDates[indexPath.section]})
- let copyActions = ratingButtonTitles
- .enumerated()
- .map { index, title in
- return UIAction(
- title: title,
- identifier: nil,
- handler: {(_) in
- if (dataMessages[indexPath.row]["message_text"] as! String).isEmpty {
- DispatchQueue.main.async {
- let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
- let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
- let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
- if let dirPath = paths.first {
- let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(dataMessages[indexPath.row]["image_id"] as! String)
- if FileManager.default.fileExists(atPath: imageURL.path) {
- let image = UIImage(contentsOfFile: imageURL.path)
- UIPasteboard.general.image = image
- self.showToast(message: "Image coppied to clipboard".localized(), font: UIFont.systemFont(ofSize: 12, weight: .medium), controller: self)
- }
- }
- }
- return
- }
- if (index == 0) {
- DispatchQueue.main.async {
- UIPasteboard.general.string = dataMessages[indexPath.row]["message_text"] as? String
- self.showToast(message: "Text coppied to clipboard".localized(), font: UIFont.systemFont(ofSize: 12, weight: .medium), controller: self)
- }
- } else {
- DispatchQueue.main.async {
- let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
- let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
- let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
- if let dirPath = paths.first {
- let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(dataMessages[indexPath.row]["image_id"] as! String)
- if FileManager.default.fileExists(atPath: imageURL.path) {
- let image = UIImage(contentsOfFile: imageURL.path)
- UIPasteboard.general.image = image
- self.showToast(message: "Image coppied to clipboard".localized(), font: UIFont.systemFont(ofSize: 12, weight: .medium), controller: self)
- }
- }
- }
- }
- self.dismissKeyboard()
-
- })
- }
- return UIMenu(
- title: "Copy".localized(),
- image: UIImage(systemName: "doc.on.doc.fill"),
- children: copyActions)
- }
-
- private func actionDelete(for type: String, title: String, dataMessages: [[String: Any?]]) -> UIAlertAction? {
- return UIAlertAction(title: title, style: .destructive) { [unowned self] _ in
- for i in 0..<dataMessages.count {
- if (type == "me") {
- 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)
- let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as? String == dataMessages[i]["message_id"] as? String})
- if idx != nil {
- self.dataMessages.remove(at: idx!)
- if (idx == self.dataMessages.count - 1) {
- NotificationCenter.default.post(name: NSNotification.Name(rawValue: "reloadTabChats"), object: nil, userInfo: nil)
- }
- for i in 0..<dataDates.count {
- if self.dataMessages.filter({ $0["chat_date"] as! String == dataDates[i] }).count == 0 {
- dataDates.remove(at: i)
- }
- }
- }
- } else {
- 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)
- let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as! String == dataMessages[i]["message_id"] as! String})
- if idx != nil {
- self.dataMessages[idx!]["lock"] = "1"
- self.dataMessages[idx!]["attachment_flag"] = "0"
- self.dataMessages[idx!]["reff_id"] = ""
- }
- }
- cancelAction()
- }
- }
- }
-
- @objc func deleteReplyView() {
- if self.containerPreviewReply.isDescendant(of: self.viewTextfield) {
- self.containerPreviewReply.subviews.forEach { $0.removeFromSuperview() }
- self.containerPreviewReply.removeConstraints(self.containerPreviewReply.constraints)
- self.containerPreviewReply.removeFromSuperview()
-
- self.reffId = nil
- UIView.animate(withDuration: 0.25, delay: 0.0, options: .curveEaseInOut, animations: {
- self.constraintTopTextField.constant = self.constraintTopTextField.constant - 50
- if self.contraintBottomMention.constant > 0 {
- self.contraintBottomMention.constant = self.contraintBottomMention.constant - 50
- }
- }, completion: nil)
- }
- }
-
- @objc func removeLinkPreviewUntilEmptyTextView() {
- isAlwaysHideLinkPreview = true
- deleteLinkPreview()
- }
-
- @objc func deleteLinkPreview() {
- if self.containerLink.isDescendant(of: self.viewTextfield) {
- self.containerLink.subviews.forEach { $0.removeFromSuperview() }
- self.containerLink.removeConstraints(self.containerLink.constraints)
- self.containerLink.removeFromSuperview()
- UIView.animate(withDuration: 0.25, delay: 0.0, options: .curveEaseInOut, animations: {
- self.constraintTopTextField.constant = self.constraintTopTextField.constant - 80
- if self.contraintBottomMention.constant > 0 {
- self.contraintBottomMention.constant = self.contraintBottomMention.constant - 80
- }
- }, completion: nil)
- self.showingLink = ""
- }
- if self.reffId != nil {
- self.bottomAnchorPreviewReply.isActive = false
- self.bottomAnchorPreviewReply = self.containerPreviewReply.bottomAnchor.constraint(equalTo: self.textFieldSend.topAnchor)
- self.bottomAnchorPreviewReply.isActive = true
- }
- }
- }
- extension EditorGroup: UICollectionViewDelegate, UICollectionViewDataSource {
- public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
- return 76
- }
-
- public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
- let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellSticker", for: indexPath)
- if (cell.contentView.subviews.count > 0) {
- cell.contentView.subviews[0].removeFromSuperview()
- }
- let imageSticker = UIImageView()
- cell.contentView.addSubview(imageSticker)
- imageSticker.translatesAutoresizingMaskIntoConstraints = false
- NSLayoutConstraint.activate([
- imageSticker.topAnchor.constraint(equalTo: cell.contentView.topAnchor),
- imageSticker.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor),
- imageSticker.leadingAnchor.constraint(equalTo: cell.contentView.leadingAnchor),
- imageSticker.trailingAnchor.constraint(equalTo: cell.contentView.trailingAnchor)
- ])
- imageSticker.image = UIImage(named: stickers[indexPath.row], in: Bundle.resourcesMediaBundle(for: Nexilis.self), with: nil)
- return cell
- }
-
- public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
- sendChat(message_text: "sticker/\(stickers[indexPath.row])", attachment_flag: "11", viewController: self)
- constraintBottomAttachment.constant = 0.0
- self.viewSticker.removeConstraints(self.viewSticker.constraints)
- self.viewSticker.removeFromSuperview()
- }
-
- public func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
- 1
- }
-
- public func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
- return self.previewItem!
- }
- }
- extension EditorGroup: UITableViewDelegate, UITableViewDataSource {
- // public func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
- // checkNewMessage(tableView: tableView)
- // }
-
- public func scrollViewDidScroll(_ scrollView: UIScrollView) {
- checkNewMessage(tableView: self.tableChatView)
- }
-
- public func numberOfSections(in tableView: UITableView) -> Int {
- if tableView == tableMention {
- return 1
- }
- return dataDates.count
- }
-
- public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
- if tableView == tableMention {
- return listMentionWithText.count
- }
- let count = dataMessages.filter({ $0["chat_date"] as! String == dataDates[section] }).count
- return count
- }
-
- public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
- if tableView == tableMention {
- return .none
- }
- let containerView = UIView()
- containerView.backgroundColor = .clear
-
- let dateView = UIView()
- containerView.addSubview(dateView)
- dateView.translatesAutoresizingMaskIntoConstraints = false
- var topAnchor = dateView.topAnchor.constraint(equalTo: containerView.topAnchor)
- if section == 0 {
- topAnchor = dateView.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 10.0)
- }
- NSLayoutConstraint.activate([
- topAnchor,
- dateView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor),
- dateView.centerXAnchor.constraint(equalTo: containerView.centerXAnchor),
- dateView.heightAnchor.constraint(equalToConstant: 30),
- dateView.widthAnchor.constraint(greaterThanOrEqualToConstant: 60)
- ])
- dateView.backgroundColor = .orangeColor
- dateView.layer.cornerRadius = 15.0
- dateView.clipsToBounds = true
-
- let labelDate = UILabel()
- dateView.addSubview(labelDate)
- labelDate.translatesAutoresizingMaskIntoConstraints = false
- NSLayoutConstraint.activate([
- labelDate.centerYAnchor.constraint(equalTo: dateView.centerYAnchor),
- labelDate.centerXAnchor.constraint(equalTo: dateView.centerXAnchor),
- labelDate.leadingAnchor.constraint(equalTo: dateView.leadingAnchor, constant: 10),
- labelDate.trailingAnchor.constraint(equalTo: dateView.trailingAnchor, constant: -10),
- ])
- labelDate.textAlignment = .center
- labelDate.textColor = .secondaryColor
- labelDate.font = UIFont.systemFont(ofSize: 12, weight: .medium)
- labelDate.text = dataDates[section]
- return containerView
- }
-
- public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
- if tableView == tableMention {
- return 0
- }
- if section == 0 {
- return 40
- }
- return 30
- }
-
- public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
- if tableView == tableMention {
- tableView.deselectRow(at: indexPath, animated: true)
- let fulltextForMention = textFieldSend.text.substring(from: 0, to: lastPositionCursorMention - 1)
- let diff = textFieldSend.text.count - fulltextForMention.count
- if let indexLastMention = fulltextForMention.lastIndex(of: "@") {
- listMentionInTextField.append(listMentionWithText[indexPath.row])
- let indexIntMention = fulltextForMention.distance(from: fulltextForMention.startIndex, to: indexLastMention)
- let rangeReplacement = NSRange(location: indexIntMention, length: lastPositionCursorMention - indexIntMention)
-
- var addSpaceAfterReplacement = ""
- if diff == 0 {
- addSpaceAfterReplacement = " "
- }
-
- var text = textFieldSend.text ?? ""
- let nameMention = (listMentionWithText[indexPath.row].firstName + " " + listMentionWithText[indexPath.row].lastName).trimmingCharacters(in: .whitespaces)
- let replacementText = "@\(nameMention)"
- // Replace the old text with the new text using the replaceSubrange(_:with:) method
- if let startIndex = text.index(text.startIndex, offsetBy: rangeReplacement.location, limitedBy: text.endIndex),
- let endIndex = text.index(startIndex, offsetBy: rangeReplacement.length, limitedBy: text.endIndex) {
- text.replaceSubrange(startIndex..<endIndex, with: replacementText + addSpaceAfterReplacement)
- }
-
- textFieldSend.attributedText = text.richText(isEditing: true, group_id: self.dataGroup["group_id"] as! String, listMentionInTextField: listMentionInTextField)
-
- let newPosition = textFieldSend.position(from: textFieldSend.beginningOfDocument, offset: textFieldSend.text.count - diff)
- textFieldSend.selectedTextRange = textFieldSend.textRange(from: newPosition!, to: newPosition!)
-
- listMentionInTextField.last?.ex_block = "\(textFieldSend.text.count - diff - addSpaceAfterReplacement.count)" //upperBound
-
- hideMention()
- }
- return
- }
- let dataMessages = self.dataMessages.filter({ $0["chat_date"] as! String == dataDates[indexPath.section] })
- if copySession || forwardSession || deleteSession {
- if copySession && dataMessages[indexPath.row]["f_pin"] as! String != "-999" {
- return
- }
- if (dataMessages[indexPath.row]["attachment_flag"] as! String != "0" || dataMessages[indexPath.row]["lock"] as? String == "1") && !forwardSession && !deleteSession {
- return
- }
- let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as! String == dataMessages[indexPath.row]["message_id"] as! String})
- if idx != nil {
- self.dataMessages[idx!]["isSelected"] = !(self.dataMessages[idx!]["isSelected"] as! Bool)
- self.tableChatView.reloadRows(at: [indexPath], with: .none)
- }
- containerMultpileSelectSession.subviews.forEach({ $0.removeFromSuperview() })
- addSubviewMultipleSession()
- return
- }
- 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 {
- var file = dataMessages[indexPath.row]["image_id"] as! String
- if file.isEmpty {
- file = dataMessages[indexPath.row]["video_id"] as! String
- if file.isEmpty {
- file = dataMessages[indexPath.row]["file_id"] as! String
- }
- }
- let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
- let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
- let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
- if let dirPath = paths.first {
- let fileURL = URL(fileURLWithPath: dirPath).appendingPathComponent(file)
- if !FileManager.default.fileExists(atPath: fileURL.path) {
- return
- }
- }
- }
- let message = dataMessages[indexPath.row]
- if let attachmentFlag = message["attachment_flag"], let attachmentFlag = attachmentFlag as? String {
- if attachmentFlag == "27" || attachmentFlag == "26" {
- let streamingController = (attachmentFlag == "27") ? QmeraCreateStreamingViewController() : CreateSeminarViewController()
- switch(attachmentFlag){
- case "27":
- (streamingController as! QmeraCreateStreamingViewController).isJoin = true
- default:
- (streamingController as! CreateSeminarViewController).isJoin = true
- }
- if let messageText = message["message_text"],
- let messageText = messageText as? String,
- var json = try! JSONSerialization.jsonObject(with: messageText.data(using: String.Encoding.utf8)!, options: []) as? [String: Any] {
- if json["blog"] == nil {
- json["blog"] = message["blog_id"] ?? nil
- }
- switch(attachmentFlag){
- case "27":
- (streamingController as! QmeraCreateStreamingViewController).data = json
- default:
- (streamingController as! CreateSeminarViewController).data = json
- }
- }
- let streamingNav = UINavigationController(rootViewController: streamingController)
- streamingNav.modalPresentationStyle = .custom
- streamingNav.navigationBar.tintColor = .white
- streamingNav.navigationBar.barTintColor = .mainColor
- streamingNav.navigationBar.isTranslucent = false
- streamingNav.navigationBar.overrideUserInterfaceStyle = .dark
- streamingNav.navigationBar.barStyle = .black
- let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.white]
- UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
- let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
- streamingNav.navigationBar.titleTextAttributes = textAttributes
- streamingNav.view.backgroundColor = .mainColor
- streamingNav.navigationBar.isTranslucent = false
- navigationController?.present(streamingNav, animated: true, completion: nil)
- }
- }
- }
-
-
-
- public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
- if tableView == tableMention {
- let cellMention = tableView.dequeueReusableCell(withIdentifier: "cellMention", for: indexPath as IndexPath)
- var content = cellMention.defaultContentConfiguration()
- content.textProperties.font = UIFont.systemFont(ofSize: 11)
- content.imageProperties.tintColor = .black
- content.imageProperties.maximumSize = CGSize(width: 24, height: 24)
- if indexPath.row < listMentionWithText.count {
- getImage(name: listMentionWithText[indexPath.row].thumb, placeholderImage: UIImage(systemName: "person"), isCircle: true, tableView: tableView, indexPath: indexPath, completion: { result, isDownloaded, image in
- content.image = image
- })
- content.text = listMentionWithText[indexPath.row].firstName
- }
- cellMention.contentConfiguration = content
- return cellMention
- }
- let idMe = UserDefaults.standard.string(forKey: "me") as String?
- let dataMessages = dataMessages.filter({$0["chat_date"] as! String == dataDates[indexPath.section]})
-
- let cellMessage = tableView.dequeueReusableCell(withIdentifier: "cellEditorGroup", for: indexPath as IndexPath)
- cellMessage.backgroundColor = .clear
- cellMessage.selectionStyle = .none
- cellMessage.contentView.subviews.forEach({ $0.removeFromSuperview() })
-
- let profileMessage = UIImageView()
- profileMessage.frame.size = CGSize(width: 35, height: 35)
- cellMessage.contentView.addSubview(profileMessage)
- profileMessage.translatesAutoresizingMaskIntoConstraints = false
- let tapGestureRecognizer = ObjectGesture(target: self, action: #selector(profilePersonTapped(_:)))
- tapGestureRecognizer.message_id = dataMessages[indexPath.row]["f_pin"] as! String
- profileMessage.isUserInteractionEnabled = true
- profileMessage.addGestureRecognizer(tapGestureRecognizer)
-
- let containerMessage = UIView()
-
- let thumbChat = dataMessages[indexPath.row]["thumb_id"] as! String
- let imageChat = dataMessages[indexPath.row]["image_id"] as! String
- let videoChat = dataMessages[indexPath.row]["video_id"] as! String
- let fileChat = dataMessages[indexPath.row]["file_id"] as! String
- let reffChat = dataMessages[indexPath.row]["reff_id"] as! String
-
- cellMessage.contentView.addSubview(containerMessage)
- containerMessage.translatesAutoresizingMaskIntoConstraints = false
-
- let timeMessage = UILabel()
- cellMessage.contentView.addSubview(timeMessage)
- timeMessage.translatesAutoresizingMaskIntoConstraints = false
- if (dataMessages[indexPath.row]["read_receipts"] as? String) == "8" {
- timeMessage.bottomAnchor.constraint(equalTo: cellMessage.contentView.bottomAnchor, constant: -40).isActive = true
- } else {
- timeMessage.bottomAnchor.constraint(equalTo: cellMessage.contentView.bottomAnchor, constant: -5).isActive = true
- }
-
- let messageText = UILabel()
- containerMessage.addSubview(messageText)
- messageText.translatesAutoresizingMaskIntoConstraints = false
- let topMarginText = messageText.topAnchor.constraint(equalTo: containerMessage.topAnchor, constant: 32)
-
- let dataProfile = getDataProfile(f_pin: dataMessages[indexPath.row]["f_pin"] as! String, message_id: dataMessages[indexPath.row]["message_id"] as! String)
-
- let statusMessage = UIImageView()
-
- if (dataMessages[indexPath.row]["attachment_flag"] as? String == "0" && dataMessages[indexPath.row]["lock"] as? String != "1") || forwardSession || deleteSession {
- var showSelectedImage = true
- if (!imageChat.isEmpty || !videoChat.isEmpty || !fileChat.isEmpty) && forwardSession {
- var file = dataMessages[indexPath.row]["image_id"] as! String
- if file.isEmpty {
- file = dataMessages[indexPath.row]["video_id"] as! String
- if file.isEmpty {
- file = dataMessages[indexPath.row]["file_id"] as! String
- }
- }
- let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
- let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
- let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
- if let dirPath = paths.first {
- let fileURL = URL(fileURLWithPath: dirPath).appendingPathComponent(file)
- if !FileManager.default.fileExists(atPath: fileURL.path) {
- showSelectedImage = false
- }
- }
- }
- if dataMessages[indexPath.row]["f_pin"] as! String == "-999" && !deleteSession {
- showSelectedImage = false
- }
- if showSelectedImage {
- let selectedImage = UIImageView()
- cellMessage.contentView.addSubview(selectedImage)
- selectedImage.translatesAutoresizingMaskIntoConstraints = false
- selectedImage.frame.size = CGSize(width: 20, height: 20)
- var leading = selectedImage.leadingAnchor.constraint(equalTo: cellMessage.contentView.leadingAnchor, constant: -20)
- selectedImage.isHidden = true
- if copySession || forwardSession || deleteSession {
- leading = selectedImage.leadingAnchor.constraint(equalTo: cellMessage.contentView.leadingAnchor, constant: 15)
- selectedImage.isHidden = false
- }
- NSLayoutConstraint.activate([
- leading,
- selectedImage.centerYAnchor.constraint(equalTo: cellMessage.contentView.centerYAnchor),
- selectedImage.widthAnchor.constraint(equalToConstant: 20),
- selectedImage.heightAnchor.constraint(equalToConstant: 20)
- ])
- selectedImage.circle()
- selectedImage.layer.borderWidth = 2
- selectedImage.layer.borderColor = UIColor.mainColor.cgColor
- if dataMessages[indexPath.row]["isSelected"] as! Bool {
- selectedImage.image = UIImage(systemName: "checkmark.circle.fill")
- }
- selectedImage.tintColor = .mainColor
- }
- }
-
- if (dataMessages[indexPath.row]["f_pin"] as? String == idMe) {
- profileMessage.topAnchor.constraint(equalTo: cellMessage.contentView.topAnchor, constant: 5).isActive = true
- profileMessage.trailingAnchor.constraint(equalTo: cellMessage.contentView.trailingAnchor, constant: -15).isActive = true
- profileMessage.heightAnchor.constraint(equalToConstant: 37).isActive = true
- profileMessage.widthAnchor.constraint(equalToConstant: 35).isActive = true
- profileMessage.circle()
- profileMessage.clipsToBounds = true
- profileMessage.backgroundColor = .lightGray
- profileMessage.image = UIImage(systemName: "person")
- profileMessage.tintColor = .white
- profileMessage.contentMode = .scaleAspectFit
-
- let pictureImage = dataProfile["image_id"]
- if (pictureImage != "" && pictureImage != nil) {
- profileMessage.setImage(name: pictureImage!)
- profileMessage.contentMode = .scaleAspectFill
- }
-
- containerMessage.topAnchor.constraint(equalTo: cellMessage.contentView.topAnchor, constant: 5).isActive = true
- containerMessage.leadingAnchor.constraint(greaterThanOrEqualTo: cellMessage.contentView.leadingAnchor, constant: 60).isActive = true
- if (dataMessages[indexPath.row]["read_receipts"] as? String) == "8" {
- containerMessage.bottomAnchor.constraint(equalTo: cellMessage.contentView.bottomAnchor, constant: -40).isActive = true
- } else {
- containerMessage.bottomAnchor.constraint(equalTo: cellMessage.contentView.bottomAnchor, constant: -5).isActive = true
- }
- containerMessage.trailingAnchor.constraint(equalTo: profileMessage.leadingAnchor, constant: -5).isActive = true
- containerMessage.widthAnchor.constraint(greaterThanOrEqualToConstant: 46).isActive = true
- containerMessage.layer.cornerRadius = 10.0
- containerMessage.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner, .layerMinXMinYCorner]
- containerMessage.clipsToBounds = true
-
- timeMessage.trailingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: -8).isActive = true
-
- if dataMessages[indexPath.row]["lock"] == nil || dataMessages[indexPath.row]["lock"] as! String == "0" {
- cellMessage.contentView.addSubview(statusMessage)
- statusMessage.translatesAutoresizingMaskIntoConstraints = false
- statusMessage.bottomAnchor.constraint(equalTo: timeMessage.topAnchor).isActive = true
- statusMessage.trailingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: -8).isActive = true
- statusMessage.widthAnchor.constraint(equalToConstant: 15).isActive = true
- statusMessage.heightAnchor.constraint(equalToConstant: 15).isActive = true
- let status = getRealStatus(messageId: dataMessages[indexPath.row]["message_id"] as! String)
- if (status == "1" || status == "2" ) {
- statusMessage.image = UIImage(named: "checklist", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withTintColor(UIColor.lightGray)
- } else if (status == "3") {
- statusMessage.image = UIImage(named: "double-checklist", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withTintColor(UIColor.lightGray)
- } else if (status == "8") {
- statusMessage.image = UIImage(named: "message_status_ack", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withRenderingMode(.alwaysOriginal)
- } else {
- statusMessage.image = UIImage(named: "double-checklist", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withTintColor(UIColor.systemBlue)
- }
- }
-
- let nameSender = UILabel()
- containerMessage.addSubview(nameSender)
- nameSender.translatesAutoresizingMaskIntoConstraints = false
- nameSender.topAnchor.constraint(equalTo: containerMessage.topAnchor, constant: 15).isActive = true
- nameSender.leadingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: 15).isActive = true
- nameSender.trailingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: -15).isActive = true
- nameSender.font = UIFont.systemFont(ofSize: 12).bold
- nameSender.text = dataProfile["name"]
- nameSender.textAlignment = .right
- if (dataMessages[indexPath.row]["attachment_flag"] as? String == "11" && dataMessages[indexPath.row]["reff_id"]as? String == "") {
- containerMessage.backgroundColor = .clear
- nameSender.textColor = .mainColor
- } else {
- containerMessage.backgroundColor = .blueBubbleColor
- nameSender.textColor = .mainColor
- }
-
- } else {
- if copySession || forwardSession || deleteSession {
- profileMessage.leadingAnchor.constraint(equalTo: cellMessage.contentView.leadingAnchor, constant: 50).isActive = true
- } else {
- profileMessage.leadingAnchor.constraint(equalTo: cellMessage.contentView.leadingAnchor, constant: 15).isActive = true
- }
- profileMessage.heightAnchor.constraint(equalToConstant: 37).isActive = true
- profileMessage.widthAnchor.constraint(equalToConstant: 35).isActive = true
- profileMessage.circle()
- profileMessage.clipsToBounds = true
- profileMessage.backgroundColor = .lightGray
- profileMessage.image = UIImage(systemName: "person")
- profileMessage.tintColor = .white
- profileMessage.contentMode = .scaleAspectFit
-
- let pictureImage = dataProfile["image_id"]
- if dataMessages[indexPath.row]["f_pin"] as? String == "-999" {
- if Utils.getIconDock() != nil {
- 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
- if dataImage != nil {
- profileMessage.image = UIImage(data: dataImage!)
- }
- } else {
- profileMessage.image = UIImage(named: "pb_button", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)
- }
- profileMessage.contentMode = .scaleAspectFill
- }
- else if (pictureImage != "" && pictureImage != nil) {
- profileMessage.setImage(name: pictureImage!)
- profileMessage.contentMode = .scaleAspectFill
- }
-
- if markerCounter != nil && dataMessages[indexPath.row]["message_id"] as? String == markerCounter {
- profileMessage.topAnchor.constraint(equalTo: cellMessage.contentView.topAnchor, constant: 35).isActive = true
- containerMessage.topAnchor.constraint(equalTo: cellMessage.contentView.topAnchor, constant: 35).isActive = true
-
- let newMessagesView = UIView()
- cellMessage.contentView.addSubview(newMessagesView)
- newMessagesView.translatesAutoresizingMaskIntoConstraints = false
- NSLayoutConstraint.activate([
- newMessagesView.topAnchor.constraint(equalTo: newMessagesView.topAnchor),
- newMessagesView.bottomAnchor.constraint(equalTo: containerMessage.topAnchor),
- newMessagesView.centerXAnchor.constraint(equalTo: cellMessage.contentView.centerXAnchor),
- newMessagesView.heightAnchor.constraint(equalToConstant: 30),
- newMessagesView.widthAnchor.constraint(greaterThanOrEqualToConstant: 60)
- ])
- newMessagesView.backgroundColor = .greenColor
- newMessagesView.layer.cornerRadius = 15.0
- newMessagesView.clipsToBounds = true
-
- let labelNewMessages = UILabel()
- newMessagesView.addSubview(labelNewMessages)
- labelNewMessages.translatesAutoresizingMaskIntoConstraints = false
- NSLayoutConstraint.activate([
- labelNewMessages.centerYAnchor.constraint(equalTo: newMessagesView.centerYAnchor),
- labelNewMessages.centerXAnchor.constraint(equalTo: newMessagesView.centerXAnchor),
- labelNewMessages.leadingAnchor.constraint(equalTo: newMessagesView.leadingAnchor, constant: 10),
- labelNewMessages.trailingAnchor.constraint(equalTo: newMessagesView.trailingAnchor, constant: -10),
- ])
- labelNewMessages.textAlignment = .center
- labelNewMessages.textColor = .secondaryColor
- labelNewMessages.font = UIFont.systemFont(ofSize: 12, weight: .medium)
- labelNewMessages.text = "Unread Messages".localized()
-
- } else {
- profileMessage.topAnchor.constraint(equalTo: cellMessage.contentView.topAnchor, constant: 5).isActive = true
- containerMessage.topAnchor.constraint(equalTo: cellMessage.contentView.topAnchor, constant: 5).isActive = true
- }
-
- containerMessage.leadingAnchor.constraint(equalTo: profileMessage.trailingAnchor, constant: 5).isActive = true
- if (dataMessages[indexPath.row]["read_receipts"] as? String) == "8" {
- containerMessage.bottomAnchor.constraint(equalTo: cellMessage.contentView.bottomAnchor, constant: -40).isActive = true
- } else {
- containerMessage.bottomAnchor.constraint(equalTo: cellMessage.contentView.bottomAnchor, constant: -5).isActive = true
- }
- containerMessage.trailingAnchor.constraint(lessThanOrEqualTo: cellMessage.contentView.trailingAnchor, constant: -60).isActive = true
- containerMessage.widthAnchor.constraint(greaterThanOrEqualToConstant: 46).isActive = true
- 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") {
- containerMessage.backgroundColor = .clear
- } else {
- containerMessage.backgroundColor = .grayColor
- }
- containerMessage.layer.cornerRadius = 10.0
- containerMessage.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMinYCorner, .layerMaxXMaxYCorner]
- containerMessage.clipsToBounds = true
-
- timeMessage.leadingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: 8).isActive = true
-
- let nameSender = UILabel()
- containerMessage.addSubview(nameSender)
- nameSender.translatesAutoresizingMaskIntoConstraints = false
- nameSender.topAnchor.constraint(equalTo: containerMessage.topAnchor, constant: 15).isActive = true
- nameSender.leadingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: 15).isActive = true
- nameSender.trailingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: -15).isActive = true
- nameSender.font = UIFont.systemFont(ofSize: 12).bold
- if dataMessages[indexPath.row]["f_pin"] as? String == "-999" {
- nameSender.text = "Bot"
- }
- else {
- nameSender.text = dataProfile["name"]
- }
- nameSender.textAlignment = .left
- nameSender.textColor = .mainColor
- }
-
- if dataMessages[indexPath.row]["is_stared"] as? String == "1" && (dataMessages[indexPath.row]["lock"] == nil || dataMessages[indexPath.row]["lock"] as! String == "0") {
- let imageStared = UIImageView()
- cellMessage.contentView.addSubview(imageStared)
- imageStared.translatesAutoresizingMaskIntoConstraints = false
- if (dataMessages[indexPath.row]["f_pin"] as? String == idMe) {
- imageStared.bottomAnchor.constraint(equalTo: statusMessage.topAnchor).isActive = true
- imageStared.trailingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: -8).isActive = true
- } else {
- imageStared.bottomAnchor.constraint(equalTo: timeMessage.topAnchor).isActive = true
- imageStared.leadingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: 8).isActive = true
- }
- imageStared.widthAnchor.constraint(equalToConstant: 15).isActive = true
- imageStared.heightAnchor.constraint(equalToConstant: 15).isActive = true
- imageStared.image = UIImage(systemName: "star.fill")
- imageStared.backgroundColor = .clear
- imageStared.tintColor = .systemYellow
- }
-
- if dataMessages[indexPath.row]["read_receipts"] as? String == "8" {
- let imageAckView = UIImageView()
- var imageAck = UIImage(named: "ack_icon_gray", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withRenderingMode(.alwaysOriginal)
- cellMessage.contentView.addSubview(imageAckView)
- imageAckView.translatesAutoresizingMaskIntoConstraints = false
- imageAckView.widthAnchor.constraint(equalToConstant: 30).isActive = true
- imageAckView.heightAnchor.constraint(equalToConstant: 30).isActive = true
- if (dataMessages[indexPath.row]["f_pin"] as? String == idMe) {
- let status = getRealStatus(messageId: dataMessages[indexPath.row]["message_id"] as! String)
- if status == "8" {
- imageAck = UIImage(named: "ack_icon", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withRenderingMode(.alwaysOriginal)
- }
- imageAckView.topAnchor.constraint(equalTo: containerMessage.bottomAnchor, constant: 5).isActive = true
- imageAckView.trailingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: 30).isActive = true
- } else {
- let status = dataMessages[indexPath.row]["status"] as? String
- if status == "8" {
- imageAck = UIImage(named: "ack_icon", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withRenderingMode(.alwaysOriginal)
- }
- imageAckView.topAnchor.constraint(equalTo: containerMessage.bottomAnchor, constant: 5).isActive = true
- imageAckView.leadingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: -30).isActive = true
- let tap = ObjectGesture(target: self, action: #selector(tapAck(_:)))
- tap.indexPath = indexPath
- imageAckView.addGestureRecognizer(tap)
- imageAckView.isUserInteractionEnabled = true
- }
- imageAckView.image = imageAck
- }
-
- messageText.numberOfLines = 0
- messageText.lineBreakMode = .byWordWrapping
- containerMessage.addSubview(messageText)
- topMarginText.isActive = true
- if dataMessages[indexPath.row]["attachment_flag"] as! String == "27" || dataMessages[indexPath.row]["attachment_flag"] as! String == "26" {
- messageText.leadingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: 85).isActive = true
- let imageLS = UIImageView()
- containerMessage.addSubview(imageLS)
- imageLS.translatesAutoresizingMaskIntoConstraints = false
- NSLayoutConstraint.activate([
- imageLS.leadingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: 15.0),
- imageLS.trailingAnchor.constraint(equalTo: messageText.leadingAnchor, constant: -10.0),
- imageLS.centerYAnchor.constraint(equalTo: containerMessage.centerYAnchor),
- imageLS.heightAnchor.constraint(equalToConstant: 60.0)
- ])
- if dataMessages[indexPath.row]["attachment_flag"] as! String == "26" {
- imageLS.image = UIImage(named: "pb_seminar_wpr", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)
- } else if dataMessages[indexPath.row]["attachment_flag"] as! String == "27" {
- imageLS.image = UIImage(named: "pb_live_tv", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)
- }
- } else {
- messageText.leadingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: 15).isActive = true
- }
- messageText.bottomAnchor.constraint(equalTo: containerMessage.bottomAnchor, constant: -15).isActive = true
- messageText.trailingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: -15).isActive = true
-
- messageText.textColor = .black
-
- var textChat = (dataMessages[indexPath.row]["message_text"])! as? String
- if (dataMessages[indexPath.row]["lock"] != nil && (dataMessages[indexPath.row]["lock"])! as? String == "1") {
- if (dataMessages[indexPath.row]["f_pin"] as? String == idMe) {
- textChat = "🚫 _"+"You were deleted this message".localized()+"_"
- } else {
- textChat = "🚫 _"+"This message was deleted".localized()+"_"
- }
- }
-
- let imageSticker = UIImageView()
-
- if let attachmentFlag = dataMessages[indexPath.row]["attachment_flag"], let attachmentFlag = attachmentFlag as? String {
- if attachmentFlag == "27" || attachmentFlag == "26", let data = textChat { // live streaming
- if let json = try! JSONSerialization.jsonObject(with: data.data(using: String.Encoding.utf8)!, options: []) as? [String: Any] {
- Database().database?.inTransaction({ fmdb, rollback in
- let title = json["title"] as! String
- let description = json["description"] as! String
- let start = json["time"] as! Int64
- let by = json["by"] as! String
- let textLS = "Live Streaming".localized()
- var type = "*\(textLS)*"
- if attachmentFlag == "26" {
- let textSeminar = "Seminar".localized()
- type = "*\(textSeminar)*"
- }
- if let c = Database().getRecords(fmdb: fmdb, query: "select first_name || ' ' || last_name from BUDDY where f_pin = '\(by)'"), c.next() {
- let name = c.string(forColumnIndex: 0)!
- messageText.attributedText = "\(type) \nTitle: \(title) \nDescription: \(description) \nStart: \(Date(milliseconds: start).format(dateFormat: "dd/MM/yyyy HH:mm")) \nBroadcaster: \(name)".richText()
- c.close()
- } else {
- messageText.attributedText = ("\(type) \nTitle: \(title) \nDescription: \(description) \nStart: \(Date(milliseconds: start).format(dateFormat: "dd/MM/yyyy HH:mm")) \nBroadcaster: " + "Unknown".localized()).richText()
- }
- })
- }
- }
- else if attachmentFlag == "11" && (dataMessages[indexPath.row]["lock"] == nil || dataMessages[indexPath.row]["lock"] as! String != "1") {
- messageText.text = ""
- topMarginText.constant = topMarginText.constant + 100
- containerMessage.addSubview(imageSticker)
- imageSticker.translatesAutoresizingMaskIntoConstraints = false
- if (reffChat == "") {
- imageSticker.topAnchor.constraint(equalTo: containerMessage.topAnchor, constant: 32).isActive = true
- imageSticker.widthAnchor.constraint(equalToConstant: 80).isActive = true
- } else {
- imageSticker.widthAnchor.constraint(greaterThanOrEqualToConstant: 80).isActive = true
- }
- imageSticker.leadingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: 15).isActive = true
- imageSticker.bottomAnchor.constraint(equalTo: messageText.topAnchor, constant: -5).isActive = true
- imageSticker.trailingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: -15).isActive = true
- imageSticker.image = UIImage(named: (textChat?.components(separatedBy: "/")[1])!, in: Bundle.resourcesMediaBundle(for: Nexilis.self), with: nil)
- imageSticker.contentMode = .scaleAspectFit
- }
- else {
- messageText.attributedText = textChat!.richText(group_id: self.dataGroup["group_id"] as! String)
- }
- } else {
- messageText.attributedText = textChat!.richText(group_id: self.dataGroup["group_id"] as! String)
- }
-
- messageText.isUserInteractionEnabled = false
- if !textChat!.isEmpty {
- let listTextEnter = textChat!.split(separator: "\n")
- for j in 0...listTextEnter.count - 1 {
- let listText = listTextEnter[j].split(separator: " ")
- for i in 0...listText.count - 1 {
- if listText[i].lowercased().checkStartWithLink() {
- let rangeTapLink = (textChat! as NSString).range(of: String(listText[i]))
- // Add tap gesture recognizer to the range of text
- let attributedString = textChat!.richText(group_id: self.dataGroup["group_id"] as! String)
- attributedString.addAttributes([.foregroundColor: UIColor.blue, .underlineStyle: NSUnderlineStyle.single.rawValue], range: rangeTapLink)
- messageText.attributedText = attributedString
- if messageText.isUserInteractionEnabled == false && !copySession && !forwardSession && !deleteSession && !isHistoryCC && !removed {
- messageText.isUserInteractionEnabled = true
- let longPress = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPressLink(_:)))
- longPress.minimumPressDuration = 0.1
- containerMessage.addGestureRecognizer(longPress)
- }
- }
- }
- }
- }
-
- if !copySession && !forwardSession && !deleteSession && !isHistoryCC && !removed && messageText.isUserInteractionEnabled == false {
- let interaction = UIContextMenuInteraction(delegate: self)
- containerMessage.addInteraction(interaction)
- containerMessage.isUserInteractionEnabled = true
- }
-
- if isSearching && textSearch.count > 1 {
- messageText.attributedText = textChat!.richText(isSearching: true, textSearch: textSearch, group_id: self.dataGroup["group_id"] as! String)
- if textChat!.lowercased().contains(textSearch) {
- countMatchesSearch += 1
- }
- }
-
- let stringDate = (dataMessages[indexPath.row]["server_date"] as! String)
- let date = Date(milliseconds: Int64(stringDate)!)
- let formatter = DateFormatter()
- formatter.dateFormat = "HH:mm"
- formatter.locale = NSLocale(localeIdentifier: "id") as Locale?
- timeMessage.text = formatter.string(from: date as Date)
- timeMessage.font = UIFont.systemFont(ofSize: 10, weight: .medium)
- timeMessage.textColor = .lightGray
-
- let imageThumb = UIImageView()
- let containerViewFile = UIView()
-
- if (thumbChat != "" && (dataMessages[indexPath.row]["lock"] == nil || dataMessages[indexPath.row]["lock"] as! String != "1")) {
- topMarginText.constant = topMarginText.constant + 205
-
- containerMessage.addSubview(imageThumb)
- imageThumb.translatesAutoresizingMaskIntoConstraints = false
- let data = queryMessageReply(message_id: reffChat)
- if (data.count == 0) {
- imageThumb.topAnchor.constraint(equalTo: containerMessage.topAnchor, constant: 32).isActive = true
- }
- imageThumb.leadingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: 15).isActive = true
- imageThumb.bottomAnchor.constraint(equalTo: messageText.topAnchor, constant: -5).isActive = true
- imageThumb.trailingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: -15).isActive = true
- imageThumb.widthAnchor.constraint(equalToConstant: self.view.frame.size.width * 0.6).isActive = true
- imageThumb.layer.cornerRadius = 5.0
- imageThumb.clipsToBounds = true
- imageThumb.contentMode = .scaleAspectFill
-
- let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
- let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
- let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
- if let dirPath = paths.first {
- let thumbURL = URL(fileURLWithPath: dirPath).appendingPathComponent(thumbChat)
- let image = UIImage(contentsOfFile: thumbURL.path)
- imageThumb.image = image
-
- let videoURL = URL(fileURLWithPath: dirPath).appendingPathComponent(videoChat)
- let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(imageChat)
- if !FileManager.default.fileExists(atPath: imageURL.path) || !FileManager.default.fileExists(atPath: videoURL.path){
- let blurEffect = UIBlurEffect(style: UIBlurEffect.Style.light)
- let blurEffectView = UIVisualEffectView(effect: blurEffect)
- blurEffectView.frame = CGRect(x: 0, y: 0, width: imageThumb.frame.size.width, height: imageThumb.frame.size.height)
- blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
- imageThumb.addSubview(blurEffectView)
- if !imageChat.isEmpty {
- let imageDownload = UIImageView(image: UIImage(systemName: "arrow.down.circle.fill", withConfiguration: UIImage.SymbolConfiguration(pointSize: 50, weight: .bold, scale: .default)))
- imageThumb.addSubview(blurEffectView)
- imageThumb.addSubview(imageDownload)
- imageDownload.tintColor = .black.withAlphaComponent(0.3)
- imageDownload.translatesAutoresizingMaskIntoConstraints = false
- imageDownload.centerXAnchor.constraint(equalTo: imageThumb.centerXAnchor).isActive = true
- imageDownload.centerYAnchor.constraint(equalTo: imageThumb.centerYAnchor).isActive = true
- }
- }
-
- }
-
- if (videoChat != "") {
- 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))
- imagePlay.circle()
- imageThumb.addSubview(imagePlay)
- imagePlay.backgroundColor = .black.withAlphaComponent(0.3)
- imagePlay.translatesAutoresizingMaskIntoConstraints = false
- imagePlay.centerXAnchor.constraint(equalTo: imageThumb.centerXAnchor).isActive = true
- imagePlay.centerYAnchor.constraint(equalTo: imageThumb.centerYAnchor).isActive = true
- }
-
- if (dataMessages[indexPath.row]["progress"] as! Double != 100.0 && dataMessages[indexPath.row]["f_pin"] as? String == idMe) {
- let container = UIView()
- imageThumb.addSubview(container)
- container.translatesAutoresizingMaskIntoConstraints = false
- container.bottomAnchor.constraint(equalTo: imageThumb.bottomAnchor, constant: -10).isActive = true
- container.leadingAnchor.constraint(equalTo: imageThumb.leadingAnchor, constant: 10).isActive = true
- container.widthAnchor.constraint(equalToConstant: 30).isActive = true
- container.heightAnchor.constraint(equalToConstant: 30).isActive = true
- container.backgroundColor = .white.withAlphaComponent(0.1)
- let circlePath = UIBezierPath(arcCenter: CGPoint(x: 10, y: 20), radius: 15, startAngle: -(.pi / 2), endAngle: .pi * 2, clockwise: true)
- let trackShape = CAShapeLayer()
- trackShape.path = circlePath.cgPath
- trackShape.fillColor = UIColor.black.withAlphaComponent(0.3).cgColor
- trackShape.lineWidth = 3
- trackShape.strokeColor = UIColor.blueBubbleColor.withAlphaComponent(0.3).cgColor
- container.backgroundColor = .clear
- container.layer.addSublayer(trackShape)
- let shapeLoading = CAShapeLayer()
- shapeLoading.path = circlePath.cgPath
- shapeLoading.fillColor = UIColor.clear.cgColor
- shapeLoading.lineWidth = 3
- shapeLoading.strokeEnd = 0
- shapeLoading.strokeColor = UIColor.blueBubbleColor.cgColor
- container.layer.addSublayer(shapeLoading)
- let imageupload = UIImageView(image: UIImage(systemName: "arrow.up", withConfiguration: UIImage.SymbolConfiguration(pointSize: 10, weight: .bold, scale: .default)))
- imageupload.tintColor = .white
- container.addSubview(imageupload)
- imageupload.translatesAutoresizingMaskIntoConstraints = false
- imageupload.bottomAnchor.constraint(equalTo: imageThumb.bottomAnchor, constant: -10).isActive = true
- imageupload.leadingAnchor.constraint(equalTo: imageThumb.leadingAnchor, constant: 10).isActive = true
- imageupload.widthAnchor.constraint(equalToConstant: 20).isActive = true
- imageupload.heightAnchor.constraint(equalToConstant: 20).isActive = true
- }
-
- if !copySession && !forwardSession && !deleteSession {
- let objectTap = ObjectGesture(target: self, action: #selector(contentMessageTapped(_:)))
- imageThumb.isUserInteractionEnabled = true
- imageThumb.addGestureRecognizer(objectTap)
- objectTap.image_id = imageChat
- objectTap.video_id = videoChat
- objectTap.imageView = imageThumb
- objectTap.indexPath = indexPath
- }
- }
-
- if (fileChat != "" && (dataMessages[indexPath.row]["lock"] == nil || dataMessages[indexPath.row]["lock"] as! String != "1")) {
- topMarginText.constant = topMarginText.constant + 55
-
- let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
- let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
- let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
- let arrExtFile = (textChat?.components(separatedBy: "|")[0])?.split(separator: ".")
- let finalExtFile = arrExtFile![arrExtFile!.count - 1]
- if let dirPath = paths.first {
- let fileURL = URL(fileURLWithPath: dirPath).appendingPathComponent(fileChat)
- if let dataFile = try? Data(contentsOf: fileURL) {
- var sizeOfFile = Int(dataFile.count / 1000000)
- if (sizeOfFile < 1) {
- sizeOfFile = Int(dataFile.count / 1000)
- if (finalExtFile.count > 4) {
- messageText.text = "\(sizeOfFile) kB \u{2022} TXT"
- }else {
- messageText.text = "\(sizeOfFile) kB \u{2022} \(finalExtFile.uppercased())"
- }
- } else {
- if (finalExtFile.count > 4) {
- messageText.text = "\(sizeOfFile) MB \u{2022} TXT"
- }else {
- messageText.text = "\(sizeOfFile) MB \u{2022} \(finalExtFile.uppercased())"
- }
- }
- } else {
- messageText.text = ""
- }
- }
-
- containerMessage.addSubview(containerViewFile)
- containerViewFile.translatesAutoresizingMaskIntoConstraints = false
- let data = queryMessageReply(message_id: reffChat)
- if (data.count == 0) {
- containerViewFile.topAnchor.constraint(equalTo: containerMessage.topAnchor, constant: 32).isActive = true
- }
- containerViewFile.leadingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: 15).isActive = true
- containerViewFile.bottomAnchor.constraint(equalTo:messageText.topAnchor, constant: -5).isActive = true
- containerViewFile.trailingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: -15).isActive = true
- containerViewFile.heightAnchor.constraint(equalToConstant: 50).isActive = true
- containerViewFile.backgroundColor = .black.withAlphaComponent(0.2)
- containerViewFile.layer.cornerRadius = 5.0
- containerViewFile.clipsToBounds = true
-
- let imageFile = UIImageView(image: UIImage(systemName: "doc.fill", withConfiguration: UIImage.SymbolConfiguration(pointSize: 30, weight: .bold, scale: .default)))
- containerViewFile.addSubview(imageFile)
- let nameFile = UILabel()
- containerViewFile.addSubview(nameFile)
-
- imageFile.translatesAutoresizingMaskIntoConstraints = false
- imageFile.leadingAnchor.constraint(equalTo: containerViewFile.leadingAnchor, constant: 5).isActive = true
- imageFile.trailingAnchor.constraint(equalTo: nameFile.leadingAnchor, constant: -5).isActive = true
- imageFile.centerYAnchor.constraint(equalTo: containerViewFile.centerYAnchor).isActive = true
- imageFile.widthAnchor.constraint(equalToConstant: 30).isActive = true
- imageFile.heightAnchor.constraint(equalToConstant: 30).isActive = true
- imageFile.tintColor = .docColor
-
- nameFile.translatesAutoresizingMaskIntoConstraints = false
- nameFile.centerYAnchor.constraint(equalTo: containerViewFile.centerYAnchor).isActive = true
- nameFile.widthAnchor.constraint(lessThanOrEqualToConstant: 200).isActive = true
- nameFile.font = UIFont.systemFont(ofSize: 12, weight: .medium)
- nameFile.textColor = .white
- nameFile.text = textChat?.components(separatedBy: "|")[0]
-
- if (dataMessages[indexPath.row]["progress"] as! Double != 100.0) {
- let containerLoading = UIView()
- containerViewFile.addSubview(containerLoading)
- containerLoading.translatesAutoresizingMaskIntoConstraints = false
- containerLoading.centerYAnchor.constraint(equalTo: containerViewFile.centerYAnchor).isActive = true
- containerLoading.leadingAnchor.constraint(equalTo: nameFile.trailingAnchor, constant: 5).isActive = true
- containerLoading.trailingAnchor.constraint(equalTo: containerViewFile.trailingAnchor, constant: -5).isActive = true
- containerLoading.widthAnchor.constraint(equalToConstant: 30).isActive = true
- containerLoading.heightAnchor.constraint(equalToConstant: 30).isActive = true
- let circlePath = UIBezierPath(arcCenter: CGPoint(x: 15, y: 15), radius: 10, startAngle: -(.pi / 2), endAngle: .pi * 2, clockwise: true)
- let trackShape = CAShapeLayer()
- trackShape.path = circlePath.cgPath
- trackShape.fillColor = UIColor.clear.cgColor
- trackShape.lineWidth = 5
- trackShape.strokeColor = UIColor.blueBubbleColor.withAlphaComponent(0.3).cgColor
- containerLoading.layer.addSublayer(trackShape)
- let shapeLoading = CAShapeLayer()
- shapeLoading.path = circlePath.cgPath
- shapeLoading.fillColor = UIColor.clear.cgColor
- shapeLoading.lineWidth = 3
- shapeLoading.strokeEnd = 0
- shapeLoading.strokeColor = UIColor.secondaryColor.cgColor
- containerLoading.layer.addSublayer(shapeLoading)
- var imageupload = UIImageView(image: UIImage(systemName: "arrow.up", withConfiguration: UIImage.SymbolConfiguration(pointSize: 10, weight: .bold, scale: .default)))
- if dataMessages[indexPath.row]["f_pin"] as? String != idMe {
- imageupload = UIImageView(image: UIImage(systemName: "arrow.down", withConfiguration: UIImage.SymbolConfiguration(pointSize: 10, weight: .bold, scale: .default)))
- shapeLoading.strokeColor = UIColor.blueBubbleColor.cgColor
- }
- imageupload.tintColor = .white
- containerLoading.addSubview(imageupload)
- imageupload.translatesAutoresizingMaskIntoConstraints = false
- imageupload.centerYAnchor.constraint(equalTo: containerLoading.centerYAnchor).isActive = true
- imageupload.centerXAnchor.constraint(equalTo: containerLoading.centerXAnchor).isActive = true
- } else {
- nameFile.trailingAnchor.constraint(equalTo: containerViewFile.trailingAnchor, constant: -5).isActive = true
- }
-
- if !copySession && !forwardSession && !deleteSession {
- let objectTap = ObjectGesture(target: self, action: #selector(contentMessageTapped(_:)))
- containerViewFile.addGestureRecognizer(objectTap)
- objectTap.containerFile = containerViewFile
- objectTap.labelFile = nameFile
- objectTap.file_id = fileChat
- objectTap.indexPath = indexPath
- }
- }
-
- let containerLinkMessage = UIView()
- if thumbChat.isEmpty && fileChat.isEmpty && !textChat!.isEmpty {
- var text = ""
- let listTextSplitBreak = textChat!.components(separatedBy: "\n")
- let indexFirstLinkSplitBreak = listTextSplitBreak.firstIndex(where: { $0.contains("www.") || $0.contains("http://") || $0.contains("https://") })
- if indexFirstLinkSplitBreak != nil {
- let listTextSplitSpace = listTextSplitBreak[indexFirstLinkSplitBreak!].components(separatedBy: " ")
- let indexFirstLinkSplitSpace = listTextSplitSpace.firstIndex(where: { ($0.starts(with: "www.") && $0.components(separatedBy: ".").count > 2) || ($0.starts(with: "http://") && $0.components(separatedBy: ".").count > 1) || ($0.starts(with: "https://") && $0.components(separatedBy: ".").count > 1) })
- if indexFirstLinkSplitSpace != nil {
- text = listTextSplitSpace[indexFirstLinkSplitSpace!]
- }
- }
- if !text.isEmpty {
- var dataURL = ""
- Database.shared.database?.inTransaction({ (fmdb, rollback) in
- if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "select data_link from LINK_PREVIEW where link='\(text)'"), cursor.next() {
- if let data = cursor.string(forColumnIndex: 0) {
- dataURL = data
- }
- cursor.close()
- }
- })
-
- if !dataURL.isEmpty {
- if let data = try! JSONSerialization.jsonObject(with: dataURL.data(using: String.Encoding.utf8)!, options: []) as? [String: Any] {
- let title = data["title"] as! String
- let description = data["description"] as! String
- let imageUrl = data["imageUrl"] as? String
- let link = data["link"] as! String
-
- topMarginText.constant = topMarginText.constant + 80
-
- containerMessage.addSubview(containerLinkMessage)
- containerLinkMessage.translatesAutoresizingMaskIntoConstraints = false
- containerLinkMessage.leadingAnchor.constraint(equalTo:containerMessage.leadingAnchor, constant: 15).isActive = true
- if dataMessages[indexPath.row]["attachment_flag"] as? String == "11" {
- containerLinkMessage.bottomAnchor.constraint(equalTo: imageSticker.topAnchor, constant: -5).isActive = true
- } else {
- containerLinkMessage.bottomAnchor.constraint(equalTo: messageText.topAnchor, constant: -5).isActive = true
- }
- containerLinkMessage.trailingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: -15).isActive = true
- containerLinkMessage.heightAnchor.constraint(equalToConstant: 80.0).isActive = true
- containerLinkMessage.backgroundColor = .gray.withAlphaComponent(0.2)
-
- let imagePreview = UIImageView()
- if imageUrl != nil {
- containerLinkMessage.addSubview(imagePreview)
- imagePreview.translatesAutoresizingMaskIntoConstraints = false
- imagePreview.leadingAnchor.constraint(equalTo: containerLinkMessage.leadingAnchor).isActive = true
- imagePreview.bottomAnchor.constraint(equalTo: containerLinkMessage.bottomAnchor).isActive = true
- imagePreview.topAnchor.constraint(equalTo: containerLinkMessage.topAnchor).isActive = true
- imagePreview.widthAnchor.constraint(equalToConstant: 80.0).isActive = true
- if !imageUrl!.starts(with: "https://") {
- imagePreview.loadImageAsync(with: "https://www.google.be" + imageUrl!)
- } else {
- imagePreview.loadImageAsync(with: imageUrl)
- }
- imagePreview.contentMode = .scaleAspectFit
- }
-
- let titlePreview = UILabel()
- containerLinkMessage.addSubview(titlePreview)
- titlePreview.translatesAutoresizingMaskIntoConstraints = false
- if imageUrl != nil {
- titlePreview.leadingAnchor.constraint(equalTo: imagePreview.trailingAnchor, constant: 5.0).isActive = true
- } else {
- titlePreview.leadingAnchor.constraint(equalTo: containerLinkMessage.leadingAnchor, constant: 5.0).isActive = true
- }
- titlePreview.topAnchor.constraint(equalTo: containerLinkMessage.topAnchor, constant: 25.0).isActive = true
- titlePreview.trailingAnchor.constraint(equalTo: containerLinkMessage.trailingAnchor, constant: -80.0).isActive = true
- titlePreview.text = title
- titlePreview.font = UIFont.systemFont(ofSize: 14.0, weight: .bold)
- titlePreview.textColor = .black
-
- let descPreview = UILabel()
- containerLinkMessage.addSubview(descPreview)
- descPreview.translatesAutoresizingMaskIntoConstraints = false
- if imageUrl != nil {
- descPreview.leadingAnchor.constraint(equalTo: imagePreview.trailingAnchor, constant: 5.0).isActive = true
- } else {
- descPreview.leadingAnchor.constraint(equalTo: containerLinkMessage.leadingAnchor, constant: 5.0).isActive = true
- }
- descPreview.topAnchor.constraint(equalTo: titlePreview.bottomAnchor).isActive = true
- descPreview.trailingAnchor.constraint(equalTo: containerLinkMessage.trailingAnchor, constant: -80.0).isActive = true
- descPreview.text = description
- descPreview.font = UIFont.systemFont(ofSize: 12.0)
- descPreview.textColor = .gray
- descPreview.numberOfLines = 1
-
- let linkPreview = UILabel()
- containerLinkMessage.addSubview(linkPreview)
- linkPreview.translatesAutoresizingMaskIntoConstraints = false
- if imageUrl != nil {
- linkPreview.leadingAnchor.constraint(equalTo: imagePreview.trailingAnchor, constant: 5.0).isActive = true
- } else {
- linkPreview.leadingAnchor.constraint(equalTo: containerLinkMessage.leadingAnchor, constant: 5.0).isActive = true
- }
- linkPreview.topAnchor.constraint(equalTo: descPreview.bottomAnchor, constant: 8.0).isActive = true
- linkPreview.trailingAnchor.constraint(equalTo: containerLinkMessage.trailingAnchor, constant: -80.0).isActive = true
- linkPreview.text = link
- linkPreview.font = UIFont.systemFont(ofSize: 10.0)
- linkPreview.textColor = .gray
- linkPreview.numberOfLines = 1
-
- if !copySession && !forwardSession && !deleteSession {
- let objectTap = ObjectGesture(target: self, action: #selector(tapMessageText(_:)))
- objectTap.message_id = text
- containerLinkMessage.addGestureRecognizer(objectTap)
- }
- }
- }
- }
- }
-
- if (reffChat != "") {
- let data = queryMessageReply(message_id: reffChat)
- if data.count != 0 {
- topMarginText.constant = topMarginText.constant + 55
-
- let containerReply = UIView()
- containerMessage.addSubview(containerReply)
- containerReply.translatesAutoresizingMaskIntoConstraints = false
- containerReply.leadingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: 15).isActive = true
- containerReply.topAnchor.constraint(equalTo: containerMessage.topAnchor, constant: 32).isActive = true
- if thumbChat != "" && (dataMessages[indexPath.row]["lock"] == nil || dataMessages[indexPath.row]["lock"] as! String != "1") {
- containerReply.bottomAnchor.constraint(equalTo: imageThumb.topAnchor, constant: -5).isActive = true
- } else if fileChat != "" && (dataMessages[indexPath.row]["lock"] == nil || dataMessages[indexPath.row]["lock"] as! String != "1") {
- containerReply.bottomAnchor.constraint(equalTo: containerViewFile.topAnchor, constant: -5).isActive = true
- } else if containerMessage.subviews.contains(containerLinkMessage) {
- containerReply.bottomAnchor.constraint(equalTo: containerLinkMessage.topAnchor, constant: -5).isActive = true
- } else if dataMessages[indexPath.row]["attachment_flag"] as? String == "11" && (dataMessages[indexPath.row]["lock"] == nil || dataMessages[indexPath.row]["lock"] as! String != "1") {
- containerReply.bottomAnchor.constraint(equalTo: imageSticker.topAnchor, constant: -5).isActive = true
- } else {
- containerReply.bottomAnchor.constraint(equalTo: messageText.topAnchor, constant: -5).isActive = true
- }
- containerReply.trailingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: -15).isActive = true
- containerReply.heightAnchor.constraint(equalToConstant: 50).isActive = true
- containerReply.backgroundColor = .black.withAlphaComponent(0.2)
- containerReply.layer.cornerRadius = 5
- containerReply.clipsToBounds = true
-
- let leftReply = UIView()
- containerReply.addSubview(leftReply)
- leftReply.translatesAutoresizingMaskIntoConstraints = false
- leftReply.leadingAnchor.constraint(equalTo: containerReply.leadingAnchor).isActive = true
- leftReply.topAnchor.constraint(equalTo: containerReply.topAnchor).isActive = true
- leftReply.bottomAnchor.constraint(equalTo: containerReply.bottomAnchor).isActive = true
- leftReply.widthAnchor.constraint(equalToConstant: 3).isActive = true
- leftReply.layer.cornerRadius = 5
- leftReply.clipsToBounds = true
- leftReply.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMinXMinYCorner]
-
- let titleReply = UILabel()
- containerReply.addSubview(titleReply)
- titleReply.translatesAutoresizingMaskIntoConstraints = false
- titleReply.leadingAnchor.constraint(equalTo: leftReply.leadingAnchor, constant: 10).isActive = true
- titleReply.topAnchor.constraint(equalTo: containerReply.topAnchor, constant: 10).isActive = true
- titleReply.trailingAnchor.constraint(lessThanOrEqualTo: containerReply.trailingAnchor, constant: -20).isActive = true
- titleReply.font = UIFont.systemFont(ofSize: 12).bold
- if (data["f_pin"] as? String == idMe) {
- titleReply.text = "You".localized()
- if dataMessages[indexPath.row]["f_pin"] as? String == idMe {
- titleReply.textColor = .white
- leftReply.backgroundColor = .white
- } else {
- titleReply.textColor = .mainColor
- leftReply.backgroundColor = .mainColor
- }
- } else {
- if data["f_pin"] as? String != "-999" {
- let dataProfile = getDataProfile(f_pin: data["f_pin"] as! String, message_id: data["message_id"] as! String)
- titleReply.text = dataProfile["name"]
- } else {
- titleReply.text = "Bot"
- }
- if dataMessages[indexPath.row]["f_pin"] as? String == idMe {
- titleReply.textColor = .white
- leftReply.backgroundColor = .white
- } else {
- titleReply.textColor = .mainColor
- leftReply.backgroundColor = .mainColor
- }
- }
-
- let contentReply = UILabel()
- containerReply.addSubview(contentReply)
- contentReply.translatesAutoresizingMaskIntoConstraints = false
- contentReply.leadingAnchor.constraint(equalTo: leftReply.leadingAnchor, constant: 10).isActive = true
- contentReply.bottomAnchor.constraint(equalTo: containerReply.bottomAnchor, constant: -10).isActive = true
- contentReply.font = UIFont.systemFont(ofSize: 10)
- let message_text = data["message_text"] as! String
- let attachment_flag = data["attachment_flag"] as! String
- let thumb_chat = data["thumb_id"] as! String
- let image_chat = data["image_id"] as! String
- let video_chat = data["video_id"] as! String
- let file_chat = data["file_id"] as! String
- if (attachment_flag == "0" && thumb_chat == "") {
- contentReply.trailingAnchor.constraint(equalTo: containerReply.trailingAnchor, constant: -20).isActive = true
- contentReply.attributedText = message_text.richText(group_id: self.dataGroup["group_id"] as! String)
- } else if (attachment_flag == "1" || image_chat != "") {
- if (message_text == "") {
- contentReply.text = "📷 Photo".localized()
- } else {
- contentReply.attributedText = message_text.richText(group_id: self.dataGroup["group_id"] as! String)
- }
- } else if (attachment_flag == "2" || video_chat != "") {
- if (message_text == "") {
- contentReply.text = "📹 Video".localized()
- } else {
- contentReply.attributedText = message_text.richText(group_id: self.dataGroup["group_id"] as! String)
- }
- } else if (attachment_flag == "6" || file_chat != ""){
- contentReply.trailingAnchor.constraint(equalTo: containerReply.trailingAnchor, constant: -20).isActive = true
- contentReply.text = "📄 \(message_text.components(separatedBy: "|")[0])"
- } else if (attachment_flag == "11") {
- contentReply.text = "❤️ Sticker"
- } else if attachment_flag == "27" {
- contentReply.trailingAnchor.constraint(equalTo: containerReply.trailingAnchor, constant: -20).isActive = true
- contentReply.text = "📄 " + "Live Streaming".localized()
- } else if attachment_flag == "26" {
- contentReply.trailingAnchor.constraint(equalTo: containerReply.trailingAnchor, constant: -20).isActive = true
- contentReply.text = "📄 " + "Seminar".localized()
- }
- contentReply.textColor = .white.withAlphaComponent(0.8)
-
- if (attachment_flag == "1" || attachment_flag == "2" || image_chat != "" || video_chat != "") {
- let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
- let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
- let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
- if let dirPath = paths.first {
- let thumbURL = URL(fileURLWithPath: dirPath).appendingPathComponent(thumb_chat)
- let image = UIImage(contentsOfFile: thumbURL.path)
- let imageThumb = UIImageView(image: image)
- containerReply.addSubview(imageThumb)
- imageThumb.layer.cornerRadius = 2.0
- imageThumb.clipsToBounds = true
- imageThumb.contentMode = .scaleAspectFill
- imageThumb.translatesAutoresizingMaskIntoConstraints = false
- imageThumb.trailingAnchor.constraint(equalTo: containerReply.trailingAnchor, constant: -10).isActive = true
- imageThumb.centerYAnchor.constraint(equalTo: containerReply.centerYAnchor).isActive = true
- imageThumb.widthAnchor.constraint(equalToConstant: 30).isActive = true
- imageThumb.heightAnchor.constraint(equalToConstant: 30).isActive = true
-
- if (attachment_flag == "2") {
- let imagePlay = UIImageView(image: UIImage(systemName: "play.circle.fill"))
- imageThumb.addSubview(imagePlay)
- imagePlay.clipsToBounds = true
- imagePlay.translatesAutoresizingMaskIntoConstraints = false
- imagePlay.centerYAnchor.constraint(equalTo: imageThumb.centerYAnchor).isActive = true
- imagePlay.centerXAnchor.constraint(equalTo: imageThumb.centerXAnchor).isActive = true
- imagePlay.widthAnchor.constraint(equalToConstant: 10).isActive = true
- imagePlay.heightAnchor.constraint(equalToConstant: 10).isActive = true
- imagePlay.tintColor = .white
- }
- titleReply.trailingAnchor.constraint(equalTo: imageThumb.leadingAnchor, constant: -20).isActive = true
- contentReply.trailingAnchor.constraint(equalTo: imageThumb.leadingAnchor, constant: -20).isActive = true
- }
- }
- if (attachment_flag == "11") {
- let imageSticker = UIImageView(image: UIImage(named: (message_text.components(separatedBy: "/")[1]), in: Bundle.resourceBundle(for: Nexilis.self), with: nil))
- containerReply.addSubview(imageSticker)
- imageSticker.layer.cornerRadius = 2.0
- imageSticker.clipsToBounds = true
- imageSticker.translatesAutoresizingMaskIntoConstraints = false
- imageSticker.trailingAnchor.constraint(equalTo: containerReply.trailingAnchor, constant: -10).isActive = true
- imageSticker.centerYAnchor.constraint(equalTo: containerReply.centerYAnchor).isActive = true
- imageSticker.widthAnchor.constraint(equalToConstant: 30).isActive = true
- imageSticker.heightAnchor.constraint(equalToConstant: 30).isActive = true
- titleReply.trailingAnchor.constraint(equalTo: imageSticker.leadingAnchor, constant: -20).isActive = true
- contentReply.trailingAnchor.constraint(equalTo: imageSticker.leadingAnchor, constant: -20).isActive = true
- }
-
- if !copySession && !forwardSession && !deleteSession {
- let objectTap = ObjectGesture(target: self, action: #selector(contentMessageTapped(_:)))
- containerReply.addGestureRecognizer(objectTap)
- objectTap.indexPath = indexPath
- objectTap.message_id = data["message_id"] as! String
- }
- }
- }
-
- return cellMessage
- }
-
- @objc func tapAck(_ sender: ObjectGesture) {
- let indexPath = sender.indexPath
- let dataMessages = self.dataMessages.filter({ $0["chat_date"] as! String == dataDates[indexPath.section]})
- if dataMessages[indexPath.row]["status"] as! String == "8" {
- return
- }
- if !CheckConnection.isConnectedToNetwork() || API.nGetCLXConnState() == 0 {
- let imageView = UIImageView(image: UIImage(systemName: "xmark.circle.fill"))
- imageView.tintColor = .white
- 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)
- banner.show()
- return
- }
- DispatchQueue.global().async {
- var opposite_pin = self.dataGroup["group_id"] as! String
- if (self.dataTopic["chat_id"] as! String != "") {
- opposite_pin = self.dataTopic["chat_id"] as! String
- }
- 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: ""))
- if result != nil {
- Database.shared.database?.inTransaction({ (fmdb, rollback) in
- _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE", cvalues: [
- "status" : "8"
- ], _where: "message_id = '\(dataMessages[indexPath.row]["message_id"] as! String)'")
- })
- DispatchQueue.main.async {
- if let index = self.dataMessages.firstIndex(where: {$0["message_id"] as? String == dataMessages[indexPath.row]["message_id"] as? String}) {
- self.dataMessages[index]["status"] = "8"
- let section = self.dataDates.firstIndex(of: self.dataMessages[index]["chat_date"] as! String)
- 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})
- if row != nil && section != nil {
- self.tableChatView.reloadRows(at: [IndexPath(row: row!, section: section!)], with: .none)
- }
- self.showToast(message: "Confirmation Success.".localized(), font: UIFont.systemFont(ofSize: 12, weight: .medium), controller: self)
- }
- }
- }
- }
- }
-
- @objc func contentMessageTapped(_ sender: ObjectGesture) {
- let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
- let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
- let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
- if (sender.image_id != "") {
- if let dirPath = paths.first {
- let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(sender.image_id)
- if FileManager.default.fileExists(atPath: imageURL.path) {
- let image = UIImage(contentsOfFile: imageURL.path)
- let previewImageVC = PreviewAttachmentImageVideo(nibName: "PreviewAttachmentImageVideo", bundle: Bundle.resourceBundle(for: Nexilis.self))
- previewImageVC.image = image
- previewImageVC.isHiddenTextField = true
- previewImageVC.modalPresentationStyle = .custom
- previewImageVC.modalTransitionStyle = .crossDissolve
- self.present(previewImageVC, animated: true, completion: nil)
- } else {
- for view in sender.imageView.subviews {
- if view is UIImageView {
- view.removeFromSuperview()
- }
- }
- let activityIndicator = UIActivityIndicatorView(style: .large)
- activityIndicator.color = .mainColor
- activityIndicator.hidesWhenStopped = true
- activityIndicator.center = CGPoint(x:sender.imageView.frame.width/2,
- y: sender.imageView.frame.height/2)
- activityIndicator.startAnimating()
- sender.imageView.addSubview(activityIndicator)
- Download().start(forKey: sender.image_id) { (name, progress) in
- guard progress == 100 else {
- return
- }
-
- let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(sender.image_id)
- let image = UIImage(contentsOfFile: imageURL.path)
- let save = UserDefaults.standard.bool(forKey: "saveToGallery")
- if save {
- UIImageWriteToSavedPhotosAlbum(image!, nil, nil, nil)
- }
-
- DispatchQueue.main.async {
- activityIndicator.stopAnimating()
- self.tableChatView.reloadRows(at: [sender.indexPath], with: .none)
- }
- }
- }
- }
- } else if (sender.video_id != "") {
- if let dirPath = paths.first {
- let videoURL = URL(fileURLWithPath: dirPath).appendingPathComponent(sender.video_id)
- if FileManager.default.fileExists(atPath: videoURL.path) {
- let player = AVPlayer(url: videoURL as URL)
- let playerVC = AVPlayerViewController()
- playerVC.modalPresentationStyle = .custom
- playerVC.player = player
- self.present(playerVC, animated: true, completion: nil)
- } else {
- for view in sender.imageView.subviews {
- if view is UIImageView {
- view.removeFromSuperview()
- }
- }
- let container = UIView()
- sender.imageView.addSubview(container)
- container.translatesAutoresizingMaskIntoConstraints = false
- container.centerXAnchor.constraint(equalTo: sender.imageView.centerXAnchor).isActive = true
- container.centerYAnchor.constraint(equalTo: sender.imageView.centerYAnchor).isActive = true
- container.widthAnchor.constraint(equalToConstant: 50).isActive = true
- container.heightAnchor.constraint(equalToConstant: 50).isActive = true
- let circlePath = UIBezierPath(arcCenter: CGPoint(x: 25, y: 25), radius: 20, startAngle: -(.pi / 2), endAngle: .pi * 2, clockwise: true)
- let trackShape = CAShapeLayer()
- trackShape.path = circlePath.cgPath
- trackShape.fillColor = UIColor.clear.cgColor
- trackShape.lineWidth = 10
- trackShape.strokeColor = UIColor.blueBubbleColor.withAlphaComponent(0.3).cgColor
- container.backgroundColor = .clear
- container.layer.addSublayer(trackShape)
- let shapeLoading = CAShapeLayer()
- shapeLoading.path = circlePath.cgPath
- shapeLoading.fillColor = UIColor.clear.cgColor
- shapeLoading.lineWidth = 10
- shapeLoading.strokeEnd = 0
- shapeLoading.strokeColor = UIColor.blueBubbleColor.cgColor
- container.layer.addSublayer(shapeLoading)
- let imageDownload = UIImageView(image: UIImage(systemName: "arrow.down", withConfiguration: UIImage.SymbolConfiguration(pointSize: 10, weight: .bold, scale: .default)))
- imageDownload.tintColor = .white
- container.addSubview(imageDownload)
- imageDownload.translatesAutoresizingMaskIntoConstraints = false
- imageDownload.centerXAnchor.constraint(equalTo: sender.imageView.centerXAnchor).isActive = true
- imageDownload.centerYAnchor.constraint(equalTo: sender.imageView.centerYAnchor).isActive = true
- imageDownload.widthAnchor.constraint(equalToConstant: 30).isActive = true
- imageDownload.heightAnchor.constraint(equalToConstant: 30).isActive = true
- Download().start(forKey: sender.video_id) { (name, progress) in
- DispatchQueue.main.async {
- guard progress == 100 else {
- shapeLoading.strokeEnd = CGFloat(progress / 100)
- return
- }
- let save = UserDefaults.standard.bool(forKey: "saveToGallery")
- if save {
- let videoURL = URL(fileURLWithPath: dirPath).appendingPathComponent(sender.video_id)
- PHPhotoLibrary.shared().performChanges({
- PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: videoURL)
- }) { saved, error in
-
- }
- }
- let idx = self.dataMessages.firstIndex(where: { $0["video_id"] as! String == sender.video_id})
- if idx != nil {
- self.dataMessages[idx!]["progress"] = progress
- self.tableChatView.reloadRows(at: [sender.indexPath], with: .none)
- }
- }
- }
- }
- }
- } else if (sender.file_id != "") {
- if let dirPath = paths.first {
- let fileURL = URL(fileURLWithPath: dirPath).appendingPathComponent(sender.file_id)
- if FileManager.default.fileExists(atPath: fileURL.path) {
- self.previewItem = fileURL as NSURL
- let previewController = QLPreviewController()
- let rightBarButton = UIBarButtonItem()
- previewController.navigationItem.rightBarButtonItem = rightBarButton
- previewController.dataSource = self
- previewController.modalPresentationStyle = .custom
-
- self.show(previewController, sender: nil)
- } else {
- for view in sender.containerFile.subviews {
- if !(view is UIImageView) && !(view is UILabel) {
- view.removeFromSuperview()
- }
- }
- let containerLoading = UIView()
- sender.containerFile.addSubview(containerLoading)
- containerLoading.translatesAutoresizingMaskIntoConstraints = false
- containerLoading.centerYAnchor.constraint(equalTo: sender.containerFile.centerYAnchor).isActive = true
- containerLoading.leadingAnchor.constraint(equalTo: sender.labelFile.trailingAnchor, constant: 5).isActive = true
- containerLoading.trailingAnchor.constraint(equalTo: sender.containerFile.trailingAnchor, constant: -5).isActive = true
- containerLoading.widthAnchor.constraint(equalToConstant: 30).isActive = true
- containerLoading.heightAnchor.constraint(equalToConstant: 30).isActive = true
- let circlePath = UIBezierPath(arcCenter: CGPoint(x: 15, y: 15), radius: 10, startAngle: -(.pi / 2), endAngle: .pi * 2, clockwise: true)
- let trackShape = CAShapeLayer()
- trackShape.path = circlePath.cgPath
- trackShape.fillColor = UIColor.clear.cgColor
- trackShape.lineWidth = 5
- trackShape.strokeColor = UIColor.blueBubbleColor.withAlphaComponent(0.3).cgColor
- containerLoading.layer.addSublayer(trackShape)
- let shapeLoading = CAShapeLayer()
- shapeLoading.path = circlePath.cgPath
- shapeLoading.fillColor = UIColor.clear.cgColor
- shapeLoading.lineWidth = 3
- shapeLoading.strokeEnd = 0
- shapeLoading.strokeColor = UIColor.blueBubbleColor.cgColor
- containerLoading.layer.addSublayer(shapeLoading)
- let imageupload = UIImageView(image: UIImage(systemName: "arrow.down", withConfiguration: UIImage.SymbolConfiguration(pointSize: 10, weight: .bold, scale: .default)))
- imageupload.tintColor = .white
- containerLoading.addSubview(imageupload)
- imageupload.translatesAutoresizingMaskIntoConstraints = false
- imageupload.centerYAnchor.constraint(equalTo: containerLoading.centerYAnchor).isActive = true
- imageupload.centerXAnchor.constraint(equalTo: containerLoading.centerXAnchor).isActive = true
-
- Download().start(forKey: sender.file_id) { (name, progress) in
- DispatchQueue.main.async {
- guard progress == 100 else {
- shapeLoading.strokeEnd = CGFloat(progress / 100)
- return
- }
- let idx = self.dataMessages.firstIndex(where: { $0["file_id"] as! String == sender.file_id})
- if idx != nil {
- self.dataMessages[idx!]["progress"] = progress
- self.tableChatView.reloadRows(at: [sender.indexPath], with: .none)
- }
- }
- }
- }
- }
- } else {
- DispatchQueue.main.async {
- let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as! String == sender.message_id})
- if idx == nil {
- return
- }
- let section = self.dataDates.firstIndex(of: self.dataMessages[idx!]["chat_date"] as! String)
- if section == nil {
- return
- }
- 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})
- if row == nil {
- return
- }
- let indexPath = IndexPath(row: row!, section: section!)
- self.tableChatView.scrollToRow(at: indexPath, at: .middle, animated: true)
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
- if let cell = self.tableChatView.cellForRow(at: indexPath) {
- let containerMessage = cell.contentView.subviews[1]
- let idMe = UserDefaults.standard.string(forKey: "me") as String?
- if (self.dataMessages[idx!]["f_pin"] as? String == idMe) {
- containerMessage.backgroundColor = .blueBubbleColor.withAlphaComponent(0.3)
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
- if (self.dataMessages[idx!]["attachment_flag"] as? String == "11") {
- containerMessage.backgroundColor = .clear
- } else {
- containerMessage.backgroundColor = .blueBubbleColor
- }
- }
- } else {
- containerMessage.backgroundColor = .grayColor.withAlphaComponent(0.3)
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
- if (self.dataMessages[idx!]["attachment_flag"] as? String == "11") {
- containerMessage.backgroundColor = .clear
- } else {
- containerMessage.backgroundColor = .grayColor
- }
- }
- }
- }
- }
- }
- }
- }
-
- @objc func handleLongPressLink(_ gestureRecognizer: UILongPressGestureRecognizer) {
- func showMenuContext() {
- if gestureRecognizer.state == .cancelled || gestureRecognizer.state == .ended{
- timerCheckLink?.invalidate()
- } else if gestureRecognizer.state == .began {
- timerCheckLink = Timer.scheduledTimer(withTimeInterval: 0.2, repeats: false, block: {_ in
- let interaction = UIContextMenuInteraction(delegate: self)
- gestureRecognizer.view!.addInteraction(interaction)
- guard let interaction = gestureRecognizer.view!.interactions.first,
- let data = Data(base64Encoded: "X3ByZXNlbnRNZW51QXRMb2NhdGlvbjo="),
- let str = String(data: data, encoding: .utf8)
- else {
- return
- }
- let selector = NSSelectorFromString(str)
- guard interaction.responds(to: selector) else {
- return
- }
- let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
- impactHeavy.impactOccurred()
- interaction.perform(selector, with: self.view)
- self.isLinkCopied = true
- })
- }
- }
- if gestureRecognizer.state == .began {
- let touchPoint = gestureRecognizer.location(in: self.view)
- touchedSubview = self.view.hitTest(touchPoint, with: nil) ?? UIView()
- if !(touchedSubview is UILabel) {
- showMenuContext()
- }
- }
- guard let label = touchedSubview as? UILabel else { return }
- let touchPointLabel = gestureRecognizer.location(in: label)
- if let text = label.text, let range = getWordRange(at: touchPointLabel, in: label) {
- let word = String(text[range])
- if word.starts(with: "www.") || word.starts(with: "https://") || word.starts(with: "http://") {
- if gestureRecognizer.state == .cancelled || gestureRecognizer.state == .ended{
- timerCheckLink?.invalidate()
- if !isLinkCopied {
- var stringURl = word
- if stringURl.starts(with: "www.") {
- stringURl = "https://" + stringURl.replacingOccurrences(of: "www.", with: "")
- }
- guard let url = URL(string: stringURl) else { return }
- UIApplication.shared.open(url)
- label.attributedText = removeHighlightedText(for: text, in: range, label: label)
- }
- isLinkCopied = false
- } else if gestureRecognizer.state == .began {
- label.attributedText = highlightedText(for: text, in: range, label: label)
- timerCheckLink = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false, block: {_ in
- self.isLinkCopied = true
- UIPasteboard.general.string = word
- self.showToast(message: "Link Copied".localized(), font: UIFont.systemFont(ofSize: 12, weight: .medium), controller: self)
- label.attributedText = self.removeHighlightedText(for: text, in: range, label: label)
- self.timerCheckLink?.invalidate()
- })
- }
- } else {
- showMenuContext()
- }
- } else {
- showMenuContext()
- }
- }
-
- func getWordRange(at point: CGPoint, in label: UILabel) -> Range<String.Index>? {
- guard let text = label.text else { return nil }
-
- let layoutManager = NSLayoutManager()
- let textContainer = NSTextContainer(size: label.frame.size)
- let textStorage = NSTextStorage(attributedString: NSAttributedString(string: text))
-
- layoutManager.addTextContainer(textContainer)
- textStorage.addLayoutManager(layoutManager)
- textContainer.lineFragmentPadding = 0
- textContainer.maximumNumberOfLines = label.numberOfLines
-
- lastTouchPoint = point
- let characterIndex = layoutManager.characterIndex(for: point, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
-
- if characterIndex == text.count - 1 {
- return nil
- }
- var wordStartIndex = characterIndex
- while wordStartIndex > 0 && text[text.index(text.startIndex, offsetBy: wordStartIndex - 1)] != " " && text[text.index(text.startIndex, offsetBy: wordStartIndex - 1)] != "\n" {
- wordStartIndex -= 1
- }
-
- var wordEndIndex = characterIndex
- while wordEndIndex < text.count && text[text.index(text.startIndex, offsetBy: wordEndIndex)] != " " && text[text.index(text.startIndex, offsetBy: wordEndIndex)] != "\n" {
- wordEndIndex += 1
- }
-
- return text.index(text.startIndex, offsetBy: wordStartIndex)..<text.index(text.startIndex, offsetBy: wordEndIndex)
- }
- func highlightedText(for text: String, in range: Range<String.Index>, label: UILabel) -> NSAttributedString {
- let mutableAttributedString = label.attributedText!.mutableCopy() as! NSMutableAttributedString
- mutableAttributedString.addAttribute(.backgroundColor, value: UIColor.lightGray.withAlphaComponent(0.5), range: NSRange(range, in: text))
- return mutableAttributedString
- }
-
- func removeHighlightedText(for text: String, in range: Range<String.Index>, label: UILabel) -> NSAttributedString {
- let mutableAttributedString = label.attributedText!.mutableCopy() as! NSMutableAttributedString
- mutableAttributedString.removeAttribute(.backgroundColor, range: NSRange(range, in: text))
- return mutableAttributedString
- }
-
- @objc func tapMessageText(_ sender: ObjectGesture) {
- var stringURl = sender.message_id.lowercased()
- if stringURl.starts(with: "www.") {
- stringURl = "https://" + stringURl.replacingOccurrences(of: "www.", with: "")
- }
- guard let url = URL(string: stringURl) else { return }
- UIApplication.shared.open(url)
- }
-
- // public func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
- // if copySession || forwardSession || deleteSession {
- // return nil
- // }
- // let idMe = UserDefaults.standard.string(forKey: "me") as String?
- // if (dataMessages[indexPath.row]["f_pin"] as? String != idMe) {
- // return nil
- // }
- // let messageInfoVC = MessageInfo()
- // self.navigationController?.show(messageInfoVC, sender: nil)
- // return UISwipeActionsConfiguration()
- // }
- //
- // public func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
- // if copySession || forwardSession || deleteSession {
- // return nil
- // }
- // let action = UIContextualAction(style: .normal,
- // title: "") { [weak self] (action, view, completionHandler) in
- // self?.handleReply(indexPath: indexPath)
- // completionHandler(true)
- // }
- // action.backgroundColor = .white
- // action.image = UIImage(systemName: "arrowshape.turn.up.left.fill")?.withTintColor(.black, renderingMode: .alwaysOriginal)
- // return UISwipeActionsConfiguration(actions: [action])
- // }
-
- private func handleReply(indexPath: IndexPath) {
- self.deleteReplyView()
- self.textFieldSend.becomeFirstResponder()
- self.reffId = dataMessages[indexPath.row]["message_id"] as? String
- UIView.animate(withDuration: 0.25, delay: 0.0, options: .curveEaseInOut, animations: {
- self.constraintTopTextField.constant = self.constraintTopTextField.constant + 50
- if self.contraintBottomMention.constant > 0 {
- self.contraintBottomMention.constant = self.contraintBottomMention.constant + 50
- }
- }, completion: nil)
- if (self.currentIndexpath != nil) {
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
- self.tableChatView.scrollToRow(at: IndexPath(row: self.currentIndexpath!.row, section: self.currentIndexpath!.section), at: .none, animated: false)
- }
- } else {
- self.tableChatView.scrollToBottom()
- }
-
- self.viewTextfield.addSubview(self.containerPreviewReply)
- self.containerPreviewReply.translatesAutoresizingMaskIntoConstraints = false
- self.containerPreviewReply.leadingAnchor.constraint(equalTo: self.viewTextfield.leadingAnchor).isActive = true
- self.containerPreviewReply.topAnchor.constraint(equalTo: self.viewTextfield.topAnchor).isActive = true
- if !self.containerLink.isDescendant(of: self.viewTextfield) {
- self.bottomAnchorPreviewReply = self.containerPreviewReply.bottomAnchor.constraint(equalTo: self.textFieldSend.topAnchor)
- } else {
- self.bottomAnchorPreviewReply = self.containerPreviewReply.bottomAnchor.constraint(equalTo: self.containerLink.topAnchor)
- }
- self.bottomAnchorPreviewReply.isActive = true
- self.containerPreviewReply.trailingAnchor.constraint(equalTo: self.viewTextfield.trailingAnchor).isActive = true
- self.containerPreviewReply.backgroundColor = .secondaryColor
-
- let leftReply = UIView()
- self.containerPreviewReply.addSubview(leftReply)
- leftReply.translatesAutoresizingMaskIntoConstraints = false
- leftReply.leadingAnchor.constraint(equalTo: self.viewTextfield.leadingAnchor).isActive = true
- leftReply.topAnchor.constraint(equalTo: self.containerPreviewReply.topAnchor).isActive = true
- leftReply.bottomAnchor.constraint(equalTo: self.containerPreviewReply.bottomAnchor).isActive = true
- leftReply.widthAnchor.constraint(equalToConstant: 3).isActive = true
- leftReply.backgroundColor = .orangeColor
-
- let titleReply = UILabel()
- self.containerPreviewReply.addSubview(titleReply)
- titleReply.translatesAutoresizingMaskIntoConstraints = false
- titleReply.leadingAnchor.constraint(equalTo: leftReply.leadingAnchor, constant: 10).isActive = true
- titleReply.topAnchor.constraint(equalTo: self.containerPreviewReply.topAnchor, constant: 10).isActive = true
- titleReply.font = UIFont.systemFont(ofSize: 12).bold
- let idMe = UserDefaults.standard.string(forKey: "me") as String?
- if (dataMessages[indexPath.row]["f_pin"] as? String == idMe) {
- titleReply.text = "You".localized()
- } else {
- if dataMessages[indexPath.row]["f_pin"] as? String != "-999" {
- let dataPerson = self.getDataProfile(f_pin: dataMessages[indexPath.row]["f_pin"] as! String, message_id: dataMessages[indexPath.row]["message_id"] as! String)
- titleReply.text = dataPerson["name"]
- } else {
- titleReply.text = "Bot"
- }
- }
- titleReply.textColor = .orangeColor
-
- let contentReply = UILabel()
- self.containerPreviewReply.addSubview(contentReply)
- contentReply.translatesAutoresizingMaskIntoConstraints = false
- contentReply.leadingAnchor.constraint(equalTo: leftReply.leadingAnchor, constant: 10).isActive = true
- contentReply.topAnchor.constraint(equalTo: titleReply.bottomAnchor).isActive = true
- contentReply.font = UIFont.systemFont(ofSize: 10)
- let message_text = dataMessages[indexPath.row]["message_text"] as! String
- let attachment_flag = dataMessages[indexPath.row]["attachment_flag"] as! String
- let thumb_chat = dataMessages[indexPath.row]["thumb_id"] as! String
- let image_chat = dataMessages[indexPath.row]["image_id"] as! String
- let video_chat = dataMessages[indexPath.row]["video_id"] as! String
- let file_chat = dataMessages[indexPath.row]["file_id"] as! String
- if (attachment_flag == "0" && thumb_chat == "") {
- contentReply.attributedText = message_text.richText(group_id: self.dataGroup["group_id"] as! String)
- } else if (attachment_flag == "1" || image_chat != "") {
- if (message_text == "") {
- contentReply.text = "📷 Photo".localized()
- } else {
- contentReply.attributedText = message_text.richText(group_id: self.dataGroup["group_id"] as! String)
- }
- } else if (attachment_flag == "2" || video_chat != "") {
- if (message_text == "") {
- contentReply.text = "📹 Video".localized()
- } else {
- contentReply.attributedText = message_text.richText(group_id: self.dataGroup["group_id"] as! String)
- }
- } else if (attachment_flag == "6" || file_chat != ""){
- contentReply.text = "📄 \(message_text.components(separatedBy: "|")[0])"
- } else if (attachment_flag == "11") {
- contentReply.text = "❤️ Sticker"
- } else if attachment_flag == "27" {
- contentReply.text = "📄 " + "Live Streaming".localized()
- } else if attachment_flag == "26" {
- contentReply.text = "📄 " + "Seminar".localized()
- }
- contentReply.textColor = .gray
-
- let buttonCancelReply = UIButton(type: .custom)
- self.containerPreviewReply.addSubview(buttonCancelReply)
- buttonCancelReply.translatesAutoresizingMaskIntoConstraints = false
- buttonCancelReply.trailingAnchor.constraint(equalTo: self.containerPreviewReply.trailingAnchor, constant: -10).isActive = true
- buttonCancelReply.centerYAnchor.constraint(equalTo: self.containerPreviewReply.centerYAnchor).isActive = true
- buttonCancelReply.setImage(UIImage(systemName: "xmark.circle" , withConfiguration: UIImage.SymbolConfiguration(pointSize: 20, weight: .regular, scale: .default)), for: .normal)
- buttonCancelReply.addTarget(nil, action: #selector(self.deleteReplyView), for: .touchUpInside)
- buttonCancelReply.backgroundColor = .clear
- buttonCancelReply.tintColor = .mainColor
-
- if (attachment_flag == "1" || attachment_flag == "2" || image_chat != "" || video_chat != "") {
- let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
- let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
- let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
- if let dirPath = paths.first {
- let thumbURL = URL(fileURLWithPath: dirPath).appendingPathComponent(thumb_chat)
- let image = UIImage(contentsOfFile: thumbURL.path)
- let imageThumb = UIImageView(image: image)
- self.containerPreviewReply.addSubview(imageThumb)
- imageThumb.layer.cornerRadius = 2.0
- imageThumb.clipsToBounds = true
- imageThumb.translatesAutoresizingMaskIntoConstraints = false
- imageThumb.trailingAnchor.constraint(equalTo: buttonCancelReply.leadingAnchor, constant: -10).isActive = true
- imageThumb.centerYAnchor.constraint(equalTo: self.containerPreviewReply.centerYAnchor).isActive = true
- imageThumb.widthAnchor.constraint(equalToConstant: 30).isActive = true
- imageThumb.heightAnchor.constraint(equalToConstant: 30).isActive = true
-
- if (attachment_flag == "2") {
- let imagePlay = UIImageView(image: UIImage(systemName: "play.circle.fill"))
- imageThumb.addSubview(imagePlay)
- imagePlay.clipsToBounds = true
- imagePlay.translatesAutoresizingMaskIntoConstraints = false
- imagePlay.centerYAnchor.constraint(equalTo: imageThumb.centerYAnchor).isActive = true
- imagePlay.centerXAnchor.constraint(equalTo: imageThumb.centerXAnchor).isActive = true
- imagePlay.widthAnchor.constraint(equalToConstant: 10).isActive = true
- imagePlay.heightAnchor.constraint(equalToConstant: 10).isActive = true
- imagePlay.tintColor = .white
- }
- }
- }
- if (attachment_flag == "11") {
- let imageSticker = UIImageView(image: UIImage(named: (message_text.components(separatedBy: "/")[1]), in: Bundle.resourceBundle(for: Nexilis.self), with: nil))
- self.containerPreviewReply.addSubview(imageSticker)
- imageSticker.layer.cornerRadius = 2.0
- imageSticker.clipsToBounds = true
- imageSticker.translatesAutoresizingMaskIntoConstraints = false
- imageSticker.trailingAnchor.constraint(equalTo: buttonCancelReply.leadingAnchor, constant: -10).isActive = true
- imageSticker.centerYAnchor.constraint(equalTo: self.containerPreviewReply.centerYAnchor).isActive = true
- imageSticker.widthAnchor.constraint(equalToConstant: 30).isActive = true
- imageSticker.heightAnchor.constraint(equalToConstant: 30).isActive = true
- }
- }
-
- func scrollToFirstSearchMessage(indexScroll: Int = 1) {
- if textSearch.count < 2 {
- return
- }
- var lastIndex = 0
- let messageTextForSearch: [[String: Any?]] = self.dataMessages.reversed()
- for idx in 0..<messageTextForSearch.count {
- if (messageTextForSearch[idx]["message_text"] as! String).lowercased().contains(textSearch) {
- lastIndex += 1
- if lastIndex < indexScroll {
- continue
- }
- lastScrollIdxSearch = lastIndex
- let section = self.dataDates.firstIndex(of: messageTextForSearch[idx]["chat_date"] as! String)
- if section == nil {
- return
- }
- 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})
- if row == nil {
- return
- }
- let indexPath = IndexPath(row: row!, section: section!)
- self.tableChatView.scrollToRow(at: indexPath, at: .middle, animated: true)
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
- if let cell = self.tableChatView.cellForRow(at: indexPath) {
- let containerMessage = cell.contentView.subviews[1]
- let idMe = UserDefaults.standard.string(forKey: "me") as String?
- if (messageTextForSearch[idx]["f_pin"] as? String == idMe) {
- containerMessage.backgroundColor = .blueBubbleColor.withAlphaComponent(0.3)
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
- if (messageTextForSearch[idx]["attachment_flag"] as? String == "11") {
- containerMessage.backgroundColor = .clear
- } else {
- containerMessage.backgroundColor = .blueBubbleColor
- }
- }
- } else {
- containerMessage.backgroundColor = .grayColor.withAlphaComponent(0.3)
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
- if (messageTextForSearch[idx]["attachment_flag"] as? String == "11") {
- containerMessage.backgroundColor = .clear
- } else {
- containerMessage.backgroundColor = .grayColor
- }
- }
- }
- }
- }
- titleSearchMatches.isHidden = false
- if countMatchesSearch != 0 {
- if countMatchesSearch > 1 {
- titleSearchMatches.text = "\(lastScrollIdxSearch) " + "of".localized() + " \(countMatchesSearch) " + "matches".localized()
- } else {
- titleSearchMatches.text = "\(countMatchesSearch) " + "matches".localized()
- }
- } else {
- titleSearchMatches.text = "Not found".localized()
- }
- if lastScrollIdxSearch == countMatchesSearch || countMatchesSearch == 0 {
- buttonUp.isEnabled = false
- buttonUp.tintColor = .gray
- } else {
- buttonUp.isEnabled = true
- buttonUp.tintColor = .mainColor
- }
- if countMatchesSearch == 0 || lastScrollIdxSearch == 1 || countMatchesSearch == 1 {
- buttonDown.isEnabled = false
- buttonDown.tintColor = .gray
- } else {
- buttonDown.isEnabled = true
- buttonDown.tintColor = .mainColor
- }
- break
- }
- }
- }
-
- public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
- let indexPath = tableChatView.indexPathsForVisibleRows?.first
- if indexPath != nil {
- let headerRect = tableChatView.rectForHeader(inSection: indexPath!.section)
- let isPinned = headerRect.origin.y <= scrollView.contentOffset.y
- if listViewOnSection.count != 0 && listViewOnSection.count - 1 <= indexPath!.section && indexPath!.row > 0 {
- let headerView = listViewOnSection[currentIndexpath!.section]
- headerView.isHidden = true
- }
- }
- }
-
- public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
- if !decelerate {
- let indexPath = tableChatView.indexPathsForVisibleRows?.first
- if indexPath != nil {
- let headerRect = tableChatView.rectForHeader(inSection: indexPath!.section)
- let isPinned = headerRect.origin.y <= scrollView.contentOffset.y
- if listViewOnSection.count != 0 && listViewOnSection.count - 1 <= indexPath!.section && isPinned {
- let headerView = listViewOnSection[currentIndexpath!.section]
- headerView.isHidden = true
- }
- }
- }
- }
- }
- extension EditorGroup: UISearchBarDelegate {
-
- public func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
- textSearch = searchText.trimmingCharacters(in: .whitespacesAndNewlines)
- countMatchesSearch = 0
- titleSearchMatches.isHidden = true
- tableChatView.reloadData()
- scrollToFirstSearchMessage()
- }
- }
|