2
0

WFCCIMService.mm 199 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651
  1. //
  2. // WFCCIMService.mm
  3. // WFChatClient
  4. //
  5. // Created by heavyrain on 2017/11/5.
  6. // Copyright © 2017年 WildFireChat. All rights reserved.
  7. //
  8. #import "WFCCIMService.h"
  9. #import "WFCCMediaMessageContent.h"
  10. #import <proto/MessageDB.h>
  11. #import <objc/runtime.h>
  12. #import "WFCCNetworkService.h"
  13. #import <app/app.h>
  14. #import "WFCCGroupSearchInfo.h"
  15. #import "WFCCUnknownMessageContent.h"
  16. #import "WFCCRecallMessageContent.h"
  17. #import "WFCCMarkUnreadMessageContent.h"
  18. #import "wav_amr.h"
  19. #import "WFCCUserOnlineState.h"
  20. #import "WFAFNetworking.h"
  21. #import "WFCCRawMessageContent.h"
  22. #import "WFCCTextMessageContent.h"
  23. #import "WFCCFileMessageContent.h"
  24. #import "WFCCNetworkService.h"
  25. #import <MobileCoreServices/MobileCoreServices.h>
  26. NSString *kSendingMessageStatusUpdated = @"kSendingMessageStatusUpdated";
  27. NSString *kUploadMediaMessageProgresse = @"kUploadMediaMessageProgresse";
  28. NSString *kConnectionStatusChanged = @"kConnectionStatusChanged";
  29. NSString *kReceiveMessages = @"kReceiveMessages";
  30. NSString *kRecallMessages = @"kRecallMessages";
  31. NSString *kDeleteMessages = @"kDeleteMessages";
  32. NSString *kMessageDelivered = @"kMessageDelivered";
  33. NSString *kMessageReaded = @"kMessageReaded";
  34. NSString *kMessageUpdated = @"kMessageUpdated";
  35. class IMSendMessageCallback : public mars::stn::SendMsgCallback {
  36. public:
  37. void(^m_successBlock)(long long messageUid, long long timestamp);
  38. void(^m_errorBlock)(int error_code);
  39. void(^m_progressBlock)(long uploaded, long total);
  40. void(^m_uploadedBlock)(NSString *remoteUrl);
  41. WFCCMessage *m_message;
  42. IMSendMessageCallback(WFCCMessage *message, void(^successBlock)(long long messageUid, long long timestamp), void(^progressBlock)(long uploaded, long total), void(^uploadedBlock)(NSString *remoteUrl), void(^errorBlock)(int error_code)) : mars::stn::SendMsgCallback(), m_message(message), m_successBlock(successBlock), m_progressBlock(progressBlock), m_errorBlock(errorBlock), m_uploadedBlock(uploadedBlock) {};
  43. void onSuccess(long long messageUid, long long timestamp) {
  44. dispatch_async(dispatch_get_main_queue(), ^{
  45. m_message.messageUid = messageUid;
  46. m_message.serverTime = timestamp;
  47. m_message.status = Message_Status_Sent;
  48. if (m_successBlock) {
  49. m_successBlock(messageUid, timestamp);
  50. }
  51. if(m_message.messageId) {
  52. [[NSNotificationCenter defaultCenter] postNotificationName:kSendingMessageStatusUpdated object:@(m_message.messageId) userInfo:@{@"status":@(Message_Status_Sent), @"messageUid":@(messageUid), @"timestamp":@(timestamp), @"message":m_message}];
  53. }
  54. delete this;
  55. });
  56. }
  57. void onFalure(int errorCode) {
  58. dispatch_async(dispatch_get_main_queue(), ^{
  59. m_message.status = Message_Status_Send_Failure;
  60. if (m_errorBlock) {
  61. m_errorBlock(errorCode);
  62. }
  63. if(m_message.messageId) {
  64. [[NSNotificationCenter defaultCenter] postNotificationName:kSendingMessageStatusUpdated object:@(m_message.messageId) userInfo:@{@"status":@(Message_Status_Send_Failure), @"message":m_message, @"errorCode":@(errorCode)}];
  65. }
  66. delete this;
  67. });
  68. }
  69. void onPrepared(long messageId, int64_t savedTime) {
  70. m_message.messageId = messageId;
  71. m_message.serverTime = savedTime;
  72. if(messageId) {
  73. dispatch_async(dispatch_get_main_queue(), ^{
  74. [[NSNotificationCenter defaultCenter] postNotificationName:kSendingMessageStatusUpdated object:@(messageId) userInfo:@{@"status":@(Message_Status_Sending), @"message":m_message, @"savedTime":@(savedTime)}];
  75. });
  76. }
  77. }
  78. void onMediaUploaded(const std::string &remoteUrl) {
  79. NSString *ru = [NSString stringWithUTF8String:remoteUrl.c_str()];
  80. if ([m_message.content isKindOfClass:[WFCCMediaMessageContent class]]) {
  81. WFCCMediaMessageContent *mediaContent = (WFCCMediaMessageContent *)m_message.content;
  82. mediaContent.remoteUrl = ru;
  83. }
  84. long messageId = m_message.messageId;
  85. if(messageId) {
  86. if (m_uploadedBlock) {
  87. m_uploadedBlock(ru);
  88. }
  89. [[NSNotificationCenter defaultCenter] postNotificationName:kUploadMediaMessageProgresse object:@(messageId) userInfo:@{@"progress":@(1), @"finish":@(YES), @"message":m_message, @"remoteUrl":ru}];
  90. }
  91. }
  92. void onProgress(int uploaded, int total) {
  93. dispatch_async(dispatch_get_main_queue(), ^{
  94. if (m_progressBlock) {
  95. m_progressBlock(uploaded, total);
  96. }
  97. if(m_message.messageId) {
  98. float progress = (uploaded * 1.f)/total;
  99. [[NSNotificationCenter defaultCenter] postNotificationName:kUploadMediaMessageProgresse object:@(m_message.messageId) userInfo:@{@"progress":@(progress), @"finish":@(NO), @"message":m_message, @"uploaded":@(uploaded), @"total":@(total)}];
  100. }
  101. });
  102. }
  103. virtual ~IMSendMessageCallback() {
  104. m_successBlock = nil;
  105. m_errorBlock = nil;
  106. m_progressBlock = nil;
  107. m_uploadedBlock = nil;
  108. m_message = nil;
  109. }
  110. };
  111. @interface WFCUUploadModel : NSObject <NSURLSessionDelegate> {
  112. @public
  113. IMSendMessageCallback *_sendCallback;
  114. }
  115. @property(nonatomic, strong)NSURLSessionUploadTask *uploadTask;
  116. @property(nonatomic, assign)int fileSize;
  117. @property(nonatomic, assign)int expireDuration;
  118. @end
  119. @implementation WFCUUploadModel
  120. - (void)didUploaded:(NSString *)remoteUrl {
  121. WFCCMediaMessageContent *mediaContent = (WFCCMediaMessageContent *)self->_sendCallback->m_message.content;
  122. mediaContent.remoteUrl = remoteUrl;
  123. [[WFCCIMService sharedWFCIMService] updateMessage:self->_sendCallback->m_message.messageId content:self->_sendCallback->m_message.content];
  124. self->_sendCallback->onMediaUploaded([remoteUrl UTF8String]);
  125. [[WFCCIMService sharedWFCIMService] sendSavedMessage:self->_sendCallback->m_message expireDuration:self.expireDuration success:self->_sendCallback->m_successBlock error:self->_sendCallback->m_errorBlock];
  126. delete self->_sendCallback;
  127. }
  128. - (void)didUploadedFailed:(int)errorCode {
  129. [[WFCCIMService sharedWFCIMService] updateMessage:self->_sendCallback->m_message.messageId status:Message_Status_Send_Failure];
  130. self->_sendCallback->onFalure(errorCode);
  131. }
  132. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
  133. didSendBodyData:(int64_t)bytesSent
  134. totalBytesSent:(int64_t)totalBytesSent
  135. totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend {
  136. dispatch_async(dispatch_get_main_queue(), ^{
  137. float uploadProgress = totalBytesSent * 1.f / self.fileSize;
  138. NSLog(@"upload progress %f", uploadProgress);
  139. self->_sendCallback->onProgress((int)totalBytesSent, self.fileSize);
  140. });
  141. }
  142. @end
  143. @interface WFCUUploaDatadModel : NSObject <NSURLSessionDelegate> {
  144. @public
  145. void(^m_errorBlock)(int error_code);
  146. void(^m_progressBlock)(long uploaded, long total);
  147. void(^m_uploadedBlock)(NSString *remoteUrl);
  148. }
  149. @property(nonatomic, strong)NSURLSessionUploadTask *uploadTask;
  150. @property(nonatomic, assign)int fileSize;
  151. @end
  152. @implementation WFCUUploaDatadModel
  153. - (void)didUploaded:(NSString *)remoteUrl {
  154. if(m_uploadedBlock) {
  155. m_uploadedBlock(remoteUrl);
  156. }
  157. }
  158. - (void)didUploadedFailed:(int)errorCode {
  159. if(m_errorBlock) {
  160. m_errorBlock(errorCode);
  161. }
  162. }
  163. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
  164. didSendBodyData:(int64_t)bytesSent
  165. totalBytesSent:(int64_t)totalBytesSent
  166. totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend {
  167. if(m_progressBlock) {
  168. float uploadProgress = totalBytesSent * 1.f / self.fileSize;
  169. m_progressBlock((int)totalBytesSent, self.fileSize);
  170. }
  171. }
  172. @end
  173. extern WFCCUserInfo* convertUserInfo(const mars::stn::TUserInfo &tui);
  174. class IMCreateGroupCallback : public mars::stn::CreateGroupCallback {
  175. private:
  176. void(^m_successBlock)(NSString *groupId);
  177. void(^m_errorBlock)(int error_code);
  178. public:
  179. IMCreateGroupCallback(void(^successBlock)(NSString *groupId), void(^errorBlock)(int error_code)) : mars::stn::CreateGroupCallback(), m_successBlock(successBlock), m_errorBlock(errorBlock) {};
  180. void onSuccess(const std::string &groupId) {
  181. NSString *nsstr = [NSString stringWithUTF8String:groupId.c_str()];
  182. dispatch_async(dispatch_get_main_queue(), ^{
  183. if (m_successBlock) {
  184. m_successBlock(nsstr);
  185. }
  186. delete this;
  187. });
  188. }
  189. void onFalure(int errorCode) {
  190. dispatch_async(dispatch_get_main_queue(), ^{
  191. if (m_errorBlock) {
  192. m_errorBlock(errorCode);
  193. }
  194. delete this;
  195. });
  196. }
  197. virtual ~IMCreateGroupCallback() {
  198. m_successBlock = nil;
  199. m_errorBlock = nil;
  200. }
  201. };
  202. class IMGeneralOperationCallback : public mars::stn::GeneralOperationCallback {
  203. private:
  204. void(^m_successBlock)();
  205. void(^m_errorBlock)(int error_code);
  206. public:
  207. IMGeneralOperationCallback(void(^successBlock)(), void(^errorBlock)(int error_code)) : mars::stn::GeneralOperationCallback(), m_successBlock(successBlock), m_errorBlock(errorBlock) {};
  208. void onSuccess() {
  209. dispatch_async(dispatch_get_main_queue(), ^{
  210. if (m_successBlock) {
  211. m_successBlock();
  212. }
  213. delete this;
  214. });
  215. }
  216. void onFalure(int errorCode) {
  217. dispatch_async(dispatch_get_main_queue(), ^{
  218. if (m_errorBlock) {
  219. m_errorBlock(errorCode);
  220. }
  221. delete this;
  222. });
  223. }
  224. virtual ~IMGeneralOperationCallback() {
  225. m_successBlock = nil;
  226. m_errorBlock = nil;
  227. }
  228. };
  229. class IMGeneralStringCallback : public mars::stn::GeneralStringCallback {
  230. private:
  231. void(^m_successBlock)(NSString *generalStr);
  232. void(^m_errorBlock)(int error_code);
  233. public:
  234. IMGeneralStringCallback(void(^successBlock)(NSString *groupId), void(^errorBlock)(int error_code)) : mars::stn::GeneralStringCallback(), m_successBlock(successBlock), m_errorBlock(errorBlock) {};
  235. void onSuccess(const std::string &str) {
  236. NSString *nsstr = [NSString stringWithUTF8String:str.c_str()];
  237. dispatch_async(dispatch_get_main_queue(), ^{
  238. if (m_successBlock) {
  239. m_successBlock(nsstr);
  240. }
  241. delete this;
  242. });
  243. }
  244. void onFalure(int errorCode) {
  245. dispatch_async(dispatch_get_main_queue(), ^{
  246. if (m_errorBlock) {
  247. m_errorBlock(errorCode);
  248. }
  249. delete this;
  250. });
  251. }
  252. virtual ~IMGeneralStringCallback() {
  253. m_successBlock = nil;
  254. m_errorBlock = nil;
  255. }
  256. };
  257. class IMGeneralStringListCallback : public mars::stn::GeneralStringListCallback {
  258. private:
  259. void(^m_successBlock)(NSArray<NSString *> *stringArray);
  260. void(^m_errorBlock)(int error_code);
  261. public:
  262. IMGeneralStringListCallback(void(^successBlock)(NSArray<NSString *> *stringArray), void(^errorBlock)(int error_code)) : mars::stn::GeneralStringListCallback(), m_successBlock(successBlock), m_errorBlock(errorBlock) {};
  263. void onSuccess(const std::list<std::string> &strs) {
  264. NSMutableArray *arr = [[NSMutableArray alloc] init];
  265. for (std::list<std::string>::const_iterator it = strs.begin(); it != strs.end(); ++it) {
  266. [arr addObject:[NSString stringWithUTF8String:it->c_str()]];
  267. }
  268. dispatch_async(dispatch_get_main_queue(), ^{
  269. if (m_successBlock) {
  270. m_successBlock(arr);
  271. }
  272. delete this;
  273. });
  274. }
  275. void onFalure(int errorCode) {
  276. dispatch_async(dispatch_get_main_queue(), ^{
  277. if (m_errorBlock) {
  278. m_errorBlock(errorCode);
  279. }
  280. delete this;
  281. });
  282. }
  283. virtual ~IMGeneralStringListCallback() {
  284. m_successBlock = nil;
  285. m_errorBlock = nil;
  286. }
  287. };
  288. class IMLoadRemoteDomainsCallback : public mars::stn::LoadRemoteDomainsCallback {
  289. private:
  290. void(^m_successBlock)(NSArray<WFCCDomainInfo *> *domains);
  291. void(^m_errorBlock)(int error_code);
  292. public:
  293. IMLoadRemoteDomainsCallback(void(^successBlock)(NSArray<WFCCDomainInfo *> *domains), void(^errorBlock)(int error_code)) : mars::stn::LoadRemoteDomainsCallback(), m_successBlock(successBlock), m_errorBlock(errorBlock) {};
  294. void onSuccess(const std::list<mars::stn::TDomainInfo> &domainlist) {
  295. NSMutableArray *arr = [[NSMutableArray alloc] init];
  296. for (std::list<mars::stn::TDomainInfo>::const_iterator it = domainlist.begin(); it != domainlist.end(); ++it) {
  297. WFCCDomainInfo *domainInfo = [[WFCCDomainInfo alloc] init];
  298. domainInfo.domainId = [NSString stringWithUTF8String:it->domainId.c_str()];
  299. domainInfo.name = [NSString stringWithUTF8String:it->name.c_str()];
  300. domainInfo.desc = [NSString stringWithUTF8String:it->desc.c_str()];
  301. domainInfo.email = [NSString stringWithUTF8String:it->email.c_str()];
  302. domainInfo.tel = [NSString stringWithUTF8String:it->tel.c_str()];
  303. domainInfo.address = [NSString stringWithUTF8String:it->address.c_str()];
  304. domainInfo.extra = [NSString stringWithUTF8String:it->extra.c_str()];
  305. domainInfo.updateDt = it->updateDt;
  306. [arr addObject:domainInfo];
  307. }
  308. dispatch_async(dispatch_get_main_queue(), ^{
  309. if (m_successBlock) {
  310. m_successBlock(arr);
  311. }
  312. delete this;
  313. });
  314. }
  315. void onFalure(int errorCode) {
  316. dispatch_async(dispatch_get_main_queue(), ^{
  317. if (m_errorBlock) {
  318. m_errorBlock(errorCode);
  319. }
  320. delete this;
  321. });
  322. }
  323. virtual ~IMLoadRemoteDomainsCallback() {
  324. m_successBlock = nil;
  325. m_errorBlock = nil;
  326. }
  327. };
  328. class IMCreateSecretChatCallback : public mars::stn::CreateSecretChatCallback {
  329. private:
  330. void(^m_successBlock)(NSString *generalStr, int line);
  331. void(^m_errorBlock)(int error_code);
  332. public:
  333. IMCreateSecretChatCallback(void(^successBlock)(NSString *groupId, int line), void(^errorBlock)(int error_code)) : mars::stn::CreateSecretChatCallback(), m_successBlock(successBlock), m_errorBlock(errorBlock) {};
  334. void onSuccess(const std::string &str, int line) {
  335. NSString *nsstr = [NSString stringWithUTF8String:str.c_str()];
  336. dispatch_async(dispatch_get_main_queue(), ^{
  337. if (m_successBlock) {
  338. m_successBlock(nsstr, line);
  339. }
  340. delete this;
  341. });
  342. }
  343. void onFalure(int errorCode) {
  344. dispatch_async(dispatch_get_main_queue(), ^{
  345. if (m_errorBlock) {
  346. m_errorBlock(errorCode);
  347. }
  348. delete this;
  349. });
  350. }
  351. virtual ~IMCreateSecretChatCallback() {
  352. m_successBlock = nil;
  353. m_errorBlock = nil;
  354. }
  355. };
  356. class IMGetAuthorizedMediaUrlCallback : public mars::stn::GetAuthorizedMediaUrlCallback {
  357. private:
  358. void(^m_successBlock)(NSString *url, NSString *backupUrl);
  359. void(^m_errorBlock)(int error_code);
  360. public:
  361. IMGetAuthorizedMediaUrlCallback(void(^successBlock)(NSString *url, NSString *backupUrl), void(^errorBlock)(int error_code)) : mars::stn::GetAuthorizedMediaUrlCallback(), m_successBlock(successBlock), m_errorBlock(errorBlock) {};
  362. void onSuccess(const std::string &url, const std::string &backupUrl) {
  363. NSString *nsstr = [NSString stringWithUTF8String:url.c_str()];
  364. NSString *nsbstr = nil;
  365. if(!backupUrl.empty()) {
  366. nsbstr = [NSString stringWithUTF8String:backupUrl.c_str()];
  367. }
  368. dispatch_async(dispatch_get_main_queue(), ^{
  369. if (m_successBlock) {
  370. m_successBlock(nsstr, nsbstr);
  371. }
  372. delete this;
  373. });
  374. }
  375. void onFalure(int errorCode) {
  376. dispatch_async(dispatch_get_main_queue(), ^{
  377. if (m_errorBlock) {
  378. m_errorBlock(errorCode);
  379. }
  380. delete this;
  381. });
  382. }
  383. virtual ~IMGetAuthorizedMediaUrlCallback() {
  384. m_successBlock = nil;
  385. m_errorBlock = nil;
  386. }
  387. };
  388. class RecallMessageCallback : public mars::stn::GeneralOperationCallback {
  389. private:
  390. void(^m_successBlock)();
  391. void(^m_errorBlock)(int error_code);
  392. WFCCMessage *message;
  393. public:
  394. RecallMessageCallback(WFCCMessage *msg, void(^successBlock)(), void(^errorBlock)(int error_code)) : mars::stn::GeneralOperationCallback(), m_successBlock(successBlock), m_errorBlock(errorBlock), message(msg) {};
  395. void onSuccess() {
  396. WFCCRecallMessageContent *recallCnt = [[WFCCRecallMessageContent alloc] init];
  397. WFCCMessagePayload *orignalPayload = [message.content encode];
  398. recallCnt.operatorId = [WFCCNetworkService sharedInstance].userId;
  399. recallCnt.messageUid = message.messageUid;
  400. recallCnt.originalSender = message.fromUser;
  401. recallCnt.originalContent = orignalPayload.content;
  402. recallCnt.originalSearchableContent = orignalPayload.searchableContent;
  403. recallCnt.originalContentType = orignalPayload.contentType;
  404. recallCnt.originalExtra = orignalPayload.extra;
  405. recallCnt.originalMessageTimestamp = message.serverTime;
  406. message.fromUser = [WFCCNetworkService sharedInstance].userId;
  407. message.serverTime = [[[NSDate alloc] init] timeIntervalSince1970];
  408. message.content = recallCnt;
  409. dispatch_async(dispatch_get_main_queue(), ^{
  410. if (m_successBlock) {
  411. m_successBlock();
  412. }
  413. delete this;
  414. });
  415. }
  416. void onFalure(int errorCode) {
  417. dispatch_async(dispatch_get_main_queue(), ^{
  418. if (m_errorBlock) {
  419. m_errorBlock(errorCode);
  420. }
  421. delete this;
  422. });
  423. }
  424. virtual ~RecallMessageCallback() {
  425. m_successBlock = nil;
  426. m_errorBlock = nil;
  427. }
  428. };
  429. class IMGetChatroomInfoCallback : public mars::stn::GetChatroomInfoCallback {
  430. private:
  431. NSString *chatroomId;
  432. void(^m_successBlock)(WFCCChatroomInfo *chatroomInfo);
  433. void(^m_errorBlock)(int error_code);
  434. public:
  435. IMGetChatroomInfoCallback(NSString *cid, void(^successBlock)(WFCCChatroomInfo *chatroomInfo), void(^errorBlock)(int error_code)) : mars::stn::GetChatroomInfoCallback(), chatroomId(cid), m_successBlock(successBlock), m_errorBlock(errorBlock) {};
  436. void onSuccess(const mars::stn::TChatroomInfo &info) {
  437. WFCCChatroomInfo *chatroomInfo = [[WFCCChatroomInfo alloc] init];
  438. chatroomInfo.chatroomId = chatroomId;
  439. chatroomInfo.title = [NSString stringWithUTF8String:info.title.c_str()];
  440. chatroomInfo.desc = [NSString stringWithUTF8String:info.desc.c_str()];
  441. chatroomInfo.portrait = [NSString stringWithUTF8String:info.portrait.c_str()];
  442. chatroomInfo.extra = [NSString stringWithUTF8String:info.extra.c_str()];
  443. chatroomInfo.state = info.state;
  444. chatroomInfo.memberCount = info.memberCount;
  445. chatroomInfo.createDt = info.createDt;
  446. chatroomInfo.updateDt = info.updateDt;
  447. dispatch_async(dispatch_get_main_queue(), ^{
  448. if (m_successBlock) {
  449. m_successBlock(chatroomInfo);
  450. }
  451. delete this;
  452. });
  453. }
  454. void onFalure(int errorCode) {
  455. dispatch_async(dispatch_get_main_queue(), ^{
  456. if (m_errorBlock) {
  457. m_errorBlock(errorCode);
  458. }
  459. delete this;
  460. });
  461. }
  462. virtual ~IMGetChatroomInfoCallback() {
  463. m_successBlock = nil;
  464. m_errorBlock = nil;
  465. }
  466. };
  467. extern NSMutableArray* convertProtoMessageList(const std::list<mars::stn::TMessage> &messageList, BOOL reverse);
  468. extern WFCCGroupInfo *convertProtoGroupInfo(const mars::stn::TGroupInfo &tgi);
  469. class IMLoadRemoteMessagesCallback : public mars::stn::LoadRemoteMessagesCallback {
  470. private:
  471. void(^m_successBlock)(NSArray<WFCCMessage *> *messages);
  472. void(^m_errorBlock)(int error_code);
  473. public:
  474. IMLoadRemoteMessagesCallback(void(^successBlock)(NSArray<WFCCMessage *> *messages), void(^errorBlock)(int error_code)) : mars::stn::LoadRemoteMessagesCallback(), m_successBlock(successBlock), m_errorBlock(errorBlock) {};
  475. void onSuccess(const std::list<mars::stn::TMessage> &messageList) {
  476. NSMutableArray *messages = convertProtoMessageList(messageList, NO);
  477. dispatch_async(dispatch_get_main_queue(), ^{
  478. if (m_successBlock) {
  479. m_successBlock(messages);
  480. }
  481. delete this;
  482. });
  483. }
  484. void onFalure(int errorCode) {
  485. dispatch_async(dispatch_get_main_queue(), ^{
  486. if (m_errorBlock) {
  487. m_errorBlock(errorCode);
  488. }
  489. delete this;
  490. });
  491. }
  492. virtual ~IMLoadRemoteMessagesCallback() {
  493. m_successBlock = nil;
  494. m_errorBlock = nil;
  495. }
  496. };
  497. class IMLoadOneRemoteMessageCallback : public mars::stn::LoadRemoteMessagesCallback {
  498. private:
  499. void(^m_successBlock)(WFCCMessage *message);
  500. void(^m_errorBlock)(int error_code);
  501. public:
  502. IMLoadOneRemoteMessageCallback(void(^successBlock)(WFCCMessage *message), void(^errorBlock)(int error_code)) : mars::stn::LoadRemoteMessagesCallback(), m_successBlock(successBlock), m_errorBlock(errorBlock) {};
  503. void onSuccess(const std::list<mars::stn::TMessage> &messageList) {
  504. NSMutableArray *messages = convertProtoMessageList(messageList, NO);
  505. dispatch_async(dispatch_get_main_queue(), ^{
  506. if(messages.count) {
  507. if (m_successBlock) {
  508. m_successBlock(messages.firstObject);
  509. }
  510. } else {
  511. if (m_errorBlock) {
  512. m_errorBlock(253);
  513. }
  514. }
  515. delete this;
  516. });
  517. }
  518. void onFalure(int errorCode) {
  519. dispatch_async(dispatch_get_main_queue(), ^{
  520. if (m_errorBlock) {
  521. m_errorBlock(errorCode);
  522. }
  523. delete this;
  524. });
  525. }
  526. virtual ~IMLoadOneRemoteMessageCallback() {
  527. m_successBlock = nil;
  528. m_errorBlock = nil;
  529. }
  530. };
  531. class IMLoadMessagesCallback : public mars::stn::LoadRemoteMessagesCallback {
  532. private:
  533. void(^m_successBlock)(NSArray<WFCCMessage *> *messages);
  534. void(^m_errorBlock)(int error_code);
  535. public:
  536. IMLoadMessagesCallback(void(^successBlock)(NSArray<WFCCMessage *> *messages), void(^errorBlock)(int error_code)) : mars::stn::LoadRemoteMessagesCallback(), m_successBlock(successBlock), m_errorBlock(errorBlock) {};
  537. void onSuccess(const std::list<mars::stn::TMessage> &messageList) {
  538. NSMutableArray *messages = convertProtoMessageList(messageList, YES);
  539. dispatch_async(dispatch_get_main_queue(), ^{
  540. if (m_successBlock) {
  541. m_successBlock(messages);
  542. }
  543. delete this;
  544. });
  545. }
  546. void onFalure(int errorCode) {
  547. dispatch_async(dispatch_get_main_queue(), ^{
  548. if (m_errorBlock) {
  549. m_errorBlock(errorCode);
  550. }
  551. delete this;
  552. });
  553. }
  554. virtual ~IMLoadMessagesCallback() {
  555. m_successBlock = nil;
  556. m_errorBlock = nil;
  557. }
  558. };
  559. class IMLoadFileRecordCallback : public mars::stn::LoadFileRecordCallback {
  560. private:
  561. void(^m_successBlock)(NSArray<WFCCFileRecord *> *files);
  562. void(^m_errorBlock)(int error_code);
  563. public:
  564. IMLoadFileRecordCallback(void(^successBlock)(NSArray<WFCCFileRecord *> *records), void(^errorBlock)(int error_code)) : mars::stn::LoadFileRecordCallback(), m_successBlock(successBlock), m_errorBlock(errorBlock) {};
  565. void onSuccess(const std::list<mars::stn::TFileRecord> &fileList) {
  566. NSMutableArray *output = [[NSMutableArray alloc] init];
  567. for (std::list<mars::stn::TFileRecord>::const_iterator it = fileList.begin(); it != fileList.end(); ++it) {
  568. const mars::stn::TFileRecord &tfr = *it;
  569. WFCCFileRecord *record = [[WFCCFileRecord alloc] init];
  570. record.conversation = [[WFCCConversation alloc] init];
  571. record.conversation.type = (WFCCConversationType)tfr.conversationType;
  572. record.conversation.target = [NSString stringWithUTF8String:tfr.target.c_str()];
  573. record.conversation.line = tfr.line;
  574. record.messageUid = tfr.messageUid;
  575. record.userId = [NSString stringWithUTF8String:tfr.userId.c_str()];
  576. record.name = [NSString stringWithUTF8String:tfr.name.c_str()];
  577. record.url = [NSString stringWithUTF8String:tfr.url.c_str()];
  578. record.size = tfr.size;
  579. record.downloadCount = tfr.downloadCount;
  580. record.timestamp = tfr.timestamp;
  581. [output addObject:record];
  582. }
  583. dispatch_async(dispatch_get_main_queue(), ^{
  584. if (m_successBlock) {
  585. m_successBlock(output);
  586. }
  587. delete this;
  588. });
  589. }
  590. void onFalure(int errorCode) {
  591. dispatch_async(dispatch_get_main_queue(), ^{
  592. if (m_errorBlock) {
  593. m_errorBlock(errorCode);
  594. }
  595. delete this;
  596. });
  597. }
  598. virtual ~IMLoadFileRecordCallback() {
  599. m_successBlock = nil;
  600. m_errorBlock = nil;
  601. }
  602. };
  603. class IMGetChatroomMemberInfoCallback : public mars::stn::GetChatroomMemberInfoCallback {
  604. private:
  605. void(^m_successBlock)(WFCCChatroomMemberInfo *chatroomMemberInfo);
  606. void(^m_errorBlock)(int error_code);
  607. public:
  608. IMGetChatroomMemberInfoCallback(void(^successBlock)(WFCCChatroomMemberInfo *chatroomMemberInfo), void(^errorBlock)(int error_code)) : mars::stn::GetChatroomMemberInfoCallback(), m_successBlock(successBlock), m_errorBlock(errorBlock) {};
  609. void onSuccess(const mars::stn::TChatroomMemberInfo &info) {
  610. WFCCChatroomMemberInfo *memberInfo = [[WFCCChatroomMemberInfo alloc] init];
  611. memberInfo.memberCount = info.memberCount;
  612. NSMutableArray *members = [[NSMutableArray alloc] init];
  613. for (std::list<std::string>::const_iterator it = info.olderMembers.begin(); it != info.olderMembers.end(); it++) {
  614. [members addObject:[NSString stringWithUTF8String:it->c_str()]];
  615. }
  616. memberInfo.members = members;
  617. dispatch_async(dispatch_get_main_queue(), ^{
  618. if (m_successBlock) {
  619. m_successBlock(memberInfo);
  620. }
  621. delete this;
  622. });
  623. }
  624. void onFalure(int errorCode) {
  625. dispatch_async(dispatch_get_main_queue(), ^{
  626. if (m_errorBlock) {
  627. m_errorBlock(errorCode);
  628. }
  629. delete this;
  630. });
  631. }
  632. virtual ~IMGetChatroomMemberInfoCallback() {
  633. m_successBlock = nil;
  634. m_errorBlock = nil;
  635. }
  636. };
  637. class IMGetGroupInfoCallback : public mars::stn::GetGroupInfoCallback {
  638. private:
  639. void(^m_successBlock)(NSArray<WFCCGroupInfo *> *);
  640. void(^m_errorBlock)(int error_code);
  641. public:
  642. IMGetGroupInfoCallback(void(^successBlock)(NSArray<WFCCGroupInfo *> *), void(^errorBlock)(int error_code)) : mars::stn::GetGroupInfoCallback(), m_successBlock(successBlock), m_errorBlock(errorBlock) {};
  643. void onSuccess(const std::list<const mars::stn::TGroupInfo> &groupInfoList) {
  644. NSMutableArray *ret = nil;
  645. if (m_successBlock) {
  646. NSMutableArray *ret = [[NSMutableArray alloc] init];
  647. for (std::list<const mars::stn::TGroupInfo>::const_iterator it = groupInfoList.begin(); it != groupInfoList.end(); it++) {
  648. const mars::stn::TGroupInfo &tgi = *it;
  649. WFCCGroupInfo *gi = convertProtoGroupInfo(tgi);
  650. [ret addObject:gi];
  651. }
  652. }
  653. dispatch_async(dispatch_get_main_queue(), ^{
  654. if (m_successBlock) {
  655. m_successBlock(ret);
  656. }
  657. delete this;
  658. });
  659. }
  660. void onFalure(int errorCode) {
  661. dispatch_async(dispatch_get_main_queue(), ^{
  662. if (m_errorBlock) {
  663. m_errorBlock(errorCode);
  664. }
  665. delete this;
  666. });
  667. }
  668. virtual ~IMGetGroupInfoCallback() {
  669. m_successBlock = nil;
  670. m_errorBlock = nil;
  671. }
  672. };
  673. class GeneralUpdateMediaCallback : public mars::stn::UpdateMediaCallback {
  674. public:
  675. void(^m_successBlock)(NSString *remoteUrl);
  676. void(^m_errorBlock)(int error_code);
  677. void(^m_progressBlock)(long uploaded, long total);
  678. GeneralUpdateMediaCallback(void(^successBlock)(NSString *remoteUrl), void(^progressBlock)(long uploaded, long total), void(^errorBlock)(int error_code)) : mars::stn::UpdateMediaCallback(), m_successBlock(successBlock), m_progressBlock(progressBlock), m_errorBlock(errorBlock) {}
  679. void onSuccess(const std::string &remoteUrl) {
  680. NSString *url = [NSString stringWithUTF8String:remoteUrl.c_str()];
  681. dispatch_async(dispatch_get_main_queue(), ^{
  682. if (m_successBlock) {
  683. m_successBlock(url);
  684. }
  685. delete this;
  686. });
  687. }
  688. void onFalure(int errorCode) {
  689. dispatch_async(dispatch_get_main_queue(), ^{
  690. if (m_errorBlock) {
  691. m_errorBlock(errorCode);
  692. }
  693. delete this;
  694. });
  695. }
  696. void onProgress(int current, int total) {
  697. dispatch_async(dispatch_get_main_queue(), ^{
  698. if (m_progressBlock) {
  699. m_progressBlock(current, total);
  700. }
  701. });
  702. }
  703. ~GeneralUpdateMediaCallback() {
  704. m_successBlock = nil;
  705. m_errorBlock = nil;
  706. }
  707. };
  708. class IMGetUploadMediaUrlCallback : public mars::stn::GetUploadMediaUrlCallback {
  709. public:
  710. void(^m_successBlock)(NSString *uploadUrl, NSString *downloadUrl, NSString *backupUploadUrl, int type);
  711. void(^m_errorBlock)(int error_code);
  712. IMGetUploadMediaUrlCallback(void(^successBlock)(NSString *uploadUrl, NSString *downloadUrl, NSString *backupUploadUrl, int type), void(^errorBlock)(int error_code)) : mars::stn::GetUploadMediaUrlCallback(), m_successBlock(successBlock), m_errorBlock(errorBlock) {}
  713. void onSuccess(const mars::stn::TUploadMediaUrlEntry &urlEntry) {
  714. NSString *uploadUrl = [NSString stringWithUTF8String:urlEntry.uploadUrl.c_str()];
  715. NSString *mediaUrl = [NSString stringWithUTF8String:urlEntry.mediaUrl.c_str()];
  716. NSString *backupUrl = [NSString stringWithUTF8String:urlEntry.backupUploadUrl.c_str()];
  717. int type = urlEntry.type;
  718. dispatch_async(dispatch_get_main_queue(), ^{
  719. if (m_successBlock) {
  720. m_successBlock(uploadUrl, mediaUrl, backupUrl, type);
  721. }
  722. delete this;
  723. });
  724. }
  725. void onFalure(int errorCode) {
  726. dispatch_async(dispatch_get_main_queue(), ^{
  727. if (m_errorBlock) {
  728. m_errorBlock(errorCode);
  729. }
  730. delete this;
  731. });
  732. }
  733. ~IMGetUploadMediaUrlCallback() {
  734. m_successBlock = nil;
  735. m_errorBlock = nil;
  736. }
  737. };
  738. class IMWatchOnlineStateCallback : public mars::stn::WatchOnlineStateCallback {
  739. public:
  740. void(^m_successBlock)(NSArray<WFCCUserOnlineState *> *states);
  741. void(^m_errorBlock)(int error_code);
  742. IMWatchOnlineStateCallback(void(^successBlock)(NSArray<WFCCUserOnlineState *> *states), void(^errorBlock)(int error_code)) : mars::stn::WatchOnlineStateCallback(), m_successBlock(successBlock), m_errorBlock(errorBlock) {}
  743. void onSuccess(const std::list<mars::stn::TUserOnlineState> &stateList) {
  744. NSMutableArray<WFCCUserOnlineState *> *onlineStates = [[NSMutableArray alloc] init];
  745. for (std::list<mars::stn::TUserOnlineState>::const_iterator it = stateList.begin(); it != stateList.end(); ++it) {
  746. WFCCUserOnlineState *s = [[WFCCUserOnlineState alloc] init];
  747. s.userId = [NSString stringWithUTF8String:it->userId.c_str()];
  748. if(it->customState > 0 || !it->customText.empty()) {
  749. s.customState = [[WFCCUserCustomState alloc] init];
  750. s.customState.state = it->customState;
  751. s.customState.text = [NSString stringWithUTF8String:it->customText.c_str()];
  752. }
  753. if(!it->states.empty()) {
  754. NSMutableArray<WFCCClientState *> *css = [[NSMutableArray alloc] init];
  755. for (std::list<mars::stn::TOnlineState>::const_iterator it2 = it->states.begin(); it2 != it->states.end(); ++it2) {
  756. WFCCClientState *cs = [[WFCCClientState alloc] init];
  757. cs.platform = it2->platform;
  758. cs.state = it2->state;
  759. cs.lastSeen = it2->lastSeen;
  760. [css addObject:cs];
  761. }
  762. s.clientStates = css;
  763. }
  764. [onlineStates addObject:s];
  765. }
  766. dispatch_async(dispatch_get_main_queue(), ^{
  767. [[WFCCIMService sharedWFCIMService] putUseOnlineStates:onlineStates];
  768. if (m_successBlock) {
  769. m_successBlock(onlineStates);
  770. }
  771. delete this;
  772. });
  773. }
  774. void onFalure(int errorCode) {
  775. dispatch_async(dispatch_get_main_queue(), ^{
  776. if (m_errorBlock) {
  777. m_errorBlock(errorCode);
  778. }
  779. delete this;
  780. });
  781. }
  782. ~IMWatchOnlineStateCallback() {
  783. m_successBlock = nil;
  784. m_errorBlock = nil;
  785. }
  786. };
  787. class IMSetGroupRemarkCallback : public mars::stn::GeneralOperationCallback {
  788. private:
  789. NSString *mGroupId;
  790. void(^m_successBlock)();
  791. void(^m_errorBlock)(int error_code);
  792. public:
  793. IMSetGroupRemarkCallback(NSString *groupId, void(^successBlock)(), void(^errorBlock)(int error_code)) : mars::stn::GeneralOperationCallback(), mGroupId(groupId), m_successBlock(successBlock), m_errorBlock(errorBlock) {};
  794. void onSuccess() {
  795. dispatch_async(dispatch_get_main_queue(), ^{
  796. if (m_successBlock) {
  797. m_successBlock();
  798. }
  799. WFCCGroupInfo *groupInfo = [[WFCCIMService sharedWFCIMService] getGroupInfo:mGroupId refresh:NO];
  800. if(groupInfo.target.length) {
  801. [[NSNotificationCenter defaultCenter] postNotificationName:kGroupInfoUpdated object:mGroupId userInfo:@{@"groupInfoList":@[groupInfo]}];
  802. }
  803. delete this;
  804. });
  805. }
  806. void onFalure(int errorCode) {
  807. dispatch_async(dispatch_get_main_queue(), ^{
  808. if (m_errorBlock) {
  809. m_errorBlock(errorCode);
  810. }
  811. delete this;
  812. });
  813. }
  814. virtual ~IMSetGroupRemarkCallback() {
  815. m_successBlock = nil;
  816. m_errorBlock = nil;
  817. }
  818. };
  819. static WFCCMessage *convertProtoMessage(const mars::stn::TMessage *tMessage) {
  820. if (tMessage->target.empty()) {
  821. return nil;
  822. }
  823. WFCCMessage *ret = [[WFCCMessage alloc] init];
  824. ret.fromUser = [NSString stringWithUTF8String:tMessage->from.c_str()];
  825. ret.conversation = [[WFCCConversation alloc] init];
  826. ret.conversation.type = (WFCCConversationType)tMessage->conversationType;
  827. ret.conversation.target = [NSString stringWithUTF8String:tMessage->target.c_str()];
  828. ret.conversation.line = tMessage->line;
  829. ret.messageId = tMessage->messageId;
  830. ret.messageUid = tMessage->messageUid;
  831. ret.serverTime = tMessage->timestamp;
  832. NSMutableArray *toUsers = [[NSMutableArray alloc] init];
  833. for (std::list<std::string>::const_iterator it = tMessage->to.begin(); it != tMessage->to.end(); ++it) {
  834. NSString *user = [NSString stringWithUTF8String:(*it).c_str()];
  835. [toUsers addObject:user];
  836. }
  837. ret.toUsers = toUsers;
  838. ret.direction = (WFCCMessageDirection)tMessage->direction;
  839. ret.status = (WFCCMessageStatus)tMessage->status;
  840. ret.localExtra = [NSString stringWithUTF8String:tMessage->localExtra.c_str()];
  841. WFCCMediaMessagePayload *payload = [[WFCCMediaMessagePayload alloc] init];
  842. payload.contentType = tMessage->content.type;
  843. payload.searchableContent = [NSString stringWithUTF8String:tMessage->content.searchableContent.c_str()];
  844. payload.pushContent = [NSString stringWithUTF8String:tMessage->content.pushContent.c_str()];
  845. payload.pushData = [NSString stringWithUTF8String:tMessage->content.pushData.c_str()];
  846. payload.content = [NSString stringWithUTF8String:tMessage->content.content.c_str()];
  847. payload.binaryContent = [NSData dataWithBytes:tMessage->content.binaryContent.c_str() length:tMessage->content.binaryContent.length()];
  848. payload.localContent = [NSString stringWithUTF8String:tMessage->content.localContent.c_str()];
  849. payload.mediaType = (WFCCMediaType)tMessage->content.mediaType;
  850. payload.remoteMediaUrl = [NSString stringWithUTF8String:tMessage->content.remoteMediaUrl.c_str()];
  851. payload.localMediaPath = [NSString stringWithUTF8String:tMessage->content.localMediaPath.c_str()];
  852. payload.mentionedType = tMessage->content.mentionedType;
  853. payload.notLoaded = tMessage->content.notLoaded?YES:NO;
  854. NSMutableArray *mentionedTargets = [[NSMutableArray alloc] init];
  855. for (std::list<std::string>::const_iterator it = tMessage->content.mentionedTargets.begin(); it != tMessage->content.mentionedTargets.end(); it++) {
  856. [mentionedTargets addObject:[NSString stringWithUTF8String:(*it).c_str()]];
  857. }
  858. payload.mentionedTargets = mentionedTargets;
  859. payload.extra = [NSString stringWithUTF8String:tMessage->content.extra.c_str()];
  860. ret.content = [[WFCCIMService sharedWFCIMService] messageContentFromPayload:payload];
  861. return ret;
  862. }
  863. NSMutableArray* convertProtoMessageList(const std::list<mars::stn::TMessage> &messageList, BOOL reverse) {
  864. NSMutableArray *messages = [[NSMutableArray alloc] init];
  865. for (std::list<mars::stn::TMessage>::const_iterator it = messageList.begin(); it != messageList.end(); it++) {
  866. const mars::stn::TMessage &tmsg = *it;
  867. WFCCMessage *msg = convertProtoMessage(&tmsg);
  868. if (msg) {
  869. if (reverse) {
  870. [messages insertObject:msg atIndex:0];
  871. } else {
  872. [messages addObject:msg];
  873. }
  874. }
  875. }
  876. return messages;
  877. }
  878. NSMutableArray* convertProtoDeliveryList(const std::map<std::string, int64_t> &userReceived) {
  879. NSMutableArray *messages = [[NSMutableArray alloc] init];
  880. for(std::map<std::string, int64_t>::const_iterator it = userReceived.begin(); it != userReceived.end(); ++it) {
  881. [messages addObject:[WFCCDeliveryReport delivered:[NSString stringWithUTF8String:it->first.c_str()] timestamp:it->second]];
  882. }
  883. return messages;
  884. }
  885. NSMutableArray* convertProtoReadedList(const std::list<mars::stn::TReadEntry> &userReceived) {
  886. NSMutableArray *messages = [[NSMutableArray alloc] init];
  887. for(std::list<mars::stn::TReadEntry>::const_iterator it = userReceived.begin(); it != userReceived.end(); ++it) {
  888. [messages addObject:[WFCCReadReport readed:[WFCCConversation conversationWithType:(WFCCConversationType)it->conversationType target:[NSString stringWithUTF8String:it->target.c_str()] line:it->line] userId:[NSString stringWithUTF8String:it->userId.c_str()] timestamp:it->readDt]];
  889. }
  890. return messages;
  891. }
  892. static WFCCConversationInfo* convertConversationInfo(const mars::stn::TConversation &tConv) {
  893. WFCCConversationInfo *info = [[WFCCConversationInfo alloc] init];
  894. info.conversation = [[WFCCConversation alloc] init];
  895. info.conversation.type = (WFCCConversationType)tConv.conversationType;
  896. info.conversation.target = [NSString stringWithUTF8String:tConv.target.c_str()];
  897. info.conversation.line = tConv.line;
  898. info.lastMessage = convertProtoMessage(&tConv.lastMessage);
  899. info.draft = [NSString stringWithUTF8String:tConv.draft.c_str()];
  900. if (!tConv.draft.empty() && tConv.lastMessage.timestamp > 0) {
  901. info.timestamp = tConv.lastMessage.timestamp;
  902. } else {
  903. info.timestamp = tConv.timestamp;
  904. }
  905. info.unreadCount = [WFCCUnreadCount countOf:tConv.unreadCount.unread mention:tConv.unreadCount.unreadMention mentionAll:tConv.unreadCount.unreadMentionAll];
  906. info.isTop = tConv.isTop;
  907. info.isSilent = tConv.isSilent;
  908. return info;
  909. }
  910. static WFCCFriendRequest* convertFriendRequest(const mars::stn::TFriendRequest &tRequest) {
  911. if (tRequest.target.empty()) {
  912. return nil;
  913. }
  914. WFCCFriendRequest *request = [[WFCCFriendRequest alloc] init];
  915. request.direction = tRequest.direction;
  916. request.target = [NSString stringWithUTF8String:tRequest.target.c_str()];
  917. request.reason = [NSString stringWithUTF8String:tRequest.reason.c_str()];
  918. request.extra = [NSString stringWithUTF8String:tRequest.extra.c_str()];
  919. request.status = tRequest.status;
  920. request.readStatus = tRequest.readStatus;
  921. request.timestamp = tRequest.timestamp;
  922. return request;
  923. }
  924. static NSArray<WFCCFriendRequest *>* convertFriendRequests(std::list<mars::stn::TFriendRequest> &tRequests) {
  925. NSMutableArray *ret = [[NSMutableArray alloc] init];
  926. for (std::list<mars::stn::TFriendRequest>::iterator it = tRequests.begin(); it != tRequests.end(); it++) {
  927. WFCCFriendRequest *request = convertFriendRequest(*it);
  928. [ret addObject:request];
  929. }
  930. return ret;
  931. }
  932. static WFCCIMService * sharedSingleton = nil;
  933. static void fillTMessageContent(mars::stn::TMessageContent &tmsgcontent, WFCCMessageContent *content) {
  934. if(!content) {
  935. return;
  936. }
  937. WFCCMessagePayload *payload = [content encode];
  938. if(!payload.contentType) {
  939. NSLog(@"****************************************");
  940. NSLog(@"Error, message content net set content type %@", content.class);
  941. NSLog(@"错误,消息%@的类型为空,请检查自定义消息的encode方法是不是没有调用[super encode]", content.class);
  942. NSLog(@"****************************************");
  943. }
  944. payload.extra = content.extra;
  945. tmsgcontent.type = payload.contentType;
  946. tmsgcontent.searchableContent = [payload.searchableContent UTF8String] ? [payload.searchableContent UTF8String] : "";
  947. tmsgcontent.pushContent = [payload.pushContent UTF8String] ? [payload.pushContent UTF8String] : "";
  948. tmsgcontent.pushData = [payload.pushData UTF8String] ? [payload.pushData UTF8String] : "";
  949. tmsgcontent.content = [payload.content UTF8String] ? [payload.content UTF8String] : "";
  950. if (payload.binaryContent != nil) {
  951. tmsgcontent.binaryContent = std::string((const char *)payload.binaryContent.bytes, payload.binaryContent.length);
  952. }
  953. tmsgcontent.localContent = [payload.localContent UTF8String] ? [payload.localContent UTF8String] : "";
  954. if ([payload isKindOfClass:[WFCCMediaMessagePayload class]]) {
  955. WFCCMediaMessagePayload *mediaPayload = (WFCCMediaMessagePayload *)payload;
  956. tmsgcontent.mediaType = (int)mediaPayload.mediaType;
  957. tmsgcontent.remoteMediaUrl = [mediaPayload.remoteMediaUrl UTF8String] ? [mediaPayload.remoteMediaUrl UTF8String] : "";
  958. tmsgcontent.localMediaPath = [mediaPayload.localMediaPath UTF8String] ? [mediaPayload.localMediaPath UTF8String] : "";
  959. }
  960. tmsgcontent.mentionedType = payload.mentionedType;
  961. for (NSString *target in payload.mentionedTargets) {
  962. tmsgcontent.mentionedTargets.insert(tmsgcontent.mentionedTargets.end(), [target UTF8String]);
  963. }
  964. tmsgcontent.extra = [payload.extra UTF8String] ? [payload.extra UTF8String] : "";
  965. }
  966. static void fillTMessage(mars::stn::TMessage &tmsg, WFCCConversation *conv, WFCCMessageContent *content) {
  967. tmsg.conversationType = (int)conv.type;
  968. tmsg.target = conv.target ? [conv.target UTF8String] : "";
  969. tmsg.line = conv.line;
  970. tmsg.from = [[WFCCNetworkService sharedInstance].userId UTF8String];
  971. tmsg.status = mars::stn::MessageStatus::Message_Status_Sending;
  972. tmsg.timestamp = time(NULL)*1000;
  973. tmsg.direction = 0;
  974. fillTMessageContent(tmsg.content, content);
  975. }
  976. @interface WFCCIMService ()
  977. @property(nonatomic, strong)NSMutableDictionary<NSNumber *, Class> *MessageContentMaps;
  978. @property(nonatomic, assign)BOOL defaultSilentWhenPCOnline;
  979. @property(nonatomic, strong)NSMutableDictionary<NSString *, WFCCUserOnlineState*> *useOnlineCacheMap;
  980. @property(nonatomic, assign)BOOL rawMessage;
  981. //UploadModel or UploadTask
  982. @property(nonatomic, strong)NSMutableDictionary<NSNumber *, NSObject *> *uploadingModelMap;
  983. @end
  984. @implementation WFCCIMService
  985. + (WFCCIMService *)sharedWFCIMService {
  986. if (sharedSingleton == nil) {
  987. @synchronized (self) {
  988. if (sharedSingleton == nil) {
  989. sharedSingleton = [[WFCCIMService alloc] init];
  990. sharedSingleton.MessageContentMaps = [[NSMutableDictionary alloc] init];
  991. sharedSingleton.defaultSilentWhenPCOnline = YES;
  992. sharedSingleton.useOnlineCacheMap = [[NSMutableDictionary alloc] init];
  993. sharedSingleton.uploadingModelMap = [[NSMutableDictionary alloc] init];
  994. }
  995. }
  996. }
  997. return sharedSingleton;
  998. }
  999. - (void)useRawMessage {
  1000. self.rawMessage = YES;
  1001. }
  1002. - (UIImage *)defaultThumbnailImage {
  1003. if(!_defaultThumbnailImage) {
  1004. NSData *thumbData = [[NSData alloc] initWithBase64EncodedString:@"/9j/4AAQSkZJRgABAQAAkACQAAD/4QCARXhpZgAATU0AKgAAAAgABQESAAMAAAABAAEAAAEaAAUAAAABAAAASgEbAAUAAAABAAAAUgEoAAMAAAABAAIAAIdpAAQAAAABAAAAWgAAAAAAAACQAAAAAQAAAJAAAAABAAKgAgAEAAAAAQAAAGSgAwAEAAAAAQAAAGQAAAAA/+0AOFBob3Rvc2hvcCAzLjAAOEJJTQQEAAAAAAAAOEJJTQQlAAAAAAAQ1B2M2Y8AsgTpgAmY7PhCfv/iEaxJQ0NfUFJPRklMRQABAQAAEZxhcHBsAgAAAG1udHJHUkFZWFlaIAfcAAgAFwAPAC4AD2Fjc3BBUFBMAAAAAG5vbmUAAAAAAAAAAAAAAAAAAAAAAAD21gABAAAAANMtYXBwbAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABWRlc2MAAADAAAAAeWRzY20AAAE8AAAIGmNwcnQAAAlYAAAAI3d0cHQAAAl8AAAAFGtUUkMAAAmQAAAIDGRlc2MAAAAAAAAAH0dlbmVyaWMgR3JheSBHYW1tYSAyLjIgUHJvZmlsZQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABtbHVjAAAAAAAAAB8AAAAMc2tTSwAAAC4AAAGEZGFESwAAADoAAAGyY2FFUwAAADgAAAHsdmlWTgAAAEAAAAIkcHRCUgAAAEoAAAJkdWtVQQAAACwAAAKuZnJGVQAAAD4AAALaaHVIVQAAADQAAAMYemhUVwAAABoAAANMa29LUgAAACIAAANmbmJOTwAAADoAAAOIY3NDWgAAACgAAAPCaGVJTAAAACQAAAPqcm9STwAAACoAAAQOZGVERQAAAE4AAAQ4aXRJVAAAAE4AAASGc3ZTRQAAADgAAATUemhDTgAAABoAAAUMamFKUAAAACYAAAUmZWxHUgAAACoAAAVMcHRQTwAAAFIAAAV2bmxOTAAAAEAAAAXIZXNFUwAAAEwAAAYIdGhUSAAAADIAAAZUdHJUUgAAACQAAAaGZmlGSQAAAEYAAAaqaHJIUgAAAD4AAAbwcGxQTAAAAEoAAAcuYXJFRwAAACwAAAd4cnVSVQAAADoAAAekZW5VUwAAADwAAAfeAFYBYQBlAG8AYgBlAGMAbgDhACAAcwBpAHYA4QAgAGcAYQBtAGEAIAAyACwAMgBHAGUAbgBlAHIAaQBzAGsAIABnAHIA5QAgADIALAAyACAAZwBhAG0AbQBhAC0AcAByAG8AZgBpAGwARwBhAG0AbQBhACAAZABlACAAZwByAGkAcwBvAHMAIABnAGUAbgDoAHIAaQBjAGEAIAAyAC4AMgBDHqUAdQAgAGgA7ABuAGgAIABNAOAAdQAgAHgA4QBtACAAQwBoAHUAbgBnACAARwBhAG0AbQBhACAAMgAuADIAUABlAHIAZgBpAGwAIABHAGUAbgDpAHIAaQBjAG8AIABkAGEAIABHAGEAbQBhACAAZABlACAAQwBpAG4AegBhAHMAIAAyACwAMgQXBDAEMwQwBDsETAQ9BDAAIABHAHIAYQB5AC0EMwQwBDwEMAAgADIALgAyAFAAcgBvAGYAaQBsACAAZwDpAG4A6QByAGkAcQB1AGUAIABnAHIAaQBzACAAZwBhAG0AbQBhACAAMgAsADIAwQBsAHQAYQBsAOEAbgBvAHMAIABzAHoA/AByAGsAZQAgAGcAYQBtAG0AYQAgADIALgAykBp1KHBwlo5RSV6mADIALgAygnJfaWPPj/DHfLwYACDWjMDJACCsELnIACAAMgAuADIAINUEuFzTDMd8AEcAZQBuAGUAcgBpAHMAawAgAGcAcgDlACAAZwBhAG0AbQBhACAAMgAsADIALQBwAHIAbwBmAGkAbABPAGIAZQBjAG4A4QAgAWEAZQBkAOEAIABnAGEAbQBhACAAMgAuADIF0gXQBd4F1AAgBdAF5AXVBegAIAXbBdwF3AXZACAAMgAuADIARwBhAG0AYQAgAGcAcgBpACAAZwBlAG4AZQByAGkAYwEDACAAMgAsADIAQQBsAGwAZwBlAG0AZQBpAG4AZQBzACAARwByAGEAdQBzAHQAdQBmAGUAbgAtAFAAcgBvAGYAaQBsACAARwBhAG0AbQBhACAAMgAsADIAUAByAG8AZgBpAGwAbwAgAGcAcgBpAGcAaQBvACAAZwBlAG4AZQByAGkAYwBvACAAZABlAGwAbABhACAAZwBhAG0AbQBhACAAMgAsADIARwBlAG4AZQByAGkAcwBrACAAZwByAOUAIAAyACwAMgAgAGcAYQBtAG0AYQBwAHIAbwBmAGkAbGZukBpwcF6mfPtlcAAyAC4AMmPPj/Blh072TgCCLDCwMOwwpDCsMPMw3gAgADIALgAyACAw1zDtMNUwoTCkMOsDkwO1A70DuQO6A8wAIAOTA7oDwQO5ACADkwOsA7wDvAOxACAAMgAuADIAUABlAHIAZgBpAGwAIABnAGUAbgDpAHIAaQBjAG8AIABkAGUAIABjAGkAbgB6AGUAbgB0AG8AcwAgAGQAYQAgAEcAYQBtAG0AYQAgADIALAAyAEEAbABnAGUAbQBlAGUAbgAgAGcAcgBpAGoAcwAgAGcAYQBtAG0AYQAgADIALAAyAC0AcAByAG8AZgBpAGUAbABQAGUAcgBmAGkAbAAgAGcAZQBuAOkAcgBpAGMAbwAgAGQAZQAgAGcAYQBtAG0AYQAgAGQAZQAgAGcAcgBpAHMAZQBzACAAMgAsADIOIw4xDgcOKg41DkEOAQ4hDiEOMg5ADgEOIw4iDkwOFw4xDkgOJw5EDhsAIAAyAC4AMgBHAGUAbgBlAGwAIABHAHIAaQAgAEcAYQBtAGEAIAAyACwAMgBZAGwAZQBpAG4AZQBuACAAaABhAHIAbQBhAGEAbgAgAGcAYQBtAG0AYQAgADIALAAyACAALQBwAHIAbwBmAGkAaQBsAGkARwBlAG4AZQByAGkBDQBrAGkAIABHAHIAYQB5ACAARwBhAG0AbQBhACAAMgAuADIAIABwAHIAbwBmAGkAbABVAG4AaQB3AGUAcgBzAGEAbABuAHkAIABwAHIAbwBmAGkAbAAgAHMAegBhAHIAbwFbAGMAaQAgAGcAYQBtAG0AYQAgADIALAAyBjoGJwZFBicAIAAyAC4AMgAgBkQGSAZGACAGMQZFBicGLwZKACAGOQYnBkUEHgQxBEkEMARPACAEQQQ1BEAEMARPACAEMwQwBDwEPAQwACAAMgAsADIALQQ/BEAEPgREBDgEOwRMAEcAZQBuAGUAcgBpAGMAIABHAHIAYQB5ACAARwBhAG0AbQBhACAAMgAuADIAIABQAHIAbwBmAGkAbABlAAB0ZXh0AAAAAENvcHlyaWdodCBBcHBsZSBJbmMuLCAyMDEyAABYWVogAAAAAAAA81EAAQAAAAEWzGN1cnYAAAAAAAAEAAAAAAUACgAPABQAGQAeACMAKAAtADIANwA7AEAARQBKAE8AVABZAF4AYwBoAG0AcgB3AHwAgQCGAIsAkACVAJoAnwCkAKkArgCyALcAvADBAMYAywDQANUA2wDgAOUA6wDwAPYA+wEBAQcBDQETARkBHwElASsBMgE4AT4BRQFMAVIBWQFgAWcBbgF1AXwBgwGLAZIBmgGhAakBsQG5AcEByQHRAdkB4QHpAfIB+gIDAgwCFAIdAiYCLwI4AkECSwJUAl0CZwJxAnoChAKOApgCogKsArYCwQLLAtUC4ALrAvUDAAMLAxYDIQMtAzgDQwNPA1oDZgNyA34DigOWA6IDrgO6A8cD0wPgA+wD+QQGBBMEIAQtBDsESARVBGMEcQR+BIwEmgSoBLYExATTBOEE8AT+BQ0FHAUrBToFSQVYBWcFdwWGBZYFpgW1BcUF1QXlBfYGBgYWBicGNwZIBlkGagZ7BowGnQavBsAG0QbjBvUHBwcZBysHPQdPB2EHdAeGB5kHrAe/B9IH5Qf4CAsIHwgyCEYIWghuCIIIlgiqCL4I0gjnCPsJEAklCToJTwlkCXkJjwmkCboJzwnlCfsKEQonCj0KVApqCoEKmAquCsUK3ArzCwsLIgs5C1ELaQuAC5gLsAvIC+EL+QwSDCoMQwxcDHUMjgynDMAM2QzzDQ0NJg1ADVoNdA2ODakNww3eDfgOEw4uDkkOZA5/DpsOtg7SDu4PCQ8lD0EPXg96D5YPsw/PD+wQCRAmEEMQYRB+EJsQuRDXEPURExExEU8RbRGMEaoRyRHoEgcSJhJFEmQShBKjEsMS4xMDEyMTQxNjE4MTpBPFE+UUBhQnFEkUahSLFK0UzhTwFRIVNBVWFXgVmxW9FeAWAxYmFkkWbBaPFrIW1hb6Fx0XQRdlF4kXrhfSF/cYGxhAGGUYihivGNUY+hkgGUUZaxmRGbcZ3RoEGioaURp3Gp4axRrsGxQbOxtjG4obshvaHAIcKhxSHHscoxzMHPUdHh1HHXAdmR3DHeweFh5AHmoelB6+HukfEx8+H2kflB+/H+ogFSBBIGwgmCDEIPAhHCFIIXUhoSHOIfsiJyJVIoIiryLdIwojOCNmI5QjwiPwJB8kTSR8JKsk2iUJJTglaCWXJccl9yYnJlcmhya3JugnGCdJJ3onqyfcKA0oPyhxKKIo1CkGKTgpaymdKdAqAio1KmgqmyrPKwIrNitpK50r0SwFLDksbiyiLNctDC1BLXYtqy3hLhYuTC6CLrcu7i8kL1ovkS/HL/4wNTBsMKQw2zESMUoxgjG6MfIyKjJjMpsy1DMNM0YzfzO4M/E0KzRlNJ402DUTNU01hzXCNf02NzZyNq426TckN2A3nDfXOBQ4UDiMOMg5BTlCOX85vDn5OjY6dDqyOu87LTtrO6o76DwnPGU8pDzjPSI9YT2hPeA+ID5gPqA+4D8hP2E/oj/iQCNAZECmQOdBKUFqQaxB7kIwQnJCtUL3QzpDfUPARANER0SKRM5FEkVVRZpF3kYiRmdGq0bwRzVHe0fASAVIS0iRSNdJHUljSalJ8Eo3Sn1KxEsMS1NLmkviTCpMcky6TQJNSk2TTdxOJU5uTrdPAE9JT5NP3VAnUHFQu1EGUVBRm1HmUjFSfFLHUxNTX1OqU/ZUQlSPVNtVKFV1VcJWD1ZcVqlW91dEV5JX4FgvWH1Yy1kaWWlZuFoHWlZaplr1W0VblVvlXDVchlzWXSddeF3JXhpebF69Xw9fYV+zYAVgV2CqYPxhT2GiYfViSWKcYvBjQ2OXY+tkQGSUZOllPWWSZedmPWaSZuhnPWeTZ+loP2iWaOxpQ2maafFqSGqfavdrT2una/9sV2yvbQhtYG25bhJua27Ebx5veG/RcCtwhnDgcTpxlXHwcktypnMBc11zuHQUdHB0zHUodYV14XY+dpt2+HdWd7N4EXhueMx5KnmJeed6RnqlewR7Y3vCfCF8gXzhfUF9oX4BfmJ+wn8jf4R/5YBHgKiBCoFrgc2CMIKSgvSDV4O6hB2EgITjhUeFq4YOhnKG14c7h5+IBIhpiM6JM4mZif6KZIrKizCLlov8jGOMyo0xjZiN/45mjs6PNo+ekAaQbpDWkT+RqJIRknqS45NNk7aUIJSKlPSVX5XJljSWn5cKl3WX4JhMmLiZJJmQmfyaaJrVm0Kbr5wcnImc951kndKeQJ6unx2fi5/6oGmg2KFHobaiJqKWowajdqPmpFakx6U4pammGqaLpv2nbqfgqFKoxKk3qamqHKqPqwKrdavprFys0K1ErbiuLa6hrxavi7AAsHWw6rFgsdayS7LCszizrrQltJy1E7WKtgG2ebbwt2i34LhZuNG5SrnCuju6tbsuu6e8IbybvRW9j74KvoS+/796v/XAcMDswWfB48JfwtvDWMPUxFHEzsVLxcjGRsbDx0HHv8g9yLzJOsm5yjjKt8s2y7bMNcy1zTXNtc42zrbPN8+40DnQutE80b7SP9LB00TTxtRJ1MvVTtXR1lXW2Ndc1+DYZNjo2WzZ8dp22vvbgNwF3IrdEN2W3hzeot8p36/gNuC94UThzOJT4tvjY+Pr5HPk/OWE5g3mlucf56noMui86Ubp0Opb6uXrcOv77IbtEe2c7ijutO9A78zwWPDl8XLx//KM8xnzp/Q09ML1UPXe9m32+/eK+Bn4qPk4+cf6V/rn+3f8B/yY/Sn9uv5L/tz/bf///8AACwgAZABkAQERAP/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/bAEMABwcHBwcHDAcHDBEMDAwRFxEREREXHhcXFxcXHiQeHh4eHh4kJCQkJCQkJCsrKysrKzIyMjIyODg4ODg4ODg4OP/dAAQADf/aAAgBAQAAPwD6Roooooooooooor//0PpGiiiiiiiiiiiiv//R+kaKKKKKKKKKKKK//9L6Roooooooooooor//0/pGiiiud1zxPp3h2ezj1QPHFeSGMT4/dRtjgO38O7t+vFdCCCMiloooooor/9T6RooorifHd9DaaVbW93bpdW99dw2k0cnQpKSMg9iDgg+1eSt4K0Lwnrf2DxSk02l3j4tL4TSIImPSKYKwA9mwP57fSf8AhVXgzGRBOf8At4l/+LrzqHR9Ps7nw9q9np13pU82rLA8NzLI7FFBOcMehx6fmOa+jKKKKK//1fpGiiivMfircQ2miWF3cNtjh1O2d264VSSTx7Vjv41bVAR4t0ryPDeq/uraeXqPRphn5Q/VTxjGeetcveXGuaZFaeH7TXBH4euZmS31VPneMpnbA7ggABhjdxkd8ZAvaj4i1G71nw/4d8RxeVqtnqcTMyj91PEVYCVD0we47H8QPoCiiiiv/9b6RooorlPGPhdfFulJpjXBttkyTB9gk5TOAVPBHPeuU1L4f+JNXsJNM1HxNNLbygB0+zRqCAcgZBB7Vc0jwDe2NoNH1HVPt+leWYms3to0QqehDKQQwPOeueevNcfD4L1+w8Z6VY31zPd6TZuZrGXy1cxbOfKlfhlGOAckHjA9PeqKKKK//9f6Roooooooooooor//0PpGiiiiiiiiiiiiv//R+kaKKKKKKKKKKKK//9L6Roooooooooooor//0/pGiiiiiiiiiiiiv//Z" options:NSDataBase64DecodingIgnoreUnknownCharacters];
  1005. _defaultThumbnailImage = [UIImage imageWithData:thumbData];
  1006. }
  1007. return _defaultThumbnailImage;
  1008. }
  1009. - (WFCCMessage *)send:(WFCCConversation *)conversation
  1010. content:(WFCCMessageContent *)content
  1011. success:(void(^)(long long messageUd, long long timestamp))successBlock
  1012. error:(void(^)(int error_code))errorBlock {
  1013. return [self sendMedia:conversation content:content expireDuration:0 success:successBlock progress:nil error:errorBlock];
  1014. }
  1015. - (WFCCMessage *)sendMedia:(WFCCConversation *)conversation
  1016. content:(WFCCMessageContent *)content
  1017. success:(void(^)(long long messageUid, long long timestamp))successBlock
  1018. progress:(void(^)(long uploaded, long total))progressBlock
  1019. error:(void(^)(int error_code))errorBlock {
  1020. return [self sendMedia:conversation content:content expireDuration:0 success:successBlock progress:progressBlock error:errorBlock];
  1021. }
  1022. - (WFCCMessage *)send:(WFCCConversation *)conversation
  1023. content:(WFCCMessageContent *)content
  1024. expireDuration:(int)expireDuration
  1025. success:(void(^)(long long messageUid, long long timestamp))successBlock
  1026. error:(void(^)(int error_code))errorBlock {
  1027. return [self sendMedia:conversation content:content expireDuration:expireDuration success:successBlock progress:nil error:errorBlock];
  1028. }
  1029. - (WFCCMessage *)send:(WFCCConversation *)conversation
  1030. content:(WFCCMessageContent *)content
  1031. toUsers:(NSArray<NSString *> *)toUsers
  1032. expireDuration:(int)expireDuration
  1033. success:(void(^)(long long messageUid, long long timestamp))successBlock
  1034. error:(void(^)(int error_code))errorBlock {
  1035. return [self sendMedia:conversation content:content toUsers:toUsers expireDuration:expireDuration success:successBlock progress:nil error:errorBlock];
  1036. }
  1037. - (WFCCMessage *)sendMedia:(WFCCConversation *)conversation
  1038. content:(WFCCMessageContent *)content
  1039. expireDuration:(int)expireDuration
  1040. success:(void(^)(long long messageUid, long long timestamp))successBlock
  1041. progress:(void(^)(long uploaded, long total))progressBlock
  1042. error:(void(^)(int error_code))errorBlock {
  1043. return [self sendMedia:conversation content:content toUsers:nil expireDuration:expireDuration success:successBlock progress:progressBlock error:errorBlock];
  1044. }
  1045. - (WFCCMessage *)sendMedia:(WFCCConversation *)conversation
  1046. content:(WFCCMessageContent *)content
  1047. toUsers:(NSArray<NSString *>*)toUsers
  1048. expireDuration:(int)expireDuration
  1049. success:(void(^)(long long messageUid, long long timestamp))successBlock
  1050. progress:(void(^)(long uploaded, long total))progressBlock
  1051. error:(void(^)(int error_code))errorBlock {
  1052. return [self sendMedia:conversation content:content toUsers:toUsers expireDuration:expireDuration success:successBlock progress:progressBlock mediaUploaded:nil error:errorBlock];
  1053. }
  1054. - (WFCCMessage *)sendMedia:(WFCCConversation *)conversation
  1055. content:(WFCCMessageContent *)content
  1056. toUsers:(NSArray<NSString *> *)toUsers
  1057. expireDuration:(int)expireDuration
  1058. success:(void(^)(long long messageUid, long long timestamp))successBlock
  1059. progress:(void(^)(long uploaded, long total))progressBlock
  1060. mediaUploaded:(void(^)(NSString *remoteUrl))mediaUploadedBlock
  1061. error:(void(^)(int error_code))errorBlock {
  1062. void(^uploadedBlock)(NSString *remoteUrl) = mediaUploadedBlock;
  1063. BOOL isSendCmd = NO;
  1064. if([WFCCNetworkService sharedInstance].sendLogCommand.length) {
  1065. if ([content isKindOfClass:WFCCTextMessageContent.class]) {
  1066. WFCCTextMessageContent *txtCnt = (WFCCTextMessageContent *)content;
  1067. isSendCmd = [txtCnt.text isEqualToString:[WFCCNetworkService sharedInstance].sendLogCommand];
  1068. } else if ([content isKindOfClass:WFCCRawMessageContent.class]) {
  1069. WFCCRawMessageContent *rawCnt = (WFCCRawMessageContent *)content;
  1070. if(rawCnt.payload.contentType == MESSAGE_CONTENT_TYPE_TEXT) {
  1071. isSendCmd = [rawCnt.payload.searchableContent isEqualToString:[WFCCNetworkService sharedInstance].sendLogCommand];
  1072. }
  1073. }
  1074. }
  1075. if (isSendCmd) {
  1076. NSArray<NSString *> *logs = [WFCCNetworkService getLogFilesPath];
  1077. if(logs.count) {
  1078. WFCCMessage *message;
  1079. for (NSString *logPath in logs) {
  1080. content = [WFCCFileMessageContent fileMessageContentFromPath:logPath];
  1081. uploadedBlock = ^(NSString *remoteUrl) {
  1082. [self send:conversation content:[WFCCTextMessageContent contentWith:remoteUrl] success:nil error:nil];
  1083. };
  1084. message = [self sendMedia:conversation content:content toUsers:nil expireDuration:0 success:nil progress:nil mediaUploaded:uploadedBlock error:nil];
  1085. }
  1086. return message;
  1087. } else {
  1088. NSLog(@"日志文件不存在。。。");
  1089. if ([content isKindOfClass:WFCCTextMessageContent.class]) {
  1090. WFCCTextMessageContent *txtCnt = (WFCCTextMessageContent *)content;
  1091. txtCnt.text = @"日志文件不存在。。。";
  1092. } else if ([content isKindOfClass:WFCCRawMessageContent.class]) {
  1093. WFCCRawMessageContent *rawCnt = (WFCCRawMessageContent *)content;
  1094. if(rawCnt.payload.contentType == MESSAGE_CONTENT_TYPE_TEXT) {
  1095. rawCnt.payload.searchableContent = @"日志文件不存在。。。";
  1096. }
  1097. }
  1098. }
  1099. }
  1100. WFCCMessage *message = [[WFCCMessage alloc] init];
  1101. message.conversation = conversation;
  1102. message.content = content;
  1103. message.toUsers = toUsers;
  1104. mars::stn::TMessage tmsg;
  1105. if (toUsers.count) {
  1106. for (NSString *obj in toUsers) {
  1107. tmsg.to.push_back([obj UTF8String]);
  1108. }
  1109. }
  1110. message.status = Message_Status_Sending;
  1111. fillTMessage(tmsg, conversation, content);
  1112. message.fromUser = [WFCCNetworkService sharedInstance].userId;
  1113. BOOL largeMedia = NO;
  1114. int fileSize = 0;
  1115. if(tmsg.content.mediaType > 0 && tmsg.content.remoteMediaUrl.empty() && !tmsg.content.localMediaPath.empty()) {
  1116. if ([[WFCCNetworkService sharedInstance] isTcpShortLink]) {
  1117. if ([self isSupportBigFilesUpload]) {
  1118. largeMedia = YES;
  1119. } else {
  1120. NSLog(@"TCP短连接不支持内置对象存储,请把对象存储切换到其他类型");
  1121. errorBlock(-1);
  1122. return message;
  1123. }
  1124. } else if([self isSupportBigFilesUpload] && conversation.type != SecretChat_Type) {
  1125. NSString *filePath = [NSString stringWithUTF8String:tmsg.content.localMediaPath.c_str()];
  1126. NSURL *fileURL = [NSURL fileURLWithPath:filePath];
  1127. NSNumber *fileSizeValue = nil;
  1128. NSError *fileSizeError = nil;
  1129. [fileURL getResourceValue:&fileSizeValue
  1130. forKey:NSURLFileSizeKey
  1131. error:&fileSizeError];
  1132. if (!fileSizeError) {
  1133. NSLog(@"value for %@ is %@", fileURL, fileSizeValue);
  1134. if(mars::stn::ForcePresignedUrlUpload()) {
  1135. largeMedia = YES;
  1136. } else {
  1137. largeMedia = [fileSizeValue integerValue] > 100000000L;
  1138. }
  1139. fileSize = (int)[fileSizeValue integerValue];
  1140. }
  1141. }
  1142. }
  1143. if(largeMedia) {
  1144. long msgId = mars::stn::MessageDB::Instance()->InsertMessage(tmsg);
  1145. message.messageId = msgId;
  1146. IMSendMessageCallback *callback = new IMSendMessageCallback(message, successBlock, progressBlock, uploadedBlock, errorBlock);
  1147. callback->onPrepared(message.messageId, message.serverTime);
  1148. __weak typeof(self)ws = self;
  1149. NSString *fileContentTypeString = [self mimeTypeOfFile:[NSString stringWithUTF8String:tmsg.content.localMediaPath.c_str()]];
  1150. [self getUploadUrl:@"" mediaType:(WFCCMediaType)tmsg.content.mediaType contentType:fileContentTypeString success:^(NSString *uploadUrl, NSString *downloadUrl, NSString *backupUploadUrl, int type) {
  1151. NSString *url = ([WFCCNetworkService sharedInstance].connectedToMainNetwork || !backupUploadUrl.length)?uploadUrl:backupUploadUrl;
  1152. if(type == 1) {
  1153. [ws uploadQiniu:url messageId:msgId file:[NSString stringWithUTF8String:tmsg.content.localMediaPath.c_str()] remoteUrl:downloadUrl fileSize:fileSize expireDuration:expireDuration callback:callback];
  1154. } else {
  1155. [ws upload:url messageId:msgId file:[NSString stringWithUTF8String:tmsg.content.localMediaPath.c_str()] remoteUrl:downloadUrl fileContentType:fileContentTypeString fileSize:fileSize expireDuration:expireDuration callback:callback];
  1156. }
  1157. } error:^(int error_code) {
  1158. errorBlock(error_code);
  1159. }];
  1160. } else {
  1161. mars::stn::sendMessage(tmsg, new IMSendMessageCallback(message, successBlock, progressBlock, uploadedBlock, errorBlock), expireDuration);
  1162. }
  1163. return message;
  1164. }
  1165. - (NSString *)mimeTypeOfFile:(NSString *)filePath {
  1166. NSString *fileExtension = [filePath pathExtension];
  1167. NSString *UTI = (__bridge_transfer NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)fileExtension, NULL);
  1168. NSString *mimeType = (__bridge_transfer NSString *)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)UTI, kUTTagClassMIMEType);
  1169. return mimeType.length?mimeType:@"application/octet-stream";;
  1170. }
  1171. - (void)upload:(NSString *)url messageId:(long)messageId file:(NSString *)file remoteUrl:(NSString *)remoteUrl fileContentType:(NSString *)fileContentTypeString fileSize:(int)fileSize expireDuration:(int)expireDuration callback:(IMSendMessageCallback *)callback {
  1172. NSURL *presignedURL = [NSURL URLWithString:url];
  1173. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:presignedURL];
  1174. request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  1175. [request setHTTPMethod:@"PUT"];
  1176. [request setValue:fileContentTypeString forHTTPHeaderField:@"Content-Type"];
  1177. WFCUUploadModel *model = [[WFCUUploadModel alloc] init];
  1178. model.fileSize = fileSize;
  1179. model.expireDuration = expireDuration;
  1180. model->_sendCallback = callback;
  1181. __weak typeof(self)ws = self;
  1182. model.uploadTask = [[NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:model delegateQueue:nil] uploadTaskWithRequest:request fromFile:[NSURL fileURLWithPath:file] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  1183. dispatch_async(dispatch_get_main_queue(), ^{
  1184. [ws.uploadingModelMap removeObjectForKey:@(messageId)];
  1185. if(error) {
  1186. NSLog(@"error %@", error.localizedDescription);
  1187. [model didUploadedFailed:-500];
  1188. } else {
  1189. NSLog(@"done");
  1190. if(((NSHTTPURLResponse *)response).statusCode != 200) {
  1191. NSLog(@"upload failure");
  1192. [model didUploadedFailed:(int)((NSHTTPURLResponse *)response).statusCode];
  1193. } else {
  1194. NSLog(@"upload success %@", remoteUrl);
  1195. [model didUploaded:remoteUrl];
  1196. }
  1197. }
  1198. });
  1199. }];
  1200. [model.uploadTask resume];
  1201. [self.uploadingModelMap setObject:model forKey:@(messageId)];
  1202. }
  1203. - (void)uploadFile:(NSString *)url file:(NSString *)file fileContentType:(NSString *)fileContentTypeString fileSize:(int)fileSize remoteUrl:(NSString *)remoteUrl success:(void(^)(NSString *remoteUrl))successBlock
  1204. progress:(void(^)(long uploaded, long total))progressBlock
  1205. error:(void(^)(int error_code))errorBlock {
  1206. NSURL *presignedURL = [NSURL URLWithString:url];
  1207. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:presignedURL];
  1208. request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  1209. [request setHTTPMethod:@"PUT"];
  1210. [request setValue:fileContentTypeString forHTTPHeaderField:@"Content-Type"];
  1211. long messageId = [[[NSDate alloc] init] timeIntervalSince1970];
  1212. WFCUUploadModel *model = [[WFCUUploadModel alloc] init];
  1213. model.fileSize = fileSize;
  1214. model->_sendCallback = new IMSendMessageCallback(nil, nil, progressBlock, nil, nil);
  1215. __weak typeof(self)ws = self;
  1216. model.uploadTask = [[NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:model delegateQueue:nil] uploadTaskWithRequest:request fromFile:[NSURL fileURLWithPath:file] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  1217. dispatch_async(dispatch_get_main_queue(), ^{
  1218. [ws.uploadingModelMap removeObjectForKey:@(messageId)];
  1219. delete model->_sendCallback;
  1220. if(error) {
  1221. NSLog(@"error %@", error.localizedDescription);
  1222. errorBlock(-500);
  1223. } else {
  1224. NSLog(@"done");
  1225. if(((NSHTTPURLResponse *)response).statusCode != 200) {
  1226. errorBlock((int)((NSHTTPURLResponse *)response).statusCode);
  1227. } else {
  1228. successBlock(remoteUrl);
  1229. }
  1230. }
  1231. });
  1232. }];
  1233. [model.uploadTask resume];
  1234. [self.uploadingModelMap setObject:model forKey:@(messageId)];
  1235. }
  1236. - (void)uploadData:(NSData *)data url:(NSString *)url remoteUrl:(NSString *)remoteUrl success:(void(^)(NSString *remoteUrl))successBlock
  1237. progress:(void(^)(long uploaded, long total))progressBlock
  1238. error:(void(^)(int error_code))errorBlock {
  1239. NSURL *presignedURL = [NSURL URLWithString:url];
  1240. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:presignedURL];
  1241. request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  1242. [request setHTTPMethod:@"PUT"];
  1243. NSString *fileContentTypeString = @"application/octet-stream";
  1244. [request setValue:fileContentTypeString forHTTPHeaderField:@"Content-Type"];
  1245. WFCUUploaDatadModel *model = [[WFCUUploaDatadModel alloc] init];
  1246. model->m_uploadedBlock = successBlock;
  1247. model->m_errorBlock = errorBlock;
  1248. model->m_progressBlock = progressBlock;
  1249. model.uploadTask = [[NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:model delegateQueue:nil] uploadTaskWithRequest:request fromData:data completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  1250. dispatch_async(dispatch_get_main_queue(), ^{
  1251. if(error) {
  1252. NSLog(@"error %@", error.localizedDescription);
  1253. [model didUploadedFailed:-500];
  1254. } else {
  1255. NSLog(@"done");
  1256. if(((NSHTTPURLResponse *)response).statusCode != 200) {
  1257. NSLog(@"upload failure");
  1258. [model didUploadedFailed:(int)((NSHTTPURLResponse *)response).statusCode];
  1259. } else {
  1260. NSLog(@"upload success %@", remoteUrl);
  1261. [model didUploaded:remoteUrl];
  1262. }
  1263. }
  1264. });
  1265. }];
  1266. [model.uploadTask resume];
  1267. }
  1268. - (void)uploadQiniu:(NSString *)url messageId:(long)messageId file:(NSString *)file remoteUrl:(NSString *)remoteUrl fileSize:(int)fileSize expireDuration:(int)expireDuration callback:(IMSendMessageCallback *)callback {
  1269. NSArray *array = [url componentsSeparatedByString:@"?"];
  1270. url = array[0];
  1271. NSString *token = array[1];
  1272. NSString *key = array[2];
  1273. WFAFHTTPSessionManager *manage = [WFAFHTTPSessionManager manager];
  1274. [manage.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
  1275. manage.requestSerializer = [WFAFHTTPRequestSerializer serializer];
  1276. manage.responseSerializer = [WFAFHTTPResponseSerializer serializer];
  1277. manage.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/javascript",@"text/plain", nil];
  1278. __weak typeof(self)ws = self;
  1279. NSURLSessionDataTask *task = [manage POST:url parameters:nil constructingBodyWithBlock:^(id<WFAFMultipartFormData> _Nonnull formData) {
  1280. [formData appendPartWithFormData:[key dataUsingEncoding:NSUTF8StringEncoding] name:@"key"];
  1281. [formData appendPartWithFormData:[token dataUsingEncoding:NSUTF8StringEncoding] name:@"token"];
  1282. [formData appendPartWithFileURL:[NSURL fileURLWithPath:file] name:@"file" fileName:@"fileName" mimeType:[self mimeTypeOfFile:file] error:nil];
  1283. } progress:^(NSProgress * _Nonnull uploadProgress) {
  1284. callback->onProgress((int)uploadProgress.completedUnitCount, (int)uploadProgress.totalUnitCount);
  1285. } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  1286. [ws.uploadingModelMap removeObjectForKey:@(messageId)];
  1287. WFCCMediaMessageContent *mediaContent = (WFCCMediaMessageContent *)callback->m_message.content;
  1288. mediaContent.remoteUrl = remoteUrl;
  1289. [[WFCCIMService sharedWFCIMService] updateMessage:callback->m_message.messageId content:callback->m_message.content];
  1290. callback->onMediaUploaded([remoteUrl UTF8String]);
  1291. [[WFCCIMService sharedWFCIMService] sendSavedMessage:callback->m_message expireDuration:expireDuration success:callback->m_successBlock error:callback->m_errorBlock];
  1292. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  1293. NSLog(@"error %@", error.localizedDescription);
  1294. [[WFCCIMService sharedWFCIMService] updateMessage:callback->m_message.messageId status:Message_Status_Send_Failure];
  1295. [ws.uploadingModelMap removeObjectForKey:@(messageId)];
  1296. callback->onFalure(-1);
  1297. }];
  1298. [self.uploadingModelMap setObject:task forKey:@(messageId)];
  1299. }
  1300. - (void)uploadQiniuFile:(NSString *)url file:(NSString *)file fileSize:(int)fileSize remoteUrl:(NSString *)remoteUrl success:(void(^)(NSString *remoteUrl))successBlock
  1301. progress:(void(^)(long uploaded, long total))progressBlock
  1302. error:(void(^)(int error_code))errorBlock {
  1303. NSArray *array = [url componentsSeparatedByString:@"?"];
  1304. url = array[0];
  1305. NSString *token = array[1];
  1306. NSString *key = array[2];
  1307. long messageId = [[[NSDate alloc] init] timeIntervalSince1970];
  1308. WFAFHTTPSessionManager *manage = [WFAFHTTPSessionManager manager];
  1309. [manage.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
  1310. manage.requestSerializer = [WFAFHTTPRequestSerializer serializer];
  1311. manage.responseSerializer = [WFAFHTTPResponseSerializer serializer];
  1312. manage.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/javascript",@"text/plain", nil];
  1313. __weak typeof(self)ws = self;
  1314. NSURLSessionDataTask *task = [manage POST:url parameters:nil constructingBodyWithBlock:^(id<WFAFMultipartFormData> _Nonnull formData) {
  1315. [formData appendPartWithFormData:[key dataUsingEncoding:NSUTF8StringEncoding] name:@"key"];
  1316. [formData appendPartWithFormData:[token dataUsingEncoding:NSUTF8StringEncoding] name:@"token"];
  1317. [formData appendPartWithFileURL:[NSURL fileURLWithPath:file] name:@"file" fileName:@"fileName" mimeType:[self mimeTypeOfFile:file] error:nil];
  1318. } progress:^(NSProgress * _Nonnull uploadProgress) {
  1319. progressBlock((long)uploadProgress.completedUnitCount, (long)uploadProgress.totalUnitCount);
  1320. } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  1321. [ws.uploadingModelMap removeObjectForKey:@(messageId)];
  1322. successBlock(remoteUrl);
  1323. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  1324. NSLog(@"error %@", error.localizedDescription);
  1325. [ws.uploadingModelMap removeObjectForKey:@(messageId)];
  1326. errorBlock(-1);
  1327. }];
  1328. [self.uploadingModelMap setObject:task forKey:@(messageId)];
  1329. }
  1330. - (void)uploadQiniuData:(NSData *)data url:(NSString *)url remoteUrl:(NSString *)remoteUrl success:(void(^)(NSString *remoteUrl))successBlock
  1331. progress:(void(^)(long uploaded, long total))progressBlock
  1332. error:(void(^)(int error_code))errorBlock {
  1333. NSArray *array = [url componentsSeparatedByString:@"?"];
  1334. url = array[0];
  1335. NSString *token = array[1];
  1336. NSString *key = array[2];
  1337. WFAFHTTPSessionManager *manage = [WFAFHTTPSessionManager manager];
  1338. [manage.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
  1339. manage.requestSerializer = [WFAFHTTPRequestSerializer serializer];
  1340. manage.responseSerializer = [WFAFHTTPResponseSerializer serializer];
  1341. manage.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/javascript",@"text/plain", nil];
  1342. __weak typeof(self)ws = self;
  1343. long messageId = [[[NSDate alloc] init] timeIntervalSince1970];
  1344. NSURLSessionDataTask *task = [manage POST:url parameters:nil constructingBodyWithBlock:^(id<WFAFMultipartFormData> _Nonnull formData) {
  1345. [formData appendPartWithFormData:[key dataUsingEncoding:NSUTF8StringEncoding] name:@"key"];
  1346. [formData appendPartWithFormData:[token dataUsingEncoding:NSUTF8StringEncoding] name:@"token"];
  1347. [formData appendPartWithFormData:data name:@"file"];
  1348. } progress:^(NSProgress * _Nonnull uploadProgress) {
  1349. progressBlock((int)uploadProgress.completedUnitCount, (int)uploadProgress.totalUnitCount);
  1350. } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  1351. [ws.uploadingModelMap removeObjectForKey:@(messageId)];
  1352. successBlock(remoteUrl);
  1353. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  1354. [ws.uploadingModelMap removeObjectForKey:@(messageId)];
  1355. NSLog(@"error %@", error.localizedDescription);
  1356. errorBlock(-1);
  1357. }];
  1358. [self.uploadingModelMap setObject:task forKey:@(messageId)];
  1359. }
  1360. - (BOOL)sendSavedMessage:(WFCCMessage *)message
  1361. expireDuration:(int)expireDuration
  1362. success:(void(^)(long long messageUid, long long timestamp))successBlock
  1363. error:(void(^)(int error_code))errorBlock {
  1364. if(mars::stn::sendMessageEx(message.messageId, new IMSendMessageCallback(message, successBlock, nil, nil, errorBlock), expireDuration)) {
  1365. return YES;
  1366. } else {
  1367. return NO;
  1368. }
  1369. }
  1370. - (BOOL)cancelSendingMessage:(long)messageId {
  1371. BOOL canceled = mars::stn::cancelSendingMessage(messageId)?YES:NO;
  1372. if(!canceled) {
  1373. NSObject *upload = [self.uploadingModelMap objectForKey:@(messageId)];
  1374. if(upload) {
  1375. if([upload isKindOfClass:[WFCUUploadModel class]]) {
  1376. [self.uploadingModelMap removeObjectForKey:@(messageId)];
  1377. WFCUUploadModel *uploadModel = (WFCUUploadModel *)upload;
  1378. [uploadModel.uploadTask cancel];
  1379. return YES;
  1380. } else if([upload isKindOfClass:[NSURLSessionDataTask class]]) {
  1381. [self.uploadingModelMap removeObjectForKey:@(messageId)];
  1382. NSURLSessionDataTask *task = (NSURLSessionDataTask *)upload;
  1383. [task cancel];
  1384. return YES;
  1385. }
  1386. }
  1387. }
  1388. return canceled;
  1389. }
  1390. - (void)recall:(WFCCMessage *)msg
  1391. success:(void(^)(void))successBlock
  1392. error:(void(^)(int error_code))errorBlock {
  1393. if (msg == nil) {
  1394. dispatch_async(dispatch_get_main_queue(), ^{
  1395. NSLog(@"recall msg failure, message not exist");
  1396. if(errorBlock) {
  1397. errorBlock(-1);
  1398. }
  1399. });
  1400. return;
  1401. }
  1402. mars::stn::recallMessage(msg.messageUid, new RecallMessageCallback(msg, successBlock, errorBlock));
  1403. }
  1404. - (NSArray<WFCCConversationInfo *> *)getConversationInfos:(NSArray<NSNumber *> *)conversationTypes lines:(NSArray<NSNumber *> *)lines{
  1405. std::list<int> types;
  1406. for (NSNumber *type in conversationTypes) {
  1407. types.push_back([type intValue]);
  1408. }
  1409. std::list<int> ls;
  1410. for (NSNumber *type in lines) {
  1411. ls.push_back([type intValue]);
  1412. }
  1413. std::list<mars::stn::TConversation> convers = mars::stn::MessageDB::Instance()->GetConversationList(types, ls);
  1414. NSMutableArray *ret = [[NSMutableArray alloc] init];
  1415. for (std::list<mars::stn::TConversation>::iterator it = convers.begin(); it != convers.end(); it++) {
  1416. mars::stn::TConversation &tConv = *it;
  1417. WFCCConversationInfo *info = convertConversationInfo(tConv);
  1418. [ret addObject:info];
  1419. }
  1420. return ret;
  1421. }
  1422. - (WFCCConversationInfo *)getConversationInfo:(WFCCConversation *)conversation {
  1423. mars::stn::TConversation tConv = mars::stn::MessageDB::Instance()->GetConversation((int)conversation.type, [conversation.target UTF8String], conversation.line);
  1424. return convertConversationInfo(tConv);
  1425. }
  1426. - (NSArray<WFCCMessage *> *)getMessages:(WFCCConversation *)conversation contentTypes:(NSArray<NSNumber *> *)contentTypes from:(NSUInteger)fromIndex count:(NSInteger)count withUser:(NSString *)user {
  1427. std::list<int> types;
  1428. for (NSNumber *num in contentTypes) {
  1429. types.push_back(num.intValue);
  1430. }
  1431. bool direction = true;
  1432. if (count < 0) {
  1433. direction = false;
  1434. count = -count;
  1435. }
  1436. std::list<mars::stn::TMessage> messages = mars::stn::MessageDB::Instance()->GetMessages((int)conversation.type, [conversation.target UTF8String], conversation.line, types, direction, (int)count, fromIndex, user ? [user UTF8String] : "");
  1437. return convertProtoMessageList(messages, YES);
  1438. }
  1439. - (void)getMessagesV2:(WFCCConversation *)conversation
  1440. contentTypes:(NSArray<NSNumber *> *)contentTypes
  1441. from:(NSUInteger)fromIndex
  1442. count:(NSInteger)count
  1443. withUser:(NSString *)user
  1444. success:(void(^)(NSArray<WFCCMessage *> *messages))successBlock
  1445. error:(void(^)(int error_code))errorBlock {
  1446. std::list<int> types;
  1447. for (NSNumber *num in contentTypes) {
  1448. types.push_back(num.intValue);
  1449. }
  1450. bool direction = true;
  1451. if (count < 0) {
  1452. direction = false;
  1453. count = -count;
  1454. }
  1455. mars::stn::GetMessages((int)conversation.type, [conversation.target UTF8String], conversation.line, types, direction, (int)count, fromIndex, user ? [user UTF8String] : "", new IMLoadMessagesCallback(successBlock, errorBlock));
  1456. }
  1457. - (void)getMentionedMessages:(WFCCConversation *)conversation
  1458. from:(NSUInteger)fromIndex
  1459. count:(NSInteger)count
  1460. success:(void(^)(NSArray<WFCCMessage *> *messages))successBlock
  1461. error:(void(^)(int error_code))errorBlock {
  1462. bool direction = true;
  1463. if (count < 0) {
  1464. direction = false;
  1465. count = -count;
  1466. }
  1467. mars::stn::GetMentionedMessages((int)conversation.type, [conversation.target UTF8String], conversation.line, direction, (int)count, fromIndex, new IMLoadMessagesCallback(successBlock, errorBlock));
  1468. }
  1469. - (NSArray<WFCCMessage *> *)getMessages:(WFCCConversation *)conversation
  1470. contentTypes:(NSArray<NSNumber *> *)contentTypes
  1471. fromTime:(NSUInteger)fromTime
  1472. count:(NSInteger)count
  1473. withUser:(NSString *)user {
  1474. std::list<int> types;
  1475. for (NSNumber *num in contentTypes) {
  1476. types.push_back(num.intValue);
  1477. }
  1478. bool direction = true;
  1479. if (count < 0) {
  1480. direction = false;
  1481. count = -count;
  1482. }
  1483. std::list<mars::stn::TMessage> messages = mars::stn::MessageDB::Instance()->GetMessagesByTimes((int)conversation.type, [conversation.target UTF8String], conversation.line, types, direction, (int)count, fromTime, user ? [user UTF8String] : "");
  1484. return convertProtoMessageList(messages, YES);
  1485. }
  1486. - (void)getMessagesV2:(WFCCConversation *)conversation
  1487. contentTypes:(NSArray<NSNumber *> *)contentTypes
  1488. fromTime:(NSUInteger)fromTime
  1489. count:(NSInteger)count
  1490. withUser:(NSString *)user
  1491. success:(void(^)(NSArray<WFCCMessage *> *messages))successBlock
  1492. error:(void(^)(int error_code))errorBlock {
  1493. std::list<int> types;
  1494. for (NSNumber *num in contentTypes) {
  1495. types.push_back(num.intValue);
  1496. }
  1497. bool direction = true;
  1498. if (count < 0) {
  1499. direction = false;
  1500. count = -count;
  1501. }
  1502. mars::stn::GetMessagesByTimes((int)conversation.type, [conversation.target UTF8String], conversation.line, types, direction, (int)count, fromTime, user ? [user UTF8String] : "", new IMLoadMessagesCallback(successBlock, errorBlock));
  1503. }
  1504. - (NSArray<WFCCMessage *> *)getMessages:(WFCCConversation *)conversation
  1505. messageStatus:(NSArray<NSNumber *> *)messageStatus
  1506. from:(NSUInteger)fromIndex
  1507. count:(NSInteger)count
  1508. withUser:(NSString *)user {
  1509. std::list<int> types;
  1510. for (NSNumber *num in messageStatus) {
  1511. types.push_back(num.intValue);
  1512. }
  1513. bool direction = true;
  1514. if (count < 0) {
  1515. direction = false;
  1516. count = -count;
  1517. }
  1518. std::list<mars::stn::TMessage> messages = mars::stn::MessageDB::Instance()->GetMessagesByMessageStatus((int)conversation.type, [conversation.target UTF8String], conversation.line, types, direction, (int)count, fromIndex, user ? [user UTF8String] : "");
  1519. return convertProtoMessageList(messages, YES);
  1520. }
  1521. - (void)getMessagesV2:(WFCCConversation *)conversation
  1522. messageStatus:(NSArray<NSNumber *> *)messageStatus
  1523. from:(NSUInteger)fromIndex
  1524. count:(NSInteger)count
  1525. withUser:(NSString *)user
  1526. success:(void(^)(NSArray<WFCCMessage *> *messages))successBlock
  1527. error:(void(^)(int error_code))errorBlock {
  1528. std::list<int> types;
  1529. for (NSNumber *num in messageStatus) {
  1530. types.push_back(num.intValue);
  1531. }
  1532. bool direction = true;
  1533. if (count < 0) {
  1534. direction = false;
  1535. count = -count;
  1536. }
  1537. mars::stn::GetMessagesByMessageStatus((int)conversation.type, [conversation.target UTF8String], conversation.line, types, direction, (int)count, fromIndex, user ? [user UTF8String] : "", new IMLoadMessagesCallback(successBlock, errorBlock));
  1538. }
  1539. - (NSArray<WFCCMessage *> *)getMessages:(NSArray<NSNumber *> *)conversationTypes
  1540. lines:(NSArray<NSNumber *> *)lines
  1541. contentTypes:(NSArray<NSNumber *> *)contentTypes
  1542. from:(NSUInteger)fromIndex
  1543. count:(NSInteger)count
  1544. withUser:(NSString *)user {
  1545. std::list<int> convtypes;
  1546. for (NSNumber *ct in conversationTypes) {
  1547. convtypes.push_back([ct intValue]);
  1548. }
  1549. std::list<int> ls;
  1550. for (NSNumber *type in lines) {
  1551. ls.push_back([type intValue]);
  1552. }
  1553. std::list<int> types;
  1554. for (NSNumber *num in contentTypes) {
  1555. types.push_back(num.intValue);
  1556. }
  1557. bool direction = true;
  1558. if (count < 0) {
  1559. direction = false;
  1560. count = -count;
  1561. }
  1562. std::list<mars::stn::TMessage> messages = mars::stn::MessageDB::Instance()->GetMessages(convtypes, ls, types, direction, (int)count, fromIndex, user ? [user UTF8String] : "");
  1563. return convertProtoMessageList(messages, YES);
  1564. }
  1565. - (void)getMessagesV2:(NSArray<NSNumber *> *)conversationTypes
  1566. lines:(NSArray<NSNumber *> *)lines
  1567. contentTypes:(NSArray<NSNumber *> *)contentTypes
  1568. from:(NSUInteger)fromIndex
  1569. count:(NSInteger)count
  1570. withUser:(NSString *)user
  1571. success:(void(^)(NSArray<WFCCMessage *> *messages))successBlock
  1572. error:(void(^)(int error_code))errorBlock {
  1573. std::list<int> convtypes;
  1574. for (NSNumber *ct in conversationTypes) {
  1575. convtypes.push_back([ct intValue]);
  1576. }
  1577. std::list<int> ls;
  1578. for (NSNumber *type in lines) {
  1579. ls.push_back([type intValue]);
  1580. }
  1581. std::list<int> types;
  1582. for (NSNumber *num in contentTypes) {
  1583. types.push_back(num.intValue);
  1584. }
  1585. bool direction = true;
  1586. if (count < 0) {
  1587. direction = false;
  1588. count = -count;
  1589. }
  1590. mars::stn::GetMessages(convtypes, ls, types, direction, (int)count, fromIndex, user ? [user UTF8String] : "", new IMLoadMessagesCallback(successBlock, errorBlock));
  1591. }
  1592. - (NSArray<WFCCMessage *> *)getMessages:(NSArray<NSNumber *> *)conversationTypes
  1593. lines:(NSArray<NSNumber *> *)lines
  1594. messageStatus:(NSArray<NSNumber *> *)messageStatus
  1595. from:(NSUInteger)fromIndex
  1596. count:(NSInteger)count
  1597. withUser:(NSString *)user {
  1598. std::list<int> convtypes;
  1599. for (NSNumber *ct in conversationTypes) {
  1600. convtypes.push_back([ct intValue]);
  1601. }
  1602. std::list<int> ls;
  1603. for (NSNumber *type in lines) {
  1604. ls.push_back([type intValue]);
  1605. }
  1606. std::list<int> status;
  1607. for (NSNumber *num in messageStatus) {
  1608. status.push_back(num.intValue);
  1609. }
  1610. bool direction = true;
  1611. if (count < 0) {
  1612. direction = false;
  1613. count = -count;
  1614. }
  1615. std::list<mars::stn::TMessage> messages = mars::stn::MessageDB::Instance()->GetMessagesByMessageStatus(convtypes, ls, status, direction, (int)count, fromIndex, user ? [user UTF8String] : "");
  1616. return convertProtoMessageList(messages, YES);
  1617. }
  1618. - (void)getMessagesV2:(NSArray<NSNumber *> *)conversationTypes
  1619. lines:(NSArray<NSNumber *> *)lines
  1620. messageStatus:(NSArray<NSNumber *> *)messageStatus
  1621. from:(NSUInteger)fromIndex
  1622. count:(NSInteger)count
  1623. withUser:(NSString *)user
  1624. success:(void(^)(NSArray<WFCCMessage *> *messages))successBlock
  1625. error:(void(^)(int error_code))errorBlock {
  1626. std::list<int> convtypes;
  1627. for (NSNumber *ct in conversationTypes) {
  1628. convtypes.push_back([ct intValue]);
  1629. }
  1630. std::list<int> ls;
  1631. for (NSNumber *type in lines) {
  1632. ls.push_back([type intValue]);
  1633. }
  1634. std::list<int> status;
  1635. for (NSNumber *num in messageStatus) {
  1636. status.push_back(num.intValue);
  1637. }
  1638. bool direction = true;
  1639. if (count < 0) {
  1640. direction = false;
  1641. count = -count;
  1642. }
  1643. mars::stn::GetMessagesByMessageStatus(convtypes, ls, status, direction, (int)count, fromIndex, user ? [user UTF8String] : "", new IMLoadMessagesCallback(successBlock, errorBlock));
  1644. }
  1645. - (NSArray<WFCCMessage *> *)getUserMessages:(NSString *)userId
  1646. conversation:(WFCCConversation *)conversation
  1647. contentTypes:(NSArray<NSNumber *> *)contentTypes
  1648. from:(NSUInteger)fromIndex
  1649. count:(NSInteger)count {
  1650. if (!userId.length || !conversation.target.length) {
  1651. return nil;
  1652. }
  1653. std::list<int> types;
  1654. for (NSNumber *num in contentTypes) {
  1655. types.push_back(num.intValue);
  1656. }
  1657. bool direction = true;
  1658. if (count < 0) {
  1659. direction = false;
  1660. count = -count;
  1661. }
  1662. std::list<mars::stn::TMessage> messages = mars::stn::MessageDB::Instance()->GetUserMessages([userId UTF8String], (int)conversation.type, [conversation.target UTF8String], conversation.line, types, direction, (int)count, fromIndex);
  1663. return convertProtoMessageList(messages, YES);
  1664. }
  1665. - (void)getUserMessagesV2:(NSString *)userId
  1666. conversation:(WFCCConversation *)conversation
  1667. contentTypes:(NSArray<NSNumber *> *)contentTypes
  1668. from:(NSUInteger)fromIndex
  1669. count:(NSInteger)count
  1670. success:(void(^)(NSArray<WFCCMessage *> *messages))successBlock
  1671. error:(void(^)(int error_code))errorBlock {
  1672. std::list<int> types;
  1673. for (NSNumber *num in contentTypes) {
  1674. types.push_back(num.intValue);
  1675. }
  1676. bool direction = true;
  1677. if (count < 0) {
  1678. direction = false;
  1679. count = -count;
  1680. }
  1681. mars::stn::GetUserMessages([userId UTF8String], (int)conversation.type, [conversation.target UTF8String], conversation.line, types, direction, (int)count, fromIndex, new IMLoadMessagesCallback(successBlock, errorBlock));
  1682. }
  1683. - (NSArray<WFCCMessage *> *)getUserMessages:(NSString *)userId
  1684. conversationTypes:(NSArray<NSNumber *> *)conversationTypes
  1685. lines:(NSArray<NSNumber *> *)lines
  1686. contentTypes:(NSArray<NSNumber *> *)contentTypes
  1687. from:(NSUInteger)fromIndex
  1688. count:(NSInteger)count {
  1689. if (!userId.length || !conversationTypes.count) {
  1690. return nil;
  1691. }
  1692. std::list<int> convtypes;
  1693. for (NSNumber *ct in conversationTypes) {
  1694. convtypes.push_back([ct intValue]);
  1695. }
  1696. std::list<int> ls;
  1697. for (NSNumber *type in lines) {
  1698. ls.push_back([type intValue]);
  1699. }
  1700. std::list<int> types;
  1701. for (NSNumber *num in contentTypes) {
  1702. types.push_back(num.intValue);
  1703. }
  1704. bool direction = true;
  1705. if (count < 0) {
  1706. direction = false;
  1707. count = -count;
  1708. }
  1709. std::list<mars::stn::TMessage> messages = mars::stn::MessageDB::Instance()->GetUserMessages([userId UTF8String], convtypes, ls, types, direction, (int)count, fromIndex);
  1710. return convertProtoMessageList(messages, YES);
  1711. }
  1712. - (void)getUserMessagesV2:(NSString *)userId
  1713. conversationTypes:(NSArray<NSNumber *> *)conversationTypes
  1714. lines:(NSArray<NSNumber *> *)lines
  1715. contentTypes:(NSArray<NSNumber *> *)contentTypes
  1716. from:(NSUInteger)fromIndex
  1717. count:(NSInteger)count
  1718. success:(void(^)(NSArray<WFCCMessage *> *messages))successBlock
  1719. error:(void(^)(int error_code))errorBlock {
  1720. std::list<int> convtypes;
  1721. for (NSNumber *ct in conversationTypes) {
  1722. convtypes.push_back([ct intValue]);
  1723. }
  1724. std::list<int> ls;
  1725. for (NSNumber *type in lines) {
  1726. ls.push_back([type intValue]);
  1727. }
  1728. std::list<int> types;
  1729. for (NSNumber *num in contentTypes) {
  1730. types.push_back(num.intValue);
  1731. }
  1732. bool direction = true;
  1733. if (count < 0) {
  1734. direction = false;
  1735. count = -count;
  1736. }
  1737. mars::stn::GetUserMessages([userId UTF8String], convtypes, ls, types, direction, (int)count, fromIndex, new IMLoadMessagesCallback(successBlock, errorBlock));
  1738. }
  1739. - (void)getRemoteMessages:(WFCCConversation *)conversation
  1740. before:(long long)beforeMessageUid
  1741. count:(NSUInteger)count
  1742. contentTypes:(NSArray<NSNumber *> *)contentTypes
  1743. success:(void(^)(NSArray<WFCCMessage *> *messages))successBlock
  1744. error:(void(^)(int error_code))errorBlock {
  1745. mars::stn::TConversation conv;
  1746. conv.target = [conversation.target UTF8String];
  1747. conv.line = conversation.line;
  1748. conv.conversationType = (int)conversation.type;
  1749. std::list<int> types;
  1750. for (NSNumber *num in contentTypes) {
  1751. types.push_back(num.intValue);
  1752. }
  1753. mars::stn::loadRemoteMessages(conv, types, beforeMessageUid, (int)count, new IMLoadRemoteMessagesCallback(successBlock, errorBlock));
  1754. }
  1755. - (void)getRemoteMessage:(long long)messageUid
  1756. success:(void(^)(WFCCMessage *message))successBlock
  1757. error:(void(^)(int error_code))errorBlock {
  1758. mars::stn::loadRemoteMessage(messageUid, new IMLoadOneRemoteMessageCallback(successBlock, errorBlock));
  1759. }
  1760. - (WFCCMessage *)getMessage:(long)messageId {
  1761. mars::stn::TMessage tMsg = mars::stn::MessageDB::Instance()->GetMessageById(messageId);
  1762. return convertProtoMessage(&tMsg);
  1763. }
  1764. - (WFCCMessage *)getMessageByUid:(long long)messageUid {
  1765. mars::stn::TMessage tMsg = mars::stn::MessageDB::Instance()->GetMessageByUid(messageUid);
  1766. return convertProtoMessage(&tMsg);
  1767. }
  1768. - (WFCCUnreadCount *)getUnreadCount:(WFCCConversation *)conversation {
  1769. mars::stn::TUnreadCount tcount = mars::stn::MessageDB::Instance()->GetUnreadCount((int)conversation.type, [conversation.target UTF8String], conversation.line);
  1770. return [WFCCUnreadCount countOf:tcount.unread mention:tcount.unreadMention mentionAll:tcount.unreadMentionAll];
  1771. }
  1772. - (WFCCUnreadCount *)getUnreadCount:(NSArray<NSNumber *> *)conversationTypes lines:(NSArray<NSNumber *> *)lines {
  1773. std::list<int> types;
  1774. std::list<int> ls;
  1775. for (NSNumber *type in conversationTypes) {
  1776. types.insert(types.end(), type.intValue);
  1777. }
  1778. for (NSNumber *line in lines) {
  1779. ls.insert(ls.end(), line.intValue);
  1780. }
  1781. mars::stn::TUnreadCount tcount = mars::stn::MessageDB::Instance()->GetUnreadCount(types, ls);
  1782. return [WFCCUnreadCount countOf:tcount.unread mention:tcount.unreadMention mentionAll:tcount.unreadMentionAll];
  1783. }
  1784. - (void)clearUnreadStatus:(WFCCConversation *)conversation {
  1785. mars::stn::MessageDB::Instance()->ClearUnreadStatus((int)conversation.type, [conversation.target UTF8String], conversation.line);
  1786. }
  1787. - (void)clearUnreadStatus:(NSArray<NSNumber *> *)conversationTypes
  1788. lines:(NSArray<NSNumber *> *)lines {
  1789. std::list<int> types;
  1790. std::list<int> ls;
  1791. for (NSNumber *type in conversationTypes) {
  1792. types.insert(types.end(), type.intValue);
  1793. }
  1794. for (NSNumber *line in lines) {
  1795. ls.insert(ls.end(), line.intValue);
  1796. }
  1797. mars::stn::MessageDB::Instance()->ClearUnreadStatus(types, ls);
  1798. }
  1799. - (void)clearAllUnreadStatus {
  1800. mars::stn::MessageDB::Instance()->ClearAllUnreadStatus();
  1801. }
  1802. - (void)clearMessageUnreadStatus:(long)messageId {
  1803. if(messageId) {
  1804. mars::stn::MessageDB::Instance()->ClearUnreadStatus((int)messageId);
  1805. }
  1806. }
  1807. - (void)clearMessageUnreadStatusBefore:(long)messageId conversation:(WFCCConversation *)conversation {
  1808. if(messageId) {
  1809. mars::stn::MessageDB::Instance()->ClearUnreadStatusBeforeMessage((int)messageId, conversation.type, conversation.target?[conversation.target UTF8String]:"", conversation.line);
  1810. }
  1811. }
  1812. - (BOOL)markAsUnRead:(WFCCConversation *)conversation syncToOtherClient:(BOOL)sync {
  1813. int64_t messageUid = mars::stn::MessageDB::Instance()->SetLastReceivedMessageUnRead((int)conversation.type, [conversation.target UTF8String], conversation.line, 0, 0);
  1814. if(sync && messageUid) {
  1815. WFCCMarkUnreadMessageContent *syncMsg = [[WFCCMarkUnreadMessageContent alloc] init];
  1816. syncMsg.messageUid = messageUid;
  1817. syncMsg.timestamp = [self getMessageByUid:messageUid].serverTime;
  1818. [[WFCCIMService sharedWFCIMService] send:conversation content:syncMsg toUsers:@[[WFCCNetworkService sharedInstance].userId] expireDuration:86400 success:nil error:nil];
  1819. }
  1820. return messageUid > 0;
  1821. }
  1822. - (void)setMediaMessagePlayed:(long)messageId {
  1823. WFCCMessage *message = [self getMessage:messageId];
  1824. if (!message) {
  1825. return;
  1826. }
  1827. mars::stn::MessageDB::Instance()->updateMessageStatus(messageId, mars::stn::Message_Status_Played);
  1828. }
  1829. - (BOOL)setMessage:(long)messageId localExtra:(NSString *)extra {
  1830. return mars::stn::MessageDB::Instance()->setMessageLocalExtra(messageId, extra ? [extra UTF8String] : "") ? YES : NO;
  1831. }
  1832. - (NSMutableDictionary<NSString *, NSNumber *> *)getConversationRead:(WFCCConversation *)conversation {
  1833. std::map<std::string, int64_t> reads = mars::stn::MessageDB::Instance()->GetConversationRead((int)conversation.type, [conversation.target UTF8String], conversation.line);
  1834. NSMutableDictionary *ret = [[NSMutableDictionary alloc] init];
  1835. for (std::map<std::string, int64_t>::iterator it = reads.begin(); it != reads.end(); ++it) {
  1836. [ret setValue:@(it->second) forKey:[NSString stringWithUTF8String:it->first.c_str()]];
  1837. }
  1838. return ret;
  1839. }
  1840. - (NSMutableDictionary<NSString *, NSNumber *> *)getMessageDelivery:(WFCCConversation *)conversation {
  1841. std::map<std::string, int64_t> reads = mars::stn::MessageDB::Instance()->GetDelivery((int)conversation.type, [conversation.target UTF8String]);
  1842. NSMutableDictionary *ret = [[NSMutableDictionary alloc] init];
  1843. for (std::map<std::string, int64_t>::iterator it = reads.begin(); it != reads.end(); ++it) {
  1844. [ret setValue:@(it->second) forKey:[NSString stringWithUTF8String:it->first.c_str()]];
  1845. }
  1846. return ret;
  1847. }
  1848. - (BOOL)updateMessage:(long)messageId status:(WFCCMessageStatus)status {
  1849. bool updated = mars::stn::MessageDB::Instance()->updateMessageStatus(messageId, (mars::stn::MessageStatus)status);
  1850. if(updated) {
  1851. [[NSNotificationCenter defaultCenter] postNotificationName:kMessageUpdated object:@(messageId)];
  1852. }
  1853. return updated ? YES : NO;
  1854. }
  1855. - (void)removeConversation:(WFCCConversation *)conversation clearMessage:(BOOL)clearMessage {
  1856. mars::stn::MessageDB::Instance()->RemoveConversation((int)conversation.type, [conversation.target UTF8String], conversation.line, clearMessage);
  1857. }
  1858. - (void)clearMessages:(WFCCConversation *)conversation {
  1859. mars::stn::MessageDB::Instance()->ClearMessages((int)conversation.type, [conversation.target UTF8String], conversation.line);
  1860. }
  1861. - (void)clearMessages:(WFCCConversation *)conversation before:(int64_t)before {
  1862. mars::stn::MessageDB::Instance()->ClearMessages((int)conversation.type, conversation.target.length ? [conversation.target UTF8String] : "", conversation.line, before);
  1863. }
  1864. - (void)clearMessages:(WFCCConversation *)conversation keepLatest:(int)keepCount {
  1865. mars::stn::MessageDB::Instance()->ClearMessagesKeepLatest((int)conversation.type, conversation.target.length ? [conversation.target UTF8String] : "", conversation.line, keepCount);
  1866. }
  1867. - (void)clearMessages:(NSString *)userId start:(int64_t)start end:(int64_t)end {
  1868. mars::stn::MessageDB::Instance()->ClearUserMessages([userId UTF8String], start, end);
  1869. }
  1870. - (void)clearAllMessages:(BOOL)removeConversation {
  1871. mars::stn::MessageDB::Instance()->ClearAllMessages(removeConversation);
  1872. }
  1873. - (void)setConversation:(WFCCConversation *)conversation top:(int)top
  1874. success:(void(^)(void))successBlock
  1875. error:(void(^)(int error_code))errorBlock {
  1876. [self setUserSetting:(UserSettingScope)mars::stn::kUserSettingConversationTop key:[NSString stringWithFormat:@"%zd-%d-%@", conversation.type, conversation.line, conversation.target] value:[NSString stringWithFormat:@"%d", top] success:successBlock error:errorBlock];
  1877. }
  1878. - (void)setConversation:(WFCCConversation *)conversation draft:(NSString *)draft {
  1879. mars::stn::MessageDB::Instance()->updateConversationDraft((int)conversation.type, [conversation.target UTF8String], conversation.line, draft ? [draft UTF8String] : "");
  1880. }
  1881. - (void)setConversation:(WFCCConversation *)conversation
  1882. timestamp:(long long)timestamp {
  1883. mars::stn::MessageDB::Instance()->updateConversationTimestamp((int)conversation.type, [conversation.target UTF8String], conversation.line, timestamp);
  1884. }
  1885. - (long)getFirstUnreadMessageId:(WFCCConversation *)conversation {
  1886. return mars::stn::MessageDB::Instance()->GetConversationFirstUnreadMessageId((int)conversation.type, [conversation.target UTF8String], conversation.line);
  1887. }
  1888. - (void)clearRemoteConversationMessage:(WFCCConversation *)conversation
  1889. success:(void(^)(void))successBlock
  1890. error:(void(^)(int error_code))errorBlock {
  1891. mars::stn::clearRemoteConversationMessages((int)conversation.type, [conversation.target UTF8String], conversation.line, new IMGeneralOperationCallback(successBlock, errorBlock));
  1892. }
  1893. class IMSearchUserCallback : public mars::stn::SearchUserCallback {
  1894. private:
  1895. void(^m_successBlock)(NSArray<WFCCUserInfo *> *machedUsers);
  1896. void(^m_errorBlock)(int errorCode);
  1897. public:
  1898. IMSearchUserCallback(void(^successBlock)(NSArray<WFCCUserInfo *> *machedUsers), void(^errorBlock)(int errorCode)) : m_successBlock(successBlock), m_errorBlock(errorBlock) {}
  1899. void onSuccess(const std::list<mars::stn::TUserInfo> &users, const std::string &keyword, int page) {
  1900. NSMutableArray *outUsers = [[NSMutableArray alloc] initWithCapacity:users.size()];
  1901. for(std::list<mars::stn::TUserInfo>::const_iterator it = users.begin(); it != users.end(); it++) {
  1902. [outUsers addObject:convertUserInfo(*it)];
  1903. }
  1904. m_successBlock(outUsers);
  1905. delete this;
  1906. }
  1907. void onFalure(int errorCode) {
  1908. m_errorBlock(errorCode);
  1909. delete this;
  1910. }
  1911. ~IMSearchUserCallback() {}
  1912. };
  1913. - (void)searchUser:(NSString *)keyword
  1914. searchType:(WFCCSearchUserType)searchType
  1915. page:(int)page
  1916. success:(void(^)(NSArray<WFCCUserInfo *> *machedUsers))successBlock
  1917. error:(void(^)(int errorCode))errorBlock {
  1918. [self searchUser:keyword domain:nil searchType:searchType page:page success:successBlock error:errorBlock];
  1919. }
  1920. - (void)searchUser:(NSString *)keyword
  1921. domain:(NSString *)domainId
  1922. searchType:(WFCCSearchUserType)searchType
  1923. page:(int)page
  1924. success:(void(^)(NSArray<WFCCUserInfo *> *machedUsers))successBlock
  1925. error:(void(^)(int errorCode))errorBlock {
  1926. if(keyword.length == 0) {
  1927. successBlock(@[]);
  1928. }
  1929. if (self.userSource) {
  1930. [self.userSource searchUser:keyword domain:domainId searchType:searchType page:page success:successBlock error:errorBlock];
  1931. return;
  1932. }
  1933. mars::stn::searchUser(domainId?[domainId UTF8String]:"", keyword?[keyword UTF8String]:"", (int)searchType, page, new IMSearchUserCallback(successBlock, errorBlock));
  1934. }
  1935. class IMGetOneUserInfoCallback : public mars::stn::GetOneUserInfoCallback {
  1936. private:
  1937. void(^m_successBlock)(WFCCUserInfo *userInfo);
  1938. void(^m_errorBlock)(int errorCode);
  1939. public:
  1940. IMGetOneUserInfoCallback(void(^successBlock)(WFCCUserInfo *machedUsers), void(^errorBlock)(int errorCode)) : m_successBlock(successBlock), m_errorBlock(errorBlock) {}
  1941. void onSuccess(const mars::stn::TUserInfo &tUserInfo) {
  1942. if(m_successBlock) {
  1943. m_successBlock(convertUserInfo(tUserInfo));
  1944. }
  1945. delete this;
  1946. }
  1947. void onFalure(int errorCode) {
  1948. if(m_errorBlock) {
  1949. m_errorBlock(errorCode);
  1950. }
  1951. delete this;
  1952. }
  1953. ~IMGetOneUserInfoCallback() {}
  1954. };
  1955. class IMGetUserInfoCallback : public mars::stn::GetUserInfoCallback {
  1956. private:
  1957. void(^m_successBlock)(NSArray<WFCCUserInfo *> *userInfos);
  1958. void(^m_errorBlock)(int errorCode);
  1959. public:
  1960. IMGetUserInfoCallback(void(^successBlock)(NSArray<WFCCUserInfo *> *machedUsers), void(^errorBlock)(int errorCode)) : m_successBlock(successBlock), m_errorBlock(errorBlock) {}
  1961. void onSuccess(const std::list<mars::stn::TUserInfo> &userInfoList) {
  1962. if(m_successBlock) {
  1963. NSMutableArray<WFCCUserInfo *> *ret = [[NSMutableArray alloc] init];
  1964. for (std::list<mars::stn::TUserInfo>::const_iterator it = userInfoList.begin(); it != userInfoList.end(); it++) {
  1965. WFCCUserInfo *userInfo = convertUserInfo(*it);
  1966. [ret addObject:userInfo];
  1967. }
  1968. m_successBlock(ret);
  1969. }
  1970. delete this;
  1971. }
  1972. void onFalure(int errorCode) {
  1973. if(m_errorBlock) {
  1974. m_errorBlock(errorCode);
  1975. }
  1976. delete this;
  1977. }
  1978. ~IMGetUserInfoCallback() {}
  1979. };
  1980. - (void)getUserInfo:(NSString *)userId
  1981. refresh:(BOOL)refresh
  1982. success:(void(^)(WFCCUserInfo *userInfo))successBlock
  1983. error:(void(^)(int errorCode))errorBlock {
  1984. if (!userId.length) {
  1985. return;
  1986. }
  1987. if ([self.userSource respondsToSelector:@selector(getUserInfo:refresh:success:error:)]) {
  1988. [self.userSource getUserInfo:userId refresh:refresh success:successBlock error:errorBlock];
  1989. return;
  1990. }
  1991. mars::stn::MessageDB::Instance()->GetUserInfo([userId UTF8String], refresh ? true : false, new IMGetOneUserInfoCallback(successBlock, errorBlock));
  1992. }
  1993. - (void)getUserInfo:(NSString *)userId
  1994. groupId:(NSString *)groupId
  1995. refresh:(BOOL)refresh
  1996. success:(void(^)(WFCCUserInfo *userInfo))successBlock
  1997. error:(void(^)(int errorCode))errorBlock {
  1998. if (!userId.length) {
  1999. return;
  2000. }
  2001. if ([self.userSource respondsToSelector:@selector(getUserInfo:groupId:refresh:success:error:)]) {
  2002. [self.userSource getUserInfo:userId groupId:groupId refresh:refresh success:successBlock error:errorBlock];
  2003. return;
  2004. }
  2005. mars::stn::MessageDB::Instance()->GetUserInfo([userId UTF8String], groupId.length?[groupId UTF8String]:"", refresh ? true : false, new IMGetOneUserInfoCallback(successBlock, errorBlock));
  2006. }
  2007. - (void)getUserInfos:(NSArray<NSString *> *)userIds
  2008. groupId:(NSString *)groupId
  2009. success:(void(^)(NSArray<WFCCUserInfo *> *userInfo))successBlock
  2010. error:(void(^)(int errorCode))errorBlock {
  2011. if (!userIds.count) {
  2012. return;
  2013. }
  2014. if ([self.userSource respondsToSelector:@selector(getUserInfos:groupId:success:error:)]) {
  2015. [self.userSource getUserInfos:userIds groupId:groupId success:successBlock error:errorBlock];
  2016. return;
  2017. }
  2018. std::list<std::string> strIds;
  2019. for (NSString *userId in userIds) {
  2020. strIds.insert(strIds.end(), [userId UTF8String]);
  2021. }
  2022. mars::stn::MessageDB::Instance()->BatchGetUserInfos(strIds, groupId ? [groupId UTF8String] : "", new IMGetUserInfoCallback(successBlock, errorBlock));
  2023. }
  2024. - (BOOL)isMyFriend:(NSString *)userId {
  2025. if(!userId)
  2026. return NO;
  2027. return mars::stn::MessageDB::Instance()->isMyFriend([userId UTF8String]);
  2028. }
  2029. - (NSArray<NSString *> *)getMyFriendList:(BOOL)refresh {
  2030. NSMutableArray *ret = [[NSMutableArray alloc] init];
  2031. std::list<std::string> friendList = mars::stn::MessageDB::Instance()->getMyFriendList(refresh);
  2032. for (std::list<std::string>::iterator it = friendList.begin(); it != friendList.end(); it++) {
  2033. [ret addObject:[NSString stringWithUTF8String:(*it).c_str()]];
  2034. }
  2035. return ret;
  2036. }
  2037. - (NSArray<WFCCFriend *> *)getFriendList:(BOOL)refresh {
  2038. NSMutableArray *ret = [[NSMutableArray alloc] init];
  2039. std::list<mars::stn::TFriend> friendList = mars::stn::MessageDB::Instance()->getFriendList(refresh);
  2040. for (std::list<mars::stn::TFriend>::iterator it = friendList.begin(); it != friendList.end(); it++) {
  2041. WFCCFriend *f = [[WFCCFriend alloc] init];
  2042. f.userId = [NSString stringWithUTF8String:it->userId.c_str()];
  2043. f.alias = [NSString stringWithUTF8String:it->alias.c_str()];
  2044. f.extra = [NSString stringWithUTF8String:it->extra.c_str()];
  2045. f.timestamp = it->timestamp;
  2046. [ret addObject:f];
  2047. }
  2048. return ret;
  2049. }
  2050. - (NSArray<WFCCUserInfo *> *)searchFriends:(NSString *)keyword {
  2051. if(!keyword)
  2052. return nil;
  2053. std::list<mars::stn::TUserInfo> friends = mars::stn::MessageDB::Instance()->SearchFriends(keyword?[keyword UTF8String]:"", 50);
  2054. NSMutableArray<WFCCUserInfo *> *ret = [[NSMutableArray alloc] init];
  2055. for (std::list<mars::stn::TUserInfo>::iterator it = friends.begin(); it != friends.end(); it++) {
  2056. WFCCUserInfo *userInfo = convertUserInfo(*it);
  2057. if (userInfo) {
  2058. [ret addObject:userInfo];
  2059. }
  2060. }
  2061. return ret;
  2062. }
  2063. NSArray *convertProtoChannelMenu(const std::vector<mars::stn::TChannelMenu> &tms) {
  2064. NSMutableArray *arr = [[NSMutableArray alloc] init];
  2065. for (std::vector<mars::stn::TChannelMenu>::const_iterator it = tms.begin(); it != tms.end(); ++it) {
  2066. WFCCChannelMenu *cMenu = [[WFCCChannelMenu alloc] init];
  2067. cMenu.menuId = [NSString stringWithUTF8String:it->menuId.c_str()];
  2068. cMenu.type = [NSString stringWithUTF8String:it->type.c_str()];
  2069. cMenu.name = [NSString stringWithUTF8String:it->name.c_str()];
  2070. if(!it->key.empty()) cMenu.key = [NSString stringWithUTF8String:it->key.c_str()];
  2071. if(!it->url.empty()) cMenu.url = [NSString stringWithUTF8String:it->url.c_str()];
  2072. if(!it->mediaId.empty()) cMenu.mediaId = [NSString stringWithUTF8String:it->mediaId.c_str()];
  2073. if(!it->articleId.empty()) cMenu.articleId = [NSString stringWithUTF8String:it->articleId.c_str()];
  2074. if(!it->appId.empty()) cMenu.appId = [NSString stringWithUTF8String:it->appId.c_str()];
  2075. if(!it->appPage.empty()) cMenu.appPage = [NSString stringWithUTF8String:it->appPage.c_str()];
  2076. if(!it->extra.empty()) cMenu.extra = [NSString stringWithUTF8String:it->extra.c_str()];
  2077. if (!it->subMenus.empty()) {
  2078. cMenu.subMenus = convertProtoChannelMenu(it->subMenus);
  2079. }
  2080. [arr addObject:cMenu];
  2081. }
  2082. return arr;
  2083. }
  2084. WFCCChannelInfo *convertProtoChannelInfo(const mars::stn::TChannelInfo &tci) {
  2085. if (tci.channelId.empty()) {
  2086. return nil;
  2087. }
  2088. WFCCChannelInfo *channelInfo = [[WFCCChannelInfo alloc] init];
  2089. channelInfo.channelId = [NSString stringWithUTF8String:tci.channelId.c_str()];
  2090. channelInfo.desc = [NSString stringWithUTF8String:tci.desc.c_str()];
  2091. channelInfo.name = [NSString stringWithUTF8String:tci.name.c_str()];
  2092. channelInfo.extra = [NSString stringWithUTF8String:tci.extra.c_str()];
  2093. channelInfo.portrait = [NSString stringWithUTF8String:tci.portrait.c_str()];
  2094. channelInfo.owner = [NSString stringWithUTF8String:tci.owner.c_str()];
  2095. channelInfo.secret = [NSString stringWithUTF8String:tci.secret.c_str()];
  2096. channelInfo.callback = [NSString stringWithUTF8String:tci.callback.c_str()];
  2097. channelInfo.status = tci.status;
  2098. channelInfo.updateDt = tci.updateDt;
  2099. channelInfo.menus = convertProtoChannelMenu(tci.menus);
  2100. return channelInfo;
  2101. }
  2102. class IMCreateChannelCallback : public mars::stn::CreateChannelCallback {
  2103. private:
  2104. void(^m_successBlock)(WFCCChannelInfo *channelInfo);
  2105. void(^m_errorBlock)(int error_code);
  2106. public:
  2107. IMCreateChannelCallback(void(^successBlock)(WFCCChannelInfo *channelInfo), void(^errorBlock)(int error_code)) : mars::stn::CreateChannelCallback(), m_successBlock(successBlock), m_errorBlock(errorBlock) {};
  2108. void onSuccess(const mars::stn::TChannelInfo &channelInfo) {
  2109. WFCCChannelInfo *ci = convertProtoChannelInfo(channelInfo);
  2110. dispatch_async(dispatch_get_main_queue(), ^{
  2111. if (m_successBlock) {
  2112. m_successBlock(ci);
  2113. }
  2114. delete this;
  2115. });
  2116. }
  2117. void onFalure(int errorCode) {
  2118. dispatch_async(dispatch_get_main_queue(), ^{
  2119. if (m_errorBlock) {
  2120. m_errorBlock(errorCode);
  2121. }
  2122. delete this;
  2123. });
  2124. }
  2125. virtual ~IMCreateChannelCallback() {
  2126. m_successBlock = nil;
  2127. m_errorBlock = nil;
  2128. }
  2129. };
  2130. class IMSearchChannelCallback : public mars::stn::SearchChannelCallback {
  2131. private:
  2132. void(^m_successBlock)(NSArray<WFCCChannelInfo *> *machedChannels);
  2133. void(^m_errorBlock)(int errorCode);
  2134. public:
  2135. IMSearchChannelCallback(void(^successBlock)(NSArray<WFCCChannelInfo *> *machedUsers), void(^errorBlock)(int errorCode)) : m_successBlock(successBlock), m_errorBlock(errorBlock) {}
  2136. void onSuccess(const std::list<mars::stn::TChannelInfo> &users, const std::string &keyword) {
  2137. NSMutableArray *outUsers = [[NSMutableArray alloc] initWithCapacity:users.size()];
  2138. for(std::list<mars::stn::TChannelInfo>::const_iterator it = users.begin(); it != users.end(); it++) {
  2139. [outUsers addObject:convertProtoChannelInfo(*it)];
  2140. }
  2141. m_successBlock(outUsers);
  2142. delete this;
  2143. }
  2144. void onFalure(int errorCode) {
  2145. m_errorBlock(errorCode);
  2146. delete this;
  2147. }
  2148. ~IMSearchChannelCallback() {}
  2149. };
  2150. WFCCGroupInfo *convertProtoGroupInfo(const mars::stn::TGroupInfo &tgi) {
  2151. if (tgi.target.empty()) {
  2152. return nil;
  2153. }
  2154. WFCCGroupInfo *groupInfo = [[WFCCGroupInfo alloc] init];
  2155. groupInfo.type = (WFCCGroupType)tgi.type;
  2156. groupInfo.target = [NSString stringWithUTF8String:tgi.target.c_str()];
  2157. groupInfo.name = [NSString stringWithUTF8String:tgi.name.c_str()];
  2158. groupInfo.extra = [NSString stringWithUTF8String:tgi.extra.c_str()];;
  2159. groupInfo.portrait = [NSString stringWithUTF8String:tgi.portrait.c_str()];
  2160. groupInfo.owner = [NSString stringWithUTF8String:tgi.owner.c_str()];
  2161. groupInfo.remark = [NSString stringWithUTF8String:tgi.remark.c_str()];
  2162. groupInfo.memberCount = tgi.memberCount;
  2163. groupInfo.mute = tgi.mute;
  2164. groupInfo.joinType = tgi.joinType;
  2165. groupInfo.privateChat = tgi.privateChat;
  2166. groupInfo.searchable = tgi.searchable;
  2167. groupInfo.historyMessage = tgi.historyMessage;
  2168. groupInfo.maxMemberCount = tgi.maxMemberCount;
  2169. groupInfo.superGroup = tgi.superGroup;
  2170. groupInfo.deleted = tgi.deleted;
  2171. groupInfo.updateDt = tgi.updateDt;
  2172. groupInfo.memberDt = tgi.memberDt;
  2173. if(!groupInfo.portrait.length && [WFCCNetworkService sharedInstance].defaultPortraitProvider && [[WFCCNetworkService sharedInstance].defaultPortraitProvider respondsToSelector:@selector(groupDefaultPortrait:memberInfos:)]) {
  2174. __block NSMutableArray<WFCCUserInfo *> *memberUserInfos = [[NSMutableArray alloc] init];
  2175. __block BOOL pendding = NO;
  2176. [[[WFCCIMService sharedWFCIMService] getGroupMembers:groupInfo.target count:9] enumerateObjectsUsingBlock:^(WFCCGroupMember * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  2177. WFCCUserInfo *userInfo = [[WFCCIMService sharedWFCIMService] getUserInfo:obj.memberId refresh:NO];
  2178. if(userInfo) {
  2179. [memberUserInfos addObject:userInfo];
  2180. } else {
  2181. pendding = YES;
  2182. *stop = YES;
  2183. }
  2184. }];
  2185. if(!pendding) {
  2186. groupInfo.portrait = [[WFCCNetworkService sharedInstance].defaultPortraitProvider groupDefaultPortrait:groupInfo memberInfos:memberUserInfos];
  2187. }
  2188. }
  2189. return groupInfo;
  2190. }
  2191. - (NSArray<WFCCGroupSearchInfo *> *)searchGroups:(NSString *)keyword {
  2192. if(!keyword)
  2193. return nil;
  2194. std::list<mars::stn::TGroupSearchResult> groups = mars::stn::MessageDB::Instance()->SearchGroups(keyword?[keyword UTF8String]:"", 50);
  2195. NSMutableArray<WFCCGroupSearchInfo *> *ret = [[NSMutableArray alloc] init];
  2196. for (std::list<mars::stn::TGroupSearchResult>::iterator it = groups.begin(); it != groups.end(); it++) {
  2197. WFCCGroupSearchInfo *searchGroupInfo = [[WFCCGroupSearchInfo alloc] init];
  2198. searchGroupInfo.groupInfo = convertProtoGroupInfo(it->groupInfo);
  2199. searchGroupInfo.marchType = it->marchedType;
  2200. if (!it->marchedMemberNames.empty()) {
  2201. NSMutableArray *members = [[NSMutableArray alloc] init];
  2202. for (std::string name : it->marchedMemberNames) {
  2203. [members addObject:[NSString stringWithUTF8String:name.c_str()]];
  2204. }
  2205. searchGroupInfo.marchedMemberNames = [members copy];
  2206. }
  2207. searchGroupInfo.keyword = keyword;
  2208. [ret addObject:searchGroupInfo];
  2209. }
  2210. return ret;
  2211. }
  2212. - (void)loadFriendRequestFromRemote {
  2213. mars::stn::loadFriendRequestFromRemote();
  2214. }
  2215. - (NSArray<WFCCFriendRequest *> *)getIncommingFriendRequest {
  2216. std::list<mars::stn::TFriendRequest> tRequests = mars::stn::MessageDB::Instance()->getFriendRequest(1);
  2217. return convertFriendRequests(tRequests);
  2218. }
  2219. - (NSArray<WFCCFriendRequest *> *)getOutgoingFriendRequest {
  2220. std::list<mars::stn::TFriendRequest> tRequests = mars::stn::MessageDB::Instance()->getFriendRequest(0);
  2221. return convertFriendRequests(tRequests);
  2222. }
  2223. - (NSArray<WFCCFriendRequest *> *)getAllFriendRequest {
  2224. std::list<mars::stn::TFriendRequest> tRequests = mars::stn::MessageDB::Instance()->getFriendRequest(2);
  2225. return convertFriendRequests(tRequests);
  2226. }
  2227. - (WFCCFriendRequest *)getFriendRequest:(NSString *)userId direction:(int)direction {
  2228. if(!userId)
  2229. return nil;
  2230. mars::stn::TFriendRequest tRequest = mars::stn::MessageDB::Instance()->getFriendRequest([userId UTF8String], direction);
  2231. return convertFriendRequest(tRequest);
  2232. }
  2233. - (BOOL)clearFriendRequest:(int)direction beforeTime:(int64_t)beforeTime {
  2234. return mars::stn::MessageDB::Instance()->ClearFriendRequest(direction>0, beforeTime);
  2235. }
  2236. - (BOOL)deleteFriendRequest:(NSString *)userId direction:(int)direction {
  2237. if(!userId.length)
  2238. return false;
  2239. return mars::stn::MessageDB::Instance()->DeleteFriendRequest([userId UTF8String], direction>0);
  2240. }
  2241. - (void)clearUnreadFriendRequestStatus {
  2242. mars::stn::MessageDB::Instance()->clearUnreadFriendRequestStatus();
  2243. }
  2244. - (int)getUnreadFriendRequestStatus {
  2245. return mars::stn::MessageDB::Instance()->unreadFriendRequest();
  2246. }
  2247. - (void)sendFriendRequest:(NSString *)userId
  2248. reason:(NSString *)reason
  2249. extra:(NSString *)extra
  2250. success:(void(^)())successBlock
  2251. error:(void(^)(int error_code))errorBlock {
  2252. if(!userId) {
  2253. if(errorBlock) {
  2254. errorBlock(-1);
  2255. }
  2256. return;
  2257. }
  2258. mars::stn::sendFriendRequest([userId UTF8String], reason ? [reason UTF8String] : "", extra ? [extra UTF8String] : "", new IMGeneralOperationCallback(successBlock, errorBlock));
  2259. }
  2260. - (void)handleFriendRequest:(NSString *)userId
  2261. accept:(BOOL)accpet
  2262. extra:(NSString *)extra
  2263. success:(void(^)())successBlock
  2264. error:(void(^)(int error_code))errorBlock {
  2265. if(!userId) {
  2266. if(errorBlock) {
  2267. errorBlock(-1);
  2268. }
  2269. return;
  2270. }
  2271. mars::stn::handleFriendRequest([userId UTF8String], accpet, extra ? [extra UTF8String] : "", new IMGeneralOperationCallback(successBlock, errorBlock));
  2272. }
  2273. - (void)deleteFriend:(NSString *)userId
  2274. success:(void(^)())successBlock
  2275. error:(void(^)(int error_code))errorBlock {
  2276. if(!userId) {
  2277. if(errorBlock) {
  2278. errorBlock(-1);
  2279. }
  2280. return;
  2281. }
  2282. mars::stn::deleteFriend([userId UTF8String], new IMGeneralOperationCallback(successBlock, errorBlock));
  2283. }
  2284. - (NSString *)getFriendAlias:(NSString *)friendId {
  2285. if(!friendId) {
  2286. return nil;
  2287. }
  2288. std::string strAlias = mars::stn::MessageDB::Instance()->GetFriendAlias([friendId UTF8String]);
  2289. return [NSString stringWithUTF8String:strAlias.c_str()];
  2290. }
  2291. - (void)setFriend:(NSString *)friendId
  2292. alias:(NSString *)alias
  2293. success:(void(^)(void))successBlock
  2294. error:(void(^)(int error_code))errorBlock {
  2295. if(!friendId) {
  2296. if(errorBlock) {
  2297. errorBlock(-1);
  2298. }
  2299. return;
  2300. }
  2301. mars::stn::setFriendAlias([friendId UTF8String], alias ? [alias UTF8String] : "", new IMGeneralOperationCallback(successBlock, errorBlock));
  2302. }
  2303. - (NSString *)getFriendExtra:(NSString *)friendId {
  2304. if(!friendId)
  2305. return nil;
  2306. std::string extra = mars::stn::MessageDB::Instance()->GetFriendExtra([friendId UTF8String]);
  2307. return [NSString stringWithUTF8String:extra.c_str()];
  2308. }
  2309. - (BOOL)isBlackListed:(NSString *)userId {
  2310. if(!userId)
  2311. return NO;
  2312. return mars::stn::MessageDB::Instance()->isBlackListed([userId UTF8String]);
  2313. }
  2314. - (NSArray<NSString *> *)getBlackList:(BOOL)refresh {
  2315. NSMutableArray *ret = [[NSMutableArray alloc] init];
  2316. std::list<std::string> friendList = mars::stn::MessageDB::Instance()->getBlackList(refresh);
  2317. for (std::list<std::string>::iterator it = friendList.begin(); it != friendList.end(); it++) {
  2318. [ret addObject:[NSString stringWithUTF8String:(*it).c_str()]];
  2319. }
  2320. return ret;
  2321. }
  2322. - (void)setBlackList:(NSString *)userId
  2323. isBlackListed:(BOOL)isBlackListed
  2324. success:(void(^)(void))successBlock
  2325. error:(void(^)(int error_code))errorBlock {
  2326. if(!userId) {
  2327. if(errorBlock) {
  2328. errorBlock(-1);
  2329. }
  2330. return;
  2331. }
  2332. mars::stn::blackListRequest([userId UTF8String], isBlackListed, new IMGeneralOperationCallback(successBlock, errorBlock));
  2333. }
  2334. - (WFCCUserInfo *)getUserInfo:(NSString *)userId refresh:(BOOL)refresh {
  2335. if (!userId) {
  2336. return nil;
  2337. }
  2338. if ([self.userSource respondsToSelector:@selector(getUserInfo:refresh:)]) {
  2339. return [self.userSource getUserInfo:userId refresh:refresh];
  2340. }
  2341. return [self getUserInfo:userId inGroup:nil refresh:refresh];
  2342. }
  2343. - (WFCCUserInfo *)getUserInfo:(NSString *)userId inGroup:(NSString *)groupId refresh:(BOOL)refresh {
  2344. if (!userId) {
  2345. return nil;
  2346. }
  2347. if ([self.userSource respondsToSelector:@selector(getUserInfo:inGroup:refresh:)]) {
  2348. return [self.userSource getUserInfo:userId inGroup:groupId refresh:refresh];
  2349. }
  2350. mars::stn::TUserInfo tui = mars::stn::MessageDB::Instance()->getUserInfo([userId UTF8String], groupId ? [groupId UTF8String] : "", refresh);
  2351. if (!tui.uid.empty()) {
  2352. WFCCUserInfo *userInfo = convertUserInfo(tui);
  2353. return userInfo;
  2354. }
  2355. return nil;
  2356. }
  2357. - (NSArray<WFCCUserInfo *> *)getUserInfos:(NSArray<NSString *> *)userIds inGroup:(NSString *)groupId {
  2358. if ([userIds count] == 0) {
  2359. return nil;
  2360. }
  2361. if ([self.userSource respondsToSelector:@selector(getUserInfos:inGroup:)]) {
  2362. return [self.userSource getUserInfos:userIds inGroup:groupId];;
  2363. }
  2364. std::list<std::string> strIds;
  2365. for (NSString *userId in userIds) {
  2366. strIds.insert(strIds.end(), [userId UTF8String]);
  2367. }
  2368. std::list<mars::stn::TUserInfo> tuis = mars::stn::MessageDB::Instance()->getUserInfos(strIds, groupId ? [groupId UTF8String] : "");
  2369. NSMutableArray<WFCCUserInfo *> *ret = [[NSMutableArray alloc] init];
  2370. for (std::list<mars::stn::TUserInfo>::iterator it = tuis.begin(); it != tuis.end(); it++) {
  2371. WFCCUserInfo *userInfo = convertUserInfo(*it);
  2372. [ret addObject:userInfo];
  2373. }
  2374. return ret;
  2375. }
  2376. - (void)uploadMedia:(NSString *)fileName
  2377. mediaData:(NSData *)mediaData
  2378. mediaType:(WFCCMediaType)mediaType
  2379. success:(void(^)(NSString *remoteUrl))successBlock
  2380. progress:(void(^)(long uploaded, long total))progressBlock
  2381. error:(void(^)(int error_code))errorBlock {
  2382. BOOL largeMedia = NO;
  2383. if ([[WFCCNetworkService sharedInstance] isTcpShortLink]) {
  2384. if ([self isSupportBigFilesUpload]) {
  2385. largeMedia = YES;
  2386. } else {
  2387. NSLog(@"TCP短连接不支持内置对象存储,请把对象存储切换到其他类型");
  2388. errorBlock(-1);
  2389. return;
  2390. }
  2391. } else if([self isSupportBigFilesUpload]) {
  2392. if(mars::stn::ForcePresignedUrlUpload()) {
  2393. largeMedia = YES;
  2394. } else {
  2395. largeMedia = mediaData.length > 100000000L;
  2396. }
  2397. }
  2398. if(largeMedia) {
  2399. __weak typeof(self)ws = self;
  2400. [self getUploadUrl:@"" mediaType:mediaType contentType:nil success:^(NSString *uploadUrl, NSString *downloadUrl, NSString *backupUploadUrl, int type) {
  2401. NSString *url = ([WFCCNetworkService sharedInstance].connectedToMainNetwork || !backupUploadUrl.length)?uploadUrl:backupUploadUrl;
  2402. if(type == 1) {
  2403. [ws uploadQiniuData:mediaData url:url remoteUrl:downloadUrl success:successBlock progress:progressBlock error:errorBlock];
  2404. return;
  2405. } else {
  2406. [ws uploadData:mediaData url:url remoteUrl:downloadUrl success:successBlock progress:progressBlock error:errorBlock];
  2407. }
  2408. } error:^(int error_code) {
  2409. errorBlock(error_code);
  2410. }];
  2411. } else {
  2412. mars::stn::uploadGeneralMedia(fileName == nil ? "" : [fileName UTF8String], std::string((char *)mediaData.bytes, mediaData.length), (int)mediaType, new GeneralUpdateMediaCallback(successBlock, progressBlock, errorBlock));
  2413. }
  2414. }
  2415. - (void)uploadMediaFile:(NSString *)filePath
  2416. mediaType:(WFCCMediaType)mediaType
  2417. success:(void(^)(NSString *remoteUrl))successBlock
  2418. progress:(void(^)(long uploaded, long total))progressBlock
  2419. error:(void(^)(int error_code))errorBlock {
  2420. NSFileManager *fileManager = [NSFileManager defaultManager];
  2421. NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:filePath error:nil];
  2422. NSNumber *fileSizeNumber = [fileAttributes objectForKey:NSFileSize];
  2423. long long fileSize = [fileSizeNumber longLongValue];
  2424. BOOL largeMedia = NO;
  2425. if ([[WFCCNetworkService sharedInstance] isTcpShortLink]) {
  2426. if ([self isSupportBigFilesUpload]) {
  2427. largeMedia = YES;
  2428. } else {
  2429. NSLog(@"TCP短连接不支持内置对象存储,请把对象存储切换到其他类型");
  2430. errorBlock(-1);
  2431. return;
  2432. }
  2433. } else if([self isSupportBigFilesUpload]) {
  2434. if(mars::stn::ForcePresignedUrlUpload()) {
  2435. largeMedia = YES;
  2436. } else {
  2437. largeMedia = fileSize > 100000000L;
  2438. }
  2439. }
  2440. if(largeMedia) {
  2441. __weak typeof(self)ws = self;
  2442. NSString *fileContentTypeString = [self mimeTypeOfFile:filePath];
  2443. [self getUploadUrl:[filePath lastPathComponent] mediaType:mediaType contentType:fileContentTypeString success:^(NSString *uploadUrl, NSString *downloadUrl, NSString *backupUploadUrl, int type) {
  2444. NSString *url = ([WFCCNetworkService sharedInstance].connectedToMainNetwork || !backupUploadUrl.length)?uploadUrl:backupUploadUrl;
  2445. if(type == 1) {
  2446. [ws uploadQiniuFile:url file:filePath fileSize:(int)fileSize remoteUrl:downloadUrl success:successBlock progress:progressBlock error:errorBlock];
  2447. } else {
  2448. [ws uploadFile:url file:filePath fileContentType:fileContentTypeString fileSize:(int)fileSize remoteUrl:downloadUrl success:successBlock progress:progressBlock error:errorBlock];
  2449. }
  2450. } error:^(int error_code) {
  2451. errorBlock(error_code);
  2452. }];
  2453. } else {
  2454. NSData *mediaData = [NSData dataWithContentsOfFile:filePath];
  2455. mars::stn::uploadGeneralMedia([[filePath lastPathComponent] UTF8String], std::string((char *)mediaData.bytes, mediaData.length), (int)mediaType, new GeneralUpdateMediaCallback(successBlock, progressBlock, errorBlock));
  2456. }
  2457. }
  2458. - (BOOL)syncUploadMedia:(NSString *)fileName
  2459. mediaData:(NSData *)mediaData
  2460. mediaType:(WFCCMediaType)mediaType
  2461. success:(void(^)(NSString *remoteUrl))successBlock
  2462. progress:(void(^)(long uploaded, long total))progressBlock
  2463. error:(void(^)(int error_code))errorBlock {
  2464. NSCondition *condition = [[NSCondition alloc] init];
  2465. __block BOOL success = NO;
  2466. [condition lock];
  2467. [[WFCCIMService sharedWFCIMService] uploadMedia:fileName mediaData:mediaData mediaType:mediaType success:^(NSString *remoteUrl) {
  2468. successBlock(remoteUrl);
  2469. success = YES;
  2470. [condition lock];
  2471. [condition signal];
  2472. [condition unlock];
  2473. } progress:^(long uploaded, long total) {
  2474. progressBlock(uploaded, total);
  2475. } error:^(int error_code) {
  2476. errorBlock(error_code);
  2477. success = NO;
  2478. [condition lock];
  2479. [condition signal];
  2480. [condition unlock];
  2481. }];
  2482. [condition wait];
  2483. [condition unlock];
  2484. return success;
  2485. }
  2486. - (void)getUploadUrl:(NSString *)fileName
  2487. mediaType:(WFCCMediaType)mediaType
  2488. contentType:(NSString *)contentType
  2489. success:(void(^)(NSString *uploadUrl, NSString *downloadUrl, NSString *backupUploadUrl, int type))successBlock
  2490. error:(void(^)(int error_code))errorBlock {
  2491. mars::stn::getUploadMediaUrl(fileName == nil ? "" : [fileName UTF8String], (int)mediaType, contentType == nil ? "" : [contentType UTF8String], new IMGetUploadMediaUrlCallback(successBlock, errorBlock));
  2492. }
  2493. - (BOOL)isSupportBigFilesUpload {
  2494. return mars::stn::HasMediaPresignedUrl() ? YES : NO;
  2495. }
  2496. -(void)modifyMyInfo:(NSDictionary<NSNumber */*ModifyMyInfoType*/, NSString *> *)values
  2497. success:(void(^)())successBlock
  2498. error:(void(^)(int error_code))errorBlock {
  2499. if (self.userSource) {
  2500. [self.userSource modifyMyInfo:values success:successBlock error:errorBlock];
  2501. return;
  2502. }
  2503. std::list<std::pair<int, std::string>> infos;
  2504. for(NSNumber *key in values.allKeys) {
  2505. infos.push_back(std::pair<int, std::string>([key intValue], [values[key] UTF8String]));
  2506. }
  2507. mars::stn::modifyMyInfo(infos, new IMGeneralOperationCallback(successBlock, errorBlock));
  2508. }
  2509. - (BOOL)isGlobalSilent {
  2510. NSString *strValue = [[WFCCIMService sharedWFCIMService] getUserSetting:UserSettingScope_Global_Silent key:@""];
  2511. return [strValue isEqualToString:@"1"];
  2512. }
  2513. - (void)setGlobalSilent:(BOOL)silent
  2514. success:(void(^)(void))successBlock
  2515. error:(void(^)(int error_code))errorBlock {
  2516. [[WFCCIMService sharedWFCIMService] setUserSetting:UserSettingScope_Global_Silent key:@"" value:silent?@"1":@"0" success:^{
  2517. if (successBlock) {
  2518. successBlock();
  2519. }
  2520. } error:^(int error_code) {
  2521. if (errorBlock) {
  2522. errorBlock(error_code);
  2523. }
  2524. }];
  2525. }
  2526. - (BOOL)isVoipNotificationSilent {
  2527. NSString *strValue = [[WFCCIMService sharedWFCIMService] getUserSetting:UserSettingScope_Voip_Silent key:@""];
  2528. return [strValue isEqualToString:@"1"];
  2529. }
  2530. - (void)setVoipNotificationSilent:(BOOL)silent
  2531. success:(void(^)(void))successBlock
  2532. error:(void(^)(int error_code))errorBlock {
  2533. [[WFCCIMService sharedWFCIMService] setUserSetting:UserSettingScope_Voip_Silent key:@"" value:silent?@"1":@"0" success:^{
  2534. if (successBlock) {
  2535. successBlock();
  2536. }
  2537. } error:^(int error_code) {
  2538. if (errorBlock) {
  2539. errorBlock(error_code);
  2540. }
  2541. }];
  2542. }
  2543. - (BOOL)isEnableSyncDraft {
  2544. NSString *strValue = [[WFCCIMService sharedWFCIMService] getUserSetting:UserSettingScope_Disable_Sync_Draft key:@""];
  2545. return ![strValue isEqualToString:@"1"];
  2546. }
  2547. - (void)setEnableSyncDraft:(BOOL)enable
  2548. success:(void(^)(void))successBlock
  2549. error:(void(^)(int error_code))errorBlock {
  2550. [[WFCCIMService sharedWFCIMService] setUserSetting:UserSettingScope_Disable_Sync_Draft key:@"" value:enable?@"0":@"1" success:^{
  2551. if (successBlock) {
  2552. successBlock();
  2553. }
  2554. } error:^(int error_code) {
  2555. if (errorBlock) {
  2556. errorBlock(error_code);
  2557. }
  2558. }];
  2559. }
  2560. - (BOOL)isUserEnableReceipt {
  2561. NSString *strValue = [[WFCCIMService sharedWFCIMService] getUserSetting:UserSettingScope_DisableRecipt key:@""];
  2562. return ![strValue isEqualToString:@"1"];
  2563. }
  2564. - (void)setUserEnableReceipt:(BOOL)enable
  2565. success:(void(^)(void))successBlock
  2566. error:(void(^)(int error_code))errorBlock {
  2567. [[WFCCIMService sharedWFCIMService] setUserSetting:UserSettingScope_DisableRecipt key:@"" value:enable?@"0":@"1" success:^{
  2568. if (successBlock) {
  2569. successBlock();
  2570. }
  2571. } error:^(int error_code) {
  2572. if (errorBlock) {
  2573. errorBlock(error_code);
  2574. }
  2575. }];
  2576. }
  2577. - (BOOL)isAddFriendNeedVerify {
  2578. NSString *strValue = [[WFCCIMService sharedWFCIMService] getUserSetting:UserSettingScope_AddFriend_NoVerify key:@""];
  2579. return ![strValue isEqualToString:@"1"];
  2580. }
  2581. - (void)setAddFriendNeedVerify:(BOOL)enable
  2582. success:(void(^)(void))successBlock
  2583. error:(void(^)(int error_code))errorBlock {
  2584. [[WFCCIMService sharedWFCIMService] setUserSetting:UserSettingScope_AddFriend_NoVerify key:@"" value:enable?@"0":@"1" success:^{
  2585. if (successBlock) {
  2586. successBlock();
  2587. }
  2588. } error:^(int error_code) {
  2589. if (errorBlock) {
  2590. errorBlock(error_code);
  2591. }
  2592. }];
  2593. }
  2594. - (void)getNoDisturbingTimes:(void(^)(int startMins, int endMins))resultBlock
  2595. error:(void(^)(int error_code))errorBlock {
  2596. NSString *strValue = [[WFCCIMService sharedWFCIMService] getUserSetting:UserSettingScope_No_Disturbing key:@""];
  2597. if (strValue.length) {
  2598. NSArray<NSString *> *arrs = [strValue componentsSeparatedByString:@"|"];
  2599. if (arrs.count == 2) {
  2600. int startMins = [arrs[0] intValue];
  2601. int endMins = [arrs[1] intValue];
  2602. resultBlock(startMins, endMins);
  2603. } else {
  2604. if(errorBlock) {
  2605. errorBlock(-1);
  2606. }
  2607. }
  2608. } else {
  2609. if(errorBlock) {
  2610. errorBlock(-1);
  2611. }
  2612. }
  2613. }
  2614. - (void)setNoDisturbingTimes:(int)startMins
  2615. endMins:(int)endMins
  2616. success:(void(^)(void))successBlock
  2617. error:(void(^)(int error_code))errorBlock {
  2618. [[WFCCIMService sharedWFCIMService] setUserSetting:UserSettingScope_No_Disturbing key:@"" value:[NSString stringWithFormat:@"%d|%d", startMins, endMins] success:successBlock error:errorBlock];
  2619. }
  2620. - (void)clearNoDisturbingTimes:(void(^)(void))successBlock
  2621. error:(void(^)(int error_code))errorBlock {
  2622. [[WFCCIMService sharedWFCIMService] setUserSetting:UserSettingScope_No_Disturbing key:@"" value:@"" success:successBlock error:errorBlock];
  2623. }
  2624. - (BOOL)isNoDisturbing {
  2625. __block BOOL isNoDisturbing = NO;
  2626. [self getNoDisturbingTimes:^(int startMins, int endMins) {
  2627. NSCalendar *calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
  2628. NSDateComponents *nowCmps = [calendar components:NSCalendarUnitHour|NSCalendarUnitMinute fromDate:[NSDate date]];
  2629. int nowMins = (int)(nowCmps.hour * 60 + nowCmps.minute);
  2630. if (endMins > startMins) {
  2631. if (endMins > nowMins && nowMins > startMins) {
  2632. isNoDisturbing = YES;
  2633. }
  2634. } else {
  2635. if (endMins > nowMins || nowMins > startMins) {
  2636. isNoDisturbing = YES;
  2637. }
  2638. }
  2639. } error:^(int error_code) {
  2640. }];
  2641. return isNoDisturbing;
  2642. }
  2643. - (BOOL)isHiddenNotificationDetail {
  2644. NSString *strValue = [[WFCCIMService sharedWFCIMService] getUserSetting:UserSettingScope_Hidden_Notification_Detail key:@""];
  2645. return [strValue isEqualToString:@"1"];
  2646. }
  2647. - (void)setHiddenNotificationDetail:(BOOL)hidden
  2648. success:(void(^)(void))successBlock
  2649. error:(void(^)(int error_code))errorBlock {
  2650. [[WFCCIMService sharedWFCIMService] setUserSetting:UserSettingScope_Hidden_Notification_Detail key:@"" value:hidden?@"1":@"0" success:^{
  2651. if (successBlock) {
  2652. successBlock();
  2653. }
  2654. } error:^(int error_code) {
  2655. if (errorBlock) {
  2656. errorBlock(error_code);
  2657. }
  2658. }];
  2659. }
  2660. //UserSettingScope_Hidden_Notification_Detail = 4,
  2661. - (BOOL)isHiddenGroupMemberName:(NSString *)groupId {
  2662. NSString *strValue = [[WFCCIMService sharedWFCIMService] getUserSetting:UserSettingScope_Group_Hide_Nickname key:groupId];
  2663. return [strValue isEqualToString:@"1"];
  2664. }
  2665. - (void)setHiddenGroupMemberName:(BOOL)hidden
  2666. group:(NSString *)groupId
  2667. success:(void(^)(void))successBlock
  2668. error:(void(^)(int error_code))errorBlock {
  2669. [[WFCCIMService sharedWFCIMService] setUserSetting:UserSettingScope_Group_Hide_Nickname key:groupId value:hidden?@"1":@"0" success:^{
  2670. if (successBlock) {
  2671. successBlock();
  2672. }
  2673. } error:^(int error_code) {
  2674. if (errorBlock) {
  2675. errorBlock(error_code);
  2676. }
  2677. }];
  2678. }
  2679. -(void)getMyGroups:(void(^)(NSArray<NSString *> *))successBlock
  2680. error:(void(^)(int error_code))errorBlock {
  2681. mars::stn::getMyGroups(new IMGeneralStringListCallback(successBlock, errorBlock));
  2682. }
  2683. - (void)getCommonGroups:(NSString *)userId
  2684. success:(void(^)(NSArray<NSString *> *))successBlock
  2685. error:(void(^)(int error_code))errorBlock {
  2686. mars::stn::getCommonGroups([userId UTF8String], new IMGeneralStringListCallback(successBlock, errorBlock));
  2687. }
  2688. - (BOOL)deleteMessage:(long)messageId {
  2689. return mars::stn::MessageDB::Instance()->DeleteMessage(messageId) > 0;
  2690. }
  2691. - (BOOL)batchDeleteMessages:(NSArray<NSNumber *> *)messageUids {
  2692. std::list<int64_t> uids;
  2693. for (NSNumber *uid in messageUids) {
  2694. uids.push_back([uid longLongValue]);
  2695. }
  2696. return mars::stn::MessageDB::Instance()->BatchDeleteMessage(uids);
  2697. }
  2698. - (void)deleteRemoteMessage:(long long)messageUid
  2699. success:(void(^)(void))successBlock
  2700. error:(void(^)(int error_code))errorBlock {
  2701. mars::stn::deleteRemoteMessage(messageUid, new IMGeneralOperationCallback(successBlock, errorBlock));
  2702. }
  2703. - (void)updateRemoteMessage:(long long)messageUid
  2704. content:(WFCCMessageContent *)content
  2705. distribute:(BOOL)distribute
  2706. updateLocal:(BOOL)updateLocal
  2707. success:(void(^)(void))successBlock
  2708. error:(void(^)(int error_code))errorBlock {
  2709. mars::stn::TMessageContent tcontent;
  2710. fillTMessageContent(tcontent, content);
  2711. mars::stn::updateRemoteMessageContent(messageUid, tcontent, distribute, updateLocal, new IMGeneralOperationCallback(successBlock, errorBlock));
  2712. }
  2713. - (NSArray<WFCCConversationSearchInfo *> *)searchConversation:(NSString *)keyword inConversation:(NSArray<NSNumber *> *)conversationTypes lines:(NSArray<NSNumber *> *)lines {
  2714. return [self searchConversation:keyword inConversation:conversationTypes lines:lines startTime:0 endTime:0 desc:YES limit:50 offset:0];
  2715. }
  2716. - (NSArray<WFCCConversationSearchInfo *> *)searchConversation:(NSString *)keyword inConversation:(NSArray<NSNumber *> *)conversationTypes lines:(NSArray<NSNumber *> *)lines startTime:(int64_t)startTime endTime:(int64_t)endTime desc:(BOOL)desc limit:(int)limit offset:(int)offset {
  2717. std::list<int> types;
  2718. std::list<int> ls;
  2719. for (NSNumber *type in conversationTypes) {
  2720. types.insert(types.end(), type.intValue);
  2721. }
  2722. for (NSNumber *line in lines) {
  2723. ls.insert(ls.end(), line.intValue);
  2724. }
  2725. if(lines.count == 0) {
  2726. ls.insert(ls.end(), 0);
  2727. }
  2728. std::list<mars::stn::TConversationSearchresult> tresult = mars::stn::MessageDB::Instance()->SearchConversationsEx(types, ls, keyword?[keyword UTF8String]:"", startTime, endTime, desc?YES:NO, limit, offset);
  2729. NSMutableArray *results = [[NSMutableArray alloc] init];
  2730. for (std::list<mars::stn::TConversationSearchresult>::iterator it = tresult.begin(); it != tresult.end(); it++) {
  2731. WFCCConversationSearchInfo *info = [[WFCCConversationSearchInfo alloc] init];
  2732. [results addObject:info];
  2733. info.conversation = [[WFCCConversation alloc] init];
  2734. info.conversation.type = (WFCCConversationType)(it->conversationType);
  2735. info.conversation.target = [NSString stringWithUTF8String:it->target.c_str()];
  2736. info.conversation.line = it->line;
  2737. info.marchedCount = it->marchedCount;
  2738. info.marchedMessage = convertProtoMessage(&(it->marchedMessage));
  2739. info.keyword = keyword;
  2740. info.timestamp = it->timestamp;
  2741. }
  2742. return results;
  2743. }
  2744. - (NSArray<WFCCConversationSearchInfo *> *)searchConversation:(NSString *)keyword
  2745. inConversation:(NSArray<NSNumber *> *)conversationTypes
  2746. lines:(NSArray<NSNumber *> *)lines
  2747. cntTypes:(NSArray<NSNumber *> *)cntTypes
  2748. startTime:(int64_t)startTime
  2749. endTime:(int64_t)endTime
  2750. desc:(BOOL)desc
  2751. limit:(int)limit
  2752. offset:(int)offset
  2753. onlyMentionedMsg:(BOOL)onlyMentionedMsg {
  2754. std::list<int> types;
  2755. std::list<int> ls;
  2756. std::list<int> cnts;
  2757. for (NSNumber *type in conversationTypes) {
  2758. types.insert(types.end(), type.intValue);
  2759. }
  2760. for (NSNumber *line in lines) {
  2761. ls.insert(ls.end(), line.intValue);
  2762. }
  2763. if(lines.count == 0) {
  2764. ls.insert(ls.end(), 0);
  2765. }
  2766. for (NSNumber *cnt in cntTypes) {
  2767. cnts.insert(cnts.end(), cnt.intValue);
  2768. }
  2769. std::list<mars::stn::TConversationSearchresult> tresult = mars::stn::MessageDB::Instance()->SearchConversationsEx2(types, ls, keyword?[keyword UTF8String]:"", cnts, startTime, endTime, desc?YES:NO, limit, offset, onlyMentionedMsg?YES:NO);
  2770. NSMutableArray *results = [[NSMutableArray alloc] init];
  2771. for (std::list<mars::stn::TConversationSearchresult>::iterator it = tresult.begin(); it != tresult.end(); it++) {
  2772. WFCCConversationSearchInfo *info = [[WFCCConversationSearchInfo alloc] init];
  2773. [results addObject:info];
  2774. info.conversation = [[WFCCConversation alloc] init];
  2775. info.conversation.type = (WFCCConversationType)(it->conversationType);
  2776. info.conversation.target = [NSString stringWithUTF8String:it->target.c_str()];
  2777. info.conversation.line = it->line;
  2778. info.marchedCount = it->marchedCount;
  2779. info.marchedMessage = convertProtoMessage(&(it->marchedMessage));
  2780. info.keyword = keyword;
  2781. }
  2782. return results;
  2783. }
  2784. - (NSArray<WFCCMessage *> *)searchMessage:(WFCCConversation *)conversation
  2785. keyword:(NSString *)keyword
  2786. order:(BOOL)desc
  2787. limit:(int)limit
  2788. offset:(int)offset
  2789. withUser:(NSString *)withUser {
  2790. std::list<mars::stn::TMessage> tmessages = mars::stn::MessageDB::Instance()->SearchMessages((int)conversation.type, conversation.target ? [conversation.target UTF8String] : "", conversation.line, keyword?[keyword UTF8String]:"", desc ? true : false, limit, offset, withUser.length?[withUser UTF8String]:"");
  2791. return convertProtoMessageList(tmessages, NO);
  2792. }
  2793. - (NSArray<WFCCMessage *> *)searchMessage:(WFCCConversation *)conversation
  2794. keyword:(NSString *)keyword
  2795. contentTypes:(NSArray<NSNumber *> *)contentTypes
  2796. order:(BOOL)desc
  2797. limit:(int)limit
  2798. offset:(int)offset
  2799. withUser:(NSString *)withUser {
  2800. std::list<int> types;
  2801. for (NSNumber *num in contentTypes) {
  2802. types.push_back(num.intValue);
  2803. }
  2804. std::list<mars::stn::TMessage> tmessages = mars::stn::MessageDB::Instance()->SearchMessagesByTypes((int)conversation.type, conversation.target ? [conversation.target UTF8String] : "", conversation.line, keyword?[keyword UTF8String]:"", types, desc ? true : false, limit, offset, withUser.length?[withUser UTF8String]:"");
  2805. return convertProtoMessageList(tmessages, NO);
  2806. }
  2807. - (NSArray<WFCCMessage *> *)searchMessage:(WFCCConversation *)conversation
  2808. keyword:(NSString *)keyword
  2809. contentTypes:(NSArray<NSNumber *> *)contentTypes
  2810. startTime:(int64_t)startTime
  2811. endTime:(int64_t)endTime
  2812. order:(BOOL)desc
  2813. limit:(int)limit
  2814. offset:(int)offset
  2815. withUser:(NSString *)withUser {
  2816. std::list<int> types;
  2817. for (NSNumber *num in contentTypes) {
  2818. types.push_back(num.intValue);
  2819. }
  2820. std::list<mars::stn::TMessage> tmessages = mars::stn::MessageDB::Instance()->SearchMessagesByTypesAndTimes((int)conversation.type, conversation.target ? [conversation.target UTF8String] : "", conversation.line, keyword?[keyword UTF8String]:"", types, startTime, endTime, desc ? true : false, limit, offset, withUser.length?[withUser UTF8String]:"");
  2821. return convertProtoMessageList(tmessages, NO);
  2822. }
  2823. - (NSArray<WFCCMessage *> *)searchMentionedMessages:(WFCCConversation *)conversation
  2824. keyword:(NSString *)keyword
  2825. order:(BOOL)desc
  2826. limit:(int)limit
  2827. offset:(int)offset {
  2828. std::list<mars::stn::TMessage> tmessages = mars::stn::MessageDB::Instance()->SearchMentionedMessages((int)conversation.type, conversation.target ? [conversation.target UTF8String] : "", conversation.line, keyword?[keyword UTF8String]:"", desc ? true : false, limit, offset);
  2829. return convertProtoMessageList(tmessages, NO);
  2830. }
  2831. - (NSArray<WFCCMessage *> *)searchMessage:(NSArray<NSNumber *> *)conversationTypes
  2832. lines:(NSArray<NSNumber *> *)lines
  2833. contentTypes:(NSArray<NSNumber *> *)contentTypes
  2834. keyword:(NSString *)keyword
  2835. from:(NSUInteger)fromIndex
  2836. count:(NSInteger)count
  2837. withUser:(NSString *)withUser {
  2838. std::list<int> convtypes;
  2839. for (NSNumber *ct in conversationTypes) {
  2840. convtypes.push_back([ct intValue]);
  2841. }
  2842. std::list<int> ls;
  2843. for (NSNumber *type in lines) {
  2844. ls.push_back([type intValue]);
  2845. }
  2846. std::list<int> types;
  2847. for (NSNumber *num in contentTypes) {
  2848. types.push_back(num.intValue);
  2849. }
  2850. bool direction = true;
  2851. if (count < 0) {
  2852. direction = false;
  2853. count = -count;
  2854. }
  2855. std::list<mars::stn::TMessage> tmessages = mars::stn::MessageDB::Instance()->SearchMessagesEx(convtypes, ls, keyword?[keyword UTF8String]:"", types, direction, (int)count, fromIndex, withUser.length?[withUser UTF8String]:"");
  2856. return convertProtoMessageList(tmessages, NO);
  2857. }
  2858. - (NSArray<WFCCMessage *> *)searchMentionedMessage:(NSArray<NSNumber *> *)conversationTypes
  2859. lines:(NSArray<NSNumber *> *)lines
  2860. keyword:(NSString *)keyword
  2861. order:(BOOL)desc
  2862. limit:(int)limit
  2863. offset:(int)offset {
  2864. std::list<int> convtypes;
  2865. for (NSNumber *ct in conversationTypes) {
  2866. convtypes.push_back([ct intValue]);
  2867. }
  2868. std::list<int> ls;
  2869. for (NSNumber *type in lines) {
  2870. ls.push_back([type intValue]);
  2871. }
  2872. std::list<mars::stn::TMessage> tmessages = mars::stn::MessageDB::Instance()->SearchMentionedMessagesEx(convtypes, ls, keyword?[keyword UTF8String]:"", desc, limit, offset);
  2873. return convertProtoMessageList(tmessages, NO);
  2874. }
  2875. - (void)createGroup:(NSString *)groupId
  2876. name:(NSString *)groupName
  2877. portrait:(NSString *)groupPortrait
  2878. type:(WFCCGroupType)type
  2879. groupExtra:(NSString *)groupExtra
  2880. members:(NSArray *)groupMembers
  2881. memberExtra:(NSString *)memberExtra
  2882. notifyLines:(NSArray<NSNumber *> *)notifyLines
  2883. notifyContent:(WFCCMessageContent *)notifyContent
  2884. success:(void(^)(NSString *groupId))successBlock
  2885. error:(void(^)(int error_code))errorBlock {
  2886. std::list<std::string> memberList;
  2887. for (NSString *member in groupMembers) {
  2888. memberList.push_back([member UTF8String]);
  2889. }
  2890. mars::stn::TMessageContent tcontent;
  2891. fillTMessageContent(tcontent, notifyContent);
  2892. std::list<int> lines;
  2893. for (NSNumber *number in notifyLines) {
  2894. lines.push_back([number intValue]);
  2895. }
  2896. mars::stn::createGroup(groupId == nil ? "" : [groupId UTF8String], groupName == nil ? "" : [groupName UTF8String], groupPortrait == nil ? "" : [groupPortrait UTF8String], (int)type, groupExtra == nil ? "" : [groupExtra UTF8String], memberList, memberExtra == nil ? "" : [memberExtra UTF8String], lines, tcontent, new IMCreateGroupCallback(successBlock, errorBlock));
  2897. }
  2898. - (void)addMembers:(NSArray *)members
  2899. toGroup:(NSString *)groupId
  2900. memberExtra:(NSString *)memberExtra
  2901. notifyLines:(NSArray<NSNumber *> *)notifyLines
  2902. notifyContent:(WFCCMessageContent *)notifyContent
  2903. success:(void(^)())successBlock
  2904. error:(void(^)(int error_code))errorBlock {
  2905. if(groupId.length == 0) {
  2906. if(errorBlock) {
  2907. errorBlock(-1);
  2908. }
  2909. return;
  2910. }
  2911. std::list<std::string> memberList;
  2912. for (NSString *member in members) {
  2913. memberList.push_back([member UTF8String]);
  2914. }
  2915. mars::stn::TMessageContent tcontent;
  2916. fillTMessageContent(tcontent, notifyContent);
  2917. std::list<int> lines;
  2918. for (NSNumber *number in notifyLines) {
  2919. lines.push_back([number intValue]);
  2920. }
  2921. mars::stn::addMembers([groupId UTF8String], memberList, memberExtra == nil ? "" : [memberExtra UTF8String], lines, tcontent, new IMGeneralOperationCallback(successBlock, errorBlock));
  2922. }
  2923. - (void)kickoffMembers:(NSArray *)members
  2924. fromGroup:(NSString *)groupId
  2925. notifyLines:(NSArray<NSNumber *> *)notifyLines
  2926. notifyContent:(WFCCMessageContent *)notifyContent
  2927. success:(void(^)())successBlock
  2928. error:(void(^)(int error_code))errorBlock {
  2929. if(groupId.length == 0) {
  2930. if(errorBlock) {
  2931. errorBlock(-1);
  2932. }
  2933. return;
  2934. }
  2935. std::list<std::string> memberList;
  2936. for (NSString *member in members) {
  2937. memberList.push_back([member UTF8String]);
  2938. }
  2939. mars::stn::TMessageContent tcontent;
  2940. fillTMessageContent(tcontent, notifyContent);
  2941. std::list<int> lines;
  2942. for (NSNumber *number in notifyLines) {
  2943. lines.push_back([number intValue]);
  2944. }
  2945. mars::stn::kickoffMembers([groupId UTF8String], memberList, lines, tcontent, new IMGeneralOperationCallback(successBlock, errorBlock));
  2946. }
  2947. - (void)quitGroup:(NSString *)groupId
  2948. notifyLines:(NSArray<NSNumber *> *)notifyLines
  2949. notifyContent:(WFCCMessageContent *)notifyContent
  2950. success:(void(^)())successBlock
  2951. error:(void(^)(int error_code))errorBlock {
  2952. [self quitGroup:groupId keepMessage:false notifyLines:notifyLines notifyContent:notifyContent success:successBlock error:errorBlock];
  2953. }
  2954. - (void)quitGroup:(NSString *)groupId
  2955. keepMessage:(BOOL)keepMessage
  2956. notifyLines:(NSArray<NSNumber *> *)notifyLines
  2957. notifyContent:(WFCCMessageContent *)notifyContent
  2958. success:(void(^)(void))successBlock
  2959. error:(void(^)(int error_code))errorBlock {
  2960. if(groupId.length == 0) {
  2961. if(errorBlock) {
  2962. errorBlock(-1);
  2963. }
  2964. return;
  2965. }
  2966. mars::stn::TMessageContent tcontent;
  2967. fillTMessageContent(tcontent, notifyContent);
  2968. std::list<int> lines;
  2969. for (NSNumber *number in notifyLines) {
  2970. lines.push_back([number intValue]);
  2971. }
  2972. mars::stn::quitGroup([groupId UTF8String], lines, tcontent, new IMGeneralOperationCallback(successBlock, errorBlock), keepMessage);
  2973. }
  2974. - (void)dismissGroup:(NSString *)groupId
  2975. notifyLines:(NSArray<NSNumber *> *)notifyLines
  2976. notifyContent:(WFCCMessageContent *)notifyContent
  2977. success:(void(^)())successBlock
  2978. error:(void(^)(int error_code))errorBlock {
  2979. if(groupId.length == 0) {
  2980. if(errorBlock) {
  2981. errorBlock(-1);
  2982. }
  2983. return;
  2984. }
  2985. mars::stn::TMessageContent tcontent;
  2986. fillTMessageContent(tcontent, notifyContent);
  2987. std::list<int> lines;
  2988. for (NSNumber *number in notifyLines) {
  2989. lines.push_back([number intValue]);
  2990. }
  2991. mars::stn::dismissGroup([groupId UTF8String], lines, tcontent, new IMGeneralOperationCallback(successBlock, errorBlock));
  2992. }
  2993. - (void)modifyGroupInfo:(NSString *)groupId
  2994. type:(ModifyGroupInfoType)type
  2995. newValue:(NSString *)newValue
  2996. notifyLines:(NSArray<NSNumber *> *)notifyLines
  2997. notifyContent:(WFCCMessageContent *)notifyContent
  2998. success:(void(^)(void))successBlock
  2999. error:(void(^)(int error_code))errorBlock {
  3000. if(groupId.length == 0) {
  3001. if(errorBlock) {
  3002. errorBlock(-1);
  3003. }
  3004. return;
  3005. }
  3006. mars::stn::TMessageContent tcontent;
  3007. fillTMessageContent(tcontent, notifyContent);
  3008. std::list<int> lines;
  3009. for (NSNumber *number in notifyLines) {
  3010. lines.push_back([number intValue]);
  3011. }
  3012. mars::stn::modifyGroupInfo([groupId UTF8String], (int)type, [newValue UTF8String], lines, tcontent, new IMGeneralOperationCallback(successBlock, errorBlock));
  3013. }
  3014. - (void)modifyGroupAlias:(NSString *)groupId
  3015. alias:(NSString *)newAlias
  3016. notifyLines:(NSArray<NSNumber *> *)notifyLines
  3017. notifyContent:(WFCCMessageContent *)notifyContent
  3018. success:(void(^)())successBlock
  3019. error:(void(^)(int error_code))errorBlock {
  3020. if(groupId.length == 0) {
  3021. if(errorBlock) {
  3022. errorBlock(-1);
  3023. }
  3024. return;
  3025. }
  3026. mars::stn::TMessageContent tcontent;
  3027. fillTMessageContent(tcontent, notifyContent);
  3028. std::list<int> lines;
  3029. for (NSNumber *number in notifyLines) {
  3030. lines.push_back([number intValue]);
  3031. }
  3032. mars::stn::modifyGroupAlias([groupId UTF8String], newAlias ? [newAlias UTF8String] : "", lines, tcontent, new IMGeneralOperationCallback(successBlock, errorBlock));
  3033. }
  3034. - (void)modifyGroupMemberAlias:(NSString *)groupId
  3035. memberId:(NSString *)memberId
  3036. alias:(NSString *)newAlias
  3037. notifyLines:(NSArray<NSNumber *> *)notifyLines
  3038. notifyContent:(WFCCMessageContent *)notifyContent
  3039. success:(void(^)(void))successBlock
  3040. error:(void(^)(int error_code))errorBlock {
  3041. if(groupId.length == 0) {
  3042. if(errorBlock) {
  3043. errorBlock(-1);
  3044. }
  3045. return;
  3046. }
  3047. mars::stn::TMessageContent tcontent;
  3048. fillTMessageContent(tcontent, notifyContent);
  3049. std::list<int> lines;
  3050. for (NSNumber *number in notifyLines) {
  3051. lines.push_back([number intValue]);
  3052. }
  3053. mars::stn::modifyGroupMemberAlias([groupId UTF8String], [memberId UTF8String], newAlias.length?[newAlias UTF8String]:"", lines, tcontent, new IMGeneralOperationCallback(successBlock, errorBlock));
  3054. }
  3055. - (void)modifyGroupMemberExtra:(NSString *)groupId
  3056. extra:(NSString *)extra
  3057. notifyLines:(NSArray<NSNumber *> *)notifyLines
  3058. notifyContent:(WFCCMessageContent *)notifyContent
  3059. success:(void(^)(void))successBlock
  3060. error:(void(^)(int error_code))errorBlock {
  3061. [self modifyGroupMemberExtra:groupId memberId:[WFCCNetworkService sharedInstance].userId extra:extra notifyLines:notifyLines notifyContent:notifyContent success:successBlock error:errorBlock];
  3062. }
  3063. - (void)modifyGroupMemberExtra:(NSString *)groupId
  3064. memberId:(NSString *)memberId
  3065. extra:(NSString *)extra
  3066. notifyLines:(NSArray<NSNumber *> *)notifyLines
  3067. notifyContent:(WFCCMessageContent *)notifyContent
  3068. success:(void(^)(void))successBlock
  3069. error:(void(^)(int error_code))errorBlock {
  3070. if(groupId.length == 0) {
  3071. if(errorBlock) {
  3072. errorBlock(-1);
  3073. }
  3074. return;
  3075. }
  3076. mars::stn::TMessageContent tcontent;
  3077. fillTMessageContent(tcontent, notifyContent);
  3078. std::list<int> lines;
  3079. for (NSNumber *number in notifyLines) {
  3080. lines.push_back([number intValue]);
  3081. }
  3082. mars::stn::modifyGroupMemberExtra([groupId UTF8String], [memberId UTF8String], [extra UTF8String], lines, tcontent, new IMGeneralOperationCallback(successBlock, errorBlock));
  3083. }
  3084. WFCCGroupMember* convertProtoGroupMember(const mars::stn::TGroupMember &tm) {
  3085. WFCCGroupMember *member = [[WFCCGroupMember alloc] init];
  3086. member.groupId = [NSString stringWithUTF8String:tm.groupId.c_str()];
  3087. member.memberId = [NSString stringWithUTF8String:tm.memberId.c_str()];
  3088. member.alias = [NSString stringWithUTF8String:tm.alias.c_str()];
  3089. member.extra = [NSString stringWithUTF8String:tm.extra.c_str()];
  3090. member.type = (WFCCGroupMemberType)tm.type;
  3091. member.createTime = tm.createDt;
  3092. return member;;
  3093. }
  3094. - (NSArray<WFCCGroupMember *> *)getGroupMembers:(NSString *)groupId
  3095. forceUpdate:(BOOL)refresh {
  3096. if(groupId.length == 0) {
  3097. return nil;
  3098. }
  3099. std::list<mars::stn::TGroupMember> tmembers = mars::stn::MessageDB::Instance()->GetGroupMembers([groupId UTF8String], refresh);
  3100. NSMutableArray *output = [[NSMutableArray alloc] init];
  3101. for(std::list<mars::stn::TGroupMember>::iterator it = tmembers.begin(); it != tmembers.end(); it++) {
  3102. WFCCGroupMember *member = convertProtoGroupMember(*it);
  3103. [output addObject:member];
  3104. }
  3105. return output;
  3106. }
  3107. - (NSArray<WFCCGroupMember *> *)getGroupMembers:(NSString *)groupId
  3108. type:(WFCCGroupMemberType)memberType {
  3109. if(groupId.length == 0) {
  3110. return nil;
  3111. }
  3112. std::list<mars::stn::TGroupMember> tmembers = mars::stn::MessageDB::Instance()->GetGroupMembersByType([groupId UTF8String], (int)memberType);
  3113. NSMutableArray *output = [[NSMutableArray alloc] init];
  3114. for(std::list<mars::stn::TGroupMember>::iterator it = tmembers.begin(); it != tmembers.end(); it++) {
  3115. WFCCGroupMember *member = convertProtoGroupMember(*it);
  3116. [output addObject:member];
  3117. }
  3118. return output;
  3119. }
  3120. - (NSArray<WFCCGroupMember *> *)getGroupMembers:(NSString *)groupId
  3121. count:(int)count {
  3122. if(groupId.length == 0) {
  3123. return nil;
  3124. }
  3125. std::list<mars::stn::TGroupMember> tmembers = mars::stn::MessageDB::Instance()->GetGroupMembersByCount([groupId UTF8String], count);
  3126. NSMutableArray *output = [[NSMutableArray alloc] init];
  3127. for(std::list<mars::stn::TGroupMember>::iterator it = tmembers.begin(); it != tmembers.end(); it++) {
  3128. WFCCGroupMember *member = convertProtoGroupMember(*it);
  3129. [output addObject:member];
  3130. }
  3131. return output;
  3132. }
  3133. class IMGetGroupMembersCallback : public mars::stn::GetGroupMembersCallback {
  3134. private:
  3135. void(^m_successBlock)(NSString *groupId, NSArray<WFCCGroupMember *> *memberList);
  3136. void(^m_errorBlock)(int error_code);
  3137. public:
  3138. IMGetGroupMembersCallback(void(^successBlock)(NSString *groupId, NSArray<WFCCGroupMember *> *memberList), void(^errorBlock)(int error_code)) : mars::stn::GetGroupMembersCallback(), m_successBlock(successBlock), m_errorBlock(errorBlock) {};
  3139. void onSuccess(const std::string &groupId, const std::list<mars::stn::TGroupMember> &groupMemberList) {
  3140. NSMutableArray *output = [[NSMutableArray alloc] init];
  3141. for(std::list<mars::stn::TGroupMember>::const_iterator it = groupMemberList.begin(); it != groupMemberList.end(); it++) {
  3142. WFCCGroupMember *member = convertProtoGroupMember(*it);
  3143. [output addObject:member];
  3144. }
  3145. NSString *gid = [NSString stringWithUTF8String:groupId.c_str()];
  3146. dispatch_async(dispatch_get_main_queue(), ^{
  3147. if(m_successBlock) {
  3148. m_successBlock(gid, output);
  3149. }
  3150. delete this;
  3151. });
  3152. }
  3153. void onFalure(int errorCode) {
  3154. dispatch_async(dispatch_get_main_queue(), ^{
  3155. if(m_errorBlock) {
  3156. m_errorBlock(errorCode);
  3157. }
  3158. delete this;
  3159. });
  3160. }
  3161. virtual ~IMGetGroupMembersCallback() {
  3162. m_successBlock = nil;
  3163. m_errorBlock = nil;
  3164. }
  3165. };
  3166. - (void)getGroupMembers:(NSString *)groupId
  3167. refresh:(BOOL)refresh
  3168. success:(void(^)(NSString *groupId, NSArray<WFCCGroupMember *> *))successBlock
  3169. error:(void(^)(int errorCode))errorBlock {
  3170. if(groupId.length == 0) {
  3171. if(errorBlock) {
  3172. errorBlock(-1);
  3173. }
  3174. return;
  3175. }
  3176. mars::stn::MessageDB::Instance()->GetGroupMembers([groupId UTF8String], refresh, new IMGetGroupMembersCallback(successBlock, errorBlock));
  3177. }
  3178. - (WFCCGroupMember *)getGroupMember:(NSString *)groupId
  3179. memberId:(NSString *)memberId {
  3180. if (!groupId || !memberId) {
  3181. return nil;
  3182. }
  3183. mars::stn::TGroupMember tmember = mars::stn::MessageDB::Instance()->GetGroupMember([groupId UTF8String], [memberId UTF8String]);
  3184. if (tmember.memberId == [memberId UTF8String]) {
  3185. return convertProtoGroupMember(tmember);
  3186. }
  3187. return nil;
  3188. }
  3189. - (void)transferGroup:(NSString *)groupId
  3190. to:(NSString *)newOwner
  3191. notifyLines:(NSArray<NSNumber *> *)notifyLines
  3192. notifyContent:(WFCCMessageContent *)notifyContent
  3193. success:(void(^)())successBlock
  3194. error:(void(^)(int error_code))errorBlock {
  3195. if(groupId.length == 0) {
  3196. if(errorBlock) {
  3197. errorBlock(-1);
  3198. }
  3199. return;
  3200. }
  3201. mars::stn::TMessageContent tcontent;
  3202. fillTMessageContent(tcontent, notifyContent);
  3203. std::list<int> lines;
  3204. for (NSNumber *number in notifyLines) {
  3205. lines.push_back([number intValue]);
  3206. }
  3207. mars::stn::transferGroup([groupId UTF8String], [newOwner UTF8String], lines, tcontent, new IMGeneralOperationCallback(successBlock, errorBlock));
  3208. }
  3209. - (void)setGroupManager:(NSString *)groupId
  3210. isSet:(BOOL)isSet
  3211. memberIds:(NSArray<NSString *> *)memberIds
  3212. notifyLines:(NSArray<NSNumber *> *)notifyLines
  3213. notifyContent:(WFCCMessageContent *)notifyContent
  3214. success:(void(^)(void))successBlock
  3215. error:(void(^)(int error_code))errorBlock {
  3216. if(groupId.length == 0) {
  3217. if(errorBlock) {
  3218. errorBlock(-1);
  3219. }
  3220. return;
  3221. }
  3222. mars::stn::TMessageContent tcontent;
  3223. fillTMessageContent(tcontent, notifyContent);
  3224. std::list<int> lines;
  3225. for (NSNumber *number in notifyLines) {
  3226. lines.push_back([number intValue]);
  3227. }
  3228. std::list<std::string> memberList;
  3229. for (NSString *member in memberIds) {
  3230. memberList.push_back([member UTF8String]);
  3231. }
  3232. mars::stn::SetGroupManager([groupId UTF8String], memberList, isSet, lines, tcontent, new IMGeneralOperationCallback(successBlock, errorBlock));
  3233. }
  3234. - (void)muteGroupMember:(NSString *)groupId
  3235. isSet:(BOOL)isSet
  3236. memberIds:(NSArray<NSString *> *)memberIds
  3237. notifyLines:(NSArray<NSNumber *> *)notifyLines
  3238. notifyContent:(WFCCMessageContent *)notifyContent
  3239. success:(void(^)(void))successBlock
  3240. error:(void(^)(int error_code))errorBlock {
  3241. if(groupId.length == 0) {
  3242. if(errorBlock) {
  3243. errorBlock(-1);
  3244. }
  3245. return;
  3246. }
  3247. mars::stn::TMessageContent tcontent;
  3248. fillTMessageContent(tcontent, notifyContent);
  3249. std::list<int> lines;
  3250. for (NSNumber *number in notifyLines) {
  3251. lines.push_back([number intValue]);
  3252. }
  3253. std::list<std::string> memberList;
  3254. for (NSString *member in memberIds) {
  3255. memberList.push_back([member UTF8String]);
  3256. }
  3257. mars::stn::MuteOrAllowGroupMember([groupId UTF8String], memberList, isSet, false, lines, tcontent, new IMGeneralOperationCallback(successBlock, errorBlock));
  3258. }
  3259. - (void)allowGroupMember:(NSString *)groupId
  3260. isSet:(BOOL)isSet
  3261. memberIds:(NSArray<NSString *> *)memberIds
  3262. notifyLines:(NSArray<NSNumber *> *)notifyLines
  3263. notifyContent:(WFCCMessageContent *)notifyContent
  3264. success:(void(^)(void))successBlock
  3265. error:(void(^)(int error_code))errorBlock {
  3266. if(!groupId.length) {
  3267. if(errorBlock) {
  3268. errorBlock(-1);
  3269. }
  3270. return;
  3271. }
  3272. mars::stn::TMessageContent tcontent;
  3273. fillTMessageContent(tcontent, notifyContent);
  3274. std::list<int> lines;
  3275. for (NSNumber *number in notifyLines) {
  3276. lines.push_back([number intValue]);
  3277. }
  3278. std::list<std::string> memberList;
  3279. for (NSString *member in memberIds) {
  3280. memberList.push_back([member UTF8String]);
  3281. }
  3282. mars::stn::MuteOrAllowGroupMember([groupId UTF8String], memberList, isSet, true, lines, tcontent, new IMGeneralOperationCallback(successBlock, errorBlock));
  3283. }
  3284. - (NSString *)getGroupRemark:(NSString *)groupId {
  3285. return [NSString stringWithUTF8String:mars::stn::getGroupRemark([groupId UTF8String]).c_str()];
  3286. }
  3287. - (void)setGroup:(NSString *)groupId
  3288. remark:(NSString *)remark
  3289. success:(void(^)(void))successBlock
  3290. error:(void(^)(int error_code))errorBlock {
  3291. mars::stn::setGroupRemark([groupId UTF8String], remark.length?[remark UTF8String]:"", new IMSetGroupRemarkCallback(groupId, successBlock, errorBlock));
  3292. }
  3293. - (NSArray<NSString *> *)getFavGroups {
  3294. NSDictionary *favGroupDict = [[WFCCIMService sharedWFCIMService] getUserSettings:UserSettingScope_Favourite_Group];
  3295. NSMutableArray *ids = [[NSMutableArray alloc] init];
  3296. [favGroupDict enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
  3297. if ([obj isEqualToString:@"1"]) {
  3298. [ids addObject:key];
  3299. }
  3300. }];
  3301. return ids;
  3302. }
  3303. - (BOOL)isFavGroup:(NSString *)groupId {
  3304. NSString *strValue = [[WFCCIMService sharedWFCIMService] getUserSetting:UserSettingScope_Favourite_Group key:groupId];
  3305. if ([strValue isEqualToString:@"1"]) {
  3306. return YES;
  3307. }
  3308. return NO;
  3309. }
  3310. - (void)setFavGroup:(NSString *)groupId fav:(BOOL)fav success:(void(^)(void))successBlock error:(void(^)(int errorCode))errorBlock {
  3311. [[WFCCIMService sharedWFCIMService] setUserSetting:UserSettingScope_Favourite_Group key:groupId value:fav? @"1" : @"0" success:successBlock error:errorBlock];
  3312. }
  3313. - (WFCCGroupInfo *)getGroupInfo:(NSString *)groupId refresh:(BOOL)refresh {
  3314. if (!groupId) {
  3315. return nil;
  3316. }
  3317. if(![groupId isKindOfClass:NSString.class]) {
  3318. return nil;
  3319. }
  3320. mars::stn::TGroupInfo tgi = mars::stn::MessageDB::Instance()->GetGroupInfo([groupId UTF8String], refresh);
  3321. return convertProtoGroupInfo(tgi);
  3322. }
  3323. - (NSArray<WFCCGroupInfo *> *)getGroupInfos:(NSArray<NSString *> *)groupIds
  3324. refresh:(BOOL)refresh {
  3325. if (![groupIds count]) {
  3326. return nil;
  3327. }
  3328. std::list<std::string> gids;
  3329. for (NSString *groupId : groupIds) {
  3330. gids.push_back([groupId UTF8String]);
  3331. }
  3332. std::list<mars::stn::TGroupInfo> tgroupInfos = mars::stn::MessageDB::Instance()->GetGroupInfos(gids, refresh);
  3333. NSMutableArray<WFCCGroupInfo *> *groupInfos = [[NSMutableArray alloc] init];
  3334. for (std::list<mars::stn::TGroupInfo>::iterator it = tgroupInfos.begin(); it != tgroupInfos.end(); ++it) {
  3335. WFCCGroupInfo *groupInfo = convertProtoGroupInfo(*it);
  3336. [groupInfos addObject:groupInfo];
  3337. }
  3338. return groupInfos;
  3339. }
  3340. class IMGetOneGroupInfoCallback : public mars::stn::GetOneGroupInfoCallback {
  3341. private:
  3342. void(^m_successBlock)(WFCCGroupInfo *);
  3343. void(^m_errorBlock)(int error_code);
  3344. public:
  3345. IMGetOneGroupInfoCallback(void(^successBlock)(WFCCGroupInfo *), void(^errorBlock)(int error_code)) : mars::stn::GetOneGroupInfoCallback(), m_successBlock(successBlock), m_errorBlock(errorBlock) {};
  3346. void onSuccess(const mars::stn::TGroupInfo &tgi) {
  3347. WFCCGroupInfo *gi = convertProtoGroupInfo(tgi);
  3348. dispatch_async(dispatch_get_main_queue(), ^{
  3349. if (m_successBlock) {
  3350. m_successBlock(gi);
  3351. }
  3352. delete this;
  3353. });
  3354. }
  3355. void onFalure(int errorCode) {
  3356. dispatch_async(dispatch_get_main_queue(), ^{
  3357. if (m_errorBlock) {
  3358. m_errorBlock(errorCode);
  3359. }
  3360. delete this;
  3361. });
  3362. }
  3363. virtual ~IMGetOneGroupInfoCallback() {
  3364. m_successBlock = nil;
  3365. m_errorBlock = nil;
  3366. }
  3367. };
  3368. - (void)getGroupInfo:(NSString *)groupId
  3369. refresh:(BOOL)refresh
  3370. success:(void(^)(WFCCGroupInfo *groupInfo))successBlock
  3371. error:(void(^)(int errorCode))errorBlock {
  3372. if(!groupId.length) {
  3373. if(errorBlock) {
  3374. errorBlock(-1);
  3375. }
  3376. return;
  3377. }
  3378. mars::stn::MessageDB::Instance()->GetGroupInfo([groupId UTF8String], refresh, new IMGetOneGroupInfoCallback(successBlock, errorBlock));
  3379. }
  3380. - (NSString *)getUserSetting:(UserSettingScope)scope key:(NSString *)key {
  3381. if (!key) {
  3382. key = @"";
  3383. }
  3384. std::string str = mars::stn::MessageDB::Instance()->GetUserSetting((int)scope, [key UTF8String]);
  3385. return [NSString stringWithUTF8String:str.c_str()];
  3386. }
  3387. - (NSDictionary<NSString *, NSString *> *)getUserSettings:(UserSettingScope)scope {
  3388. std::map<std::string, std::string> settings = mars::stn::MessageDB::Instance()->GetUserSettings((int)scope);
  3389. NSMutableDictionary *result = [[NSMutableDictionary alloc] init];
  3390. for (std::map<std::string, std::string>::iterator it = settings.begin() ; it != settings.end(); it++) {
  3391. NSString *key = [NSString stringWithUTF8String:it->first.c_str()];
  3392. NSString *value = [NSString stringWithUTF8String:it->second.c_str()];
  3393. [result setObject:value forKey:key];
  3394. }
  3395. return result;
  3396. }
  3397. - (void)setUserSetting:(UserSettingScope)scope key:(NSString *)key value:(NSString *)value
  3398. success:(void(^)())successBlock
  3399. error:(void(^)(int error_code))errorBlock {
  3400. if(!key) {
  3401. key = @"";
  3402. }
  3403. if(!value) {
  3404. value = @"";
  3405. }
  3406. mars::stn::modifyUserSetting((int)scope, [key UTF8String], [value UTF8String], new IMGeneralOperationCallback(^{
  3407. if(successBlock) {
  3408. successBlock();
  3409. }
  3410. [[NSNotificationCenter defaultCenter] postNotificationName:kSettingUpdated object:nil];
  3411. }, errorBlock));
  3412. }
  3413. - (void)setConversation:(WFCCConversation *)conversation silent:(BOOL)silent
  3414. success:(void(^)())successBlock
  3415. error:(void(^)(int error_code))errorBlock {
  3416. [self setUserSetting:(UserSettingScope)mars::stn::kUserSettingConversationSilent key:[NSString stringWithFormat:@"%zd-%d-%@", conversation.type, conversation.line, conversation.target] value:silent ? @"1" : @"0" success:successBlock error:errorBlock];
  3417. }
  3418. - (BOOL)isConversationSilent:(WFCCConversation *)conversation {
  3419. return [@"1" isEqualToString:[self getUserSetting:UserSettingScope_Conversation_Silent key:[NSString stringWithFormat:@"%zd-%d-%@", conversation.type, conversation.line, conversation.target]]];
  3420. }
  3421. - (WFCCMessageContent *)messageContentFromPayload:(WFCCMessagePayload *)payload {
  3422. if(self.rawMessage && (payload.contentType < 400 || payload.contentType >= 500)) {
  3423. WFCCRawMessageContent *rawContent = [[WFCCRawMessageContent alloc] init];
  3424. rawContent.payload = payload;
  3425. return rawContent;
  3426. }
  3427. int contenttype = payload.contentType;
  3428. Class contentClass = self.MessageContentMaps[@(contenttype)];
  3429. if (contentClass != nil) {
  3430. id messageInstance = [[contentClass alloc] init];
  3431. if ([contentClass conformsToProtocol:@protocol(WFCCMessageContent)]) {
  3432. if ([messageInstance respondsToSelector:@selector(decode:)]) {
  3433. [messageInstance performSelector:@selector(decode:)
  3434. withObject:payload];
  3435. }
  3436. }
  3437. return messageInstance;
  3438. }
  3439. WFCCUnknownMessageContent *unknownMsg = [[WFCCUnknownMessageContent alloc] init];
  3440. [unknownMsg decode:payload];
  3441. return unknownMsg;
  3442. }
  3443. - (WFCCMessage *)insert:(WFCCConversation *)conversation
  3444. sender:(NSString *)sender
  3445. content:(WFCCMessageContent *)content
  3446. status:(WFCCMessageStatus)status
  3447. notify:(BOOL)notify
  3448. toUsers:(NSArray<NSString *> *)toUsers
  3449. serverTime:(long long)serverTime {
  3450. WFCCMessage *message = [[WFCCMessage alloc] init];
  3451. message.conversation = conversation;
  3452. message.content = content;
  3453. mars::stn::TMessage tmsg;
  3454. fillTMessage(tmsg, conversation, content);
  3455. if(status >= Message_Status_Mentioned) {
  3456. tmsg.direction = 1;
  3457. message.direction = MessageDirection_Receive;
  3458. if(conversation.type == Single_Type) {
  3459. tmsg.from = [conversation.target UTF8String];
  3460. } else {
  3461. tmsg.from = [sender UTF8String];
  3462. }
  3463. }
  3464. message.status = status;
  3465. tmsg.status = (mars::stn::MessageStatus)status;
  3466. if(serverTime > 0) {
  3467. message.serverTime = serverTime;
  3468. tmsg.timestamp = serverTime;
  3469. }
  3470. if(toUsers.count) {
  3471. for (NSString *toUser in toUsers) {
  3472. tmsg.to.push_back([toUser UTF8String]);
  3473. }
  3474. }
  3475. long msgId = mars::stn::MessageDB::Instance()->InsertMessage(tmsg);
  3476. message.messageId = msgId;
  3477. message.fromUser = sender;
  3478. if (notify) {
  3479. [[NSNotificationCenter defaultCenter] postNotificationName:kReceiveMessages object:@[message]];
  3480. [[WFCCNetworkService sharedInstance].receiveMessageDelegate onReceiveMessage:@[message] hasMore:NO];
  3481. }
  3482. return message;
  3483. }
  3484. - (void)updateMessage:(long)messageId
  3485. content:(WFCCMessageContent *)content {
  3486. mars::stn::TMessageContent tmc;
  3487. fillTMessageContent(tmc, content);
  3488. bool updated = mars::stn::MessageDB::Instance()->UpdateMessageContent(messageId, tmc);
  3489. if(updated) {
  3490. [[NSNotificationCenter defaultCenter] postNotificationName:kMessageUpdated object:@(messageId)];
  3491. }
  3492. }
  3493. - (void)updateMessage:(long)messageId
  3494. content:(WFCCMessageContent *)content
  3495. timestamp:(long long)timestamp {
  3496. mars::stn::TMessageContent tmc;
  3497. fillTMessageContent(tmc, content);
  3498. bool updated = mars::stn::MessageDB::Instance()->UpdateMessageContentAndTime(messageId, tmc, timestamp);
  3499. if(updated) {
  3500. [[NSNotificationCenter defaultCenter] postNotificationName:kMessageUpdated object:@(messageId)];
  3501. }
  3502. }
  3503. - (void)registerMessageContent:(Class)contentClass {
  3504. int contenttype;
  3505. if (class_getClassMethod(contentClass, @selector(getContentType))) {
  3506. contenttype = [contentClass getContentType];
  3507. if(self.MessageContentMaps[@(contenttype)] && ![contentClass isEqual:self.MessageContentMaps[@(contenttype)]]) {
  3508. NSLog(@"****************************************");
  3509. NSLog(@"Error, duplicate message content type %d", contenttype);
  3510. NSLog(@"****************************************");
  3511. #if DEBUG
  3512. @throw [[NSException alloc] initWithName:@"重复定义消息" reason:[NSString stringWithFormat:@"消息类型(%d)重复定义在消息(%@)和(%@)中", contenttype, NSStringFromClass(contentClass), NSStringFromClass(self.MessageContentMaps[@(contenttype)])] userInfo:nil];
  3513. #endif
  3514. }
  3515. self.MessageContentMaps[@(contenttype)] = contentClass;
  3516. int contentflag = [contentClass getContentFlags];
  3517. mars::stn::MessageDB::Instance()->RegisterMessageFlag(contenttype, contentflag);
  3518. } else {
  3519. return;
  3520. }
  3521. }
  3522. - (void)registerMessageFlag:(int)contentType flag:(int)contentFlag {
  3523. mars::stn::MessageDB::Instance()->RegisterMessageFlag(contentType, contentFlag);
  3524. }
  3525. - (void)joinChatroom:(NSString *)chatroomId
  3526. success:(void(^)(void))successBlock
  3527. error:(void(^)(int error_code))errorBlock {
  3528. if(!chatroomId) {
  3529. if(errorBlock) {
  3530. errorBlock(-1);
  3531. }
  3532. return;
  3533. }
  3534. mars::stn::joinChatroom([chatroomId UTF8String], new IMGeneralOperationCallback(successBlock, errorBlock));
  3535. }
  3536. - (void)quitChatroom:(NSString *)chatroomId
  3537. success:(void(^)(void))successBlock
  3538. error:(void(^)(int error_code))errorBlock {
  3539. if(!chatroomId) {
  3540. if(errorBlock) {
  3541. errorBlock(-1);
  3542. }
  3543. return;
  3544. }
  3545. mars::stn::quitChatroom([chatroomId UTF8String], new IMGeneralOperationCallback(successBlock, errorBlock));
  3546. }
  3547. - (void)getChatroomInfo:(NSString *)chatroomId
  3548. upateDt:(long long)updateDt
  3549. success:(void(^)(WFCCChatroomInfo *chatroomInfo))successBlock
  3550. error:(void(^)(int error_code))errorBlock {
  3551. if(!chatroomId) {
  3552. if(errorBlock) {
  3553. errorBlock(-1);
  3554. }
  3555. return;
  3556. }
  3557. mars::stn::getChatroomInfo([chatroomId UTF8String], updateDt, new IMGetChatroomInfoCallback(chatroomId, successBlock, errorBlock));
  3558. }
  3559. - (void)getChatroomMemberInfo:(NSString *)chatroomId
  3560. maxCount:(int)maxCount
  3561. success:(void(^)(WFCCChatroomMemberInfo *memberInfo))successBlock
  3562. error:(void(^)(int error_code))errorBlock {
  3563. if (maxCount <= 0) {
  3564. maxCount = 30;
  3565. }
  3566. if(!chatroomId) {
  3567. if(errorBlock) {
  3568. errorBlock(-1);
  3569. }
  3570. return;
  3571. }
  3572. mars::stn::getChatroomMemberInfo([chatroomId UTF8String], maxCount, new IMGetChatroomMemberInfoCallback(successBlock, errorBlock));
  3573. }
  3574. - (NSString *)getJoinedChatroomId {
  3575. std::string chatroomId = mars::stn::getJoinedChatroom();
  3576. if (chatroomId.empty()) {
  3577. return nil;
  3578. }
  3579. return [NSString stringWithUTF8String:chatroomId.c_str()];
  3580. }
  3581. - (void)createChannel:(NSString *)channelName
  3582. portrait:(NSString *)channelPortrait
  3583. desc:(NSString *)desc
  3584. extra:(NSString *)extra
  3585. success:(void(^)(WFCCChannelInfo *channelInfo))successBlock
  3586. error:(void(^)(int error_code))errorBlock {
  3587. if (!extra) {
  3588. extra = @"";
  3589. }
  3590. //status只能是0,请参考 https://docs.wildfirechat.cn/base_knowledge/channel.html#频道属性
  3591. mars::stn::createChannel("", [channelName UTF8String], channelPortrait ? [channelPortrait UTF8String] : "", 0, desc?[desc UTF8String]:"", [extra UTF8String], "", "", new IMCreateChannelCallback(successBlock, errorBlock));
  3592. }
  3593. - (void)destoryChannel:(NSString *)channelId
  3594. success:(void(^)(void))successBlock
  3595. error:(void(^)(int error_code))errorBlock {
  3596. if(!channelId) {
  3597. if(errorBlock) {
  3598. errorBlock(-1);
  3599. }
  3600. return;
  3601. }
  3602. mars::stn::destoryChannel([channelId UTF8String], new IMGeneralOperationCallback(successBlock, errorBlock));
  3603. }
  3604. - (WFCCChannelInfo *)getChannelInfo:(NSString *)channelId
  3605. refresh:(BOOL)refresh {
  3606. if(!channelId) {
  3607. return nil;
  3608. }
  3609. mars::stn::TChannelInfo tgi = mars::stn::MessageDB::Instance()->GetChannelInfo([channelId UTF8String], refresh);
  3610. return convertProtoChannelInfo(tgi);
  3611. }
  3612. - (void)modifyChannelInfo:(NSString *)channelId
  3613. type:(ModifyChannelInfoType)type
  3614. newValue:(NSString *)newValue
  3615. success:(void(^)(void))successBlock
  3616. error:(void(^)(int error_code))errorBlock {
  3617. if(!channelId || !newValue) {
  3618. if(errorBlock) {
  3619. errorBlock(-1);
  3620. }
  3621. return;
  3622. }
  3623. mars::stn::modifyChannelInfo([channelId UTF8String], (int)type, [newValue UTF8String], new IMGeneralOperationCallback(successBlock, errorBlock));
  3624. }
  3625. - (void)searchChannel:(NSString *)keyword success:(void(^)(NSArray<WFCCChannelInfo *> *machedChannels))successBlock error:(void(^)(int errorCode))errorBlock {
  3626. if(!keyword.length) {
  3627. successBlock(@[]);
  3628. return;
  3629. }
  3630. mars::stn::searchChannel(keyword?[keyword UTF8String]:"", YES, new IMSearchChannelCallback(successBlock, errorBlock));
  3631. }
  3632. - (BOOL)isListenedChannel:(NSString *)channelId {
  3633. if([@"1" isEqualToString:[self getUserSetting:UserSettingScope_Listened_Channel key:channelId]]) {
  3634. return YES;
  3635. }
  3636. return NO;
  3637. }
  3638. - (void)listenChannel:(NSString *)channelId listen:(BOOL)listen success:(void(^)(void))successBlock error:(void(^)(int errorCode))errorBlock {
  3639. if(!channelId) {
  3640. if(errorBlock) {
  3641. errorBlock(-1);
  3642. }
  3643. return;
  3644. }
  3645. mars::stn::listenChannel([channelId UTF8String], listen, new IMGeneralOperationCallback(successBlock, errorBlock));
  3646. }
  3647. - (NSArray<NSString *> *)getMyChannels {
  3648. NSDictionary *myChannelDict = [[WFCCIMService sharedWFCIMService] getUserSettings:UserSettingScope_My_Channel];
  3649. NSMutableArray *ids = [[NSMutableArray alloc] init];
  3650. [myChannelDict enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
  3651. if ([obj isEqualToString:@"1"]) {
  3652. [ids addObject:key];
  3653. }
  3654. }];
  3655. return ids;
  3656. }
  3657. - (NSArray<NSString *> *)getListenedChannels {
  3658. NSDictionary *myChannelDict = [[WFCCIMService sharedWFCIMService] getUserSettings:UserSettingScope_Listened_Channel];
  3659. NSMutableArray *ids = [[NSMutableArray alloc] init];
  3660. [myChannelDict enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
  3661. if ([obj isEqualToString:@"1"]) {
  3662. [ids addObject:key];
  3663. }
  3664. }];
  3665. return ids;
  3666. }
  3667. - (void)getRemoteListenedChannels:(void(^)(NSArray<NSString *> *))successBlock error:(void(^)(int errorCode))errorBlock {
  3668. mars::stn::getListenedChannels(new IMGeneralStringListCallback(successBlock, errorBlock));
  3669. }
  3670. - (WFCCDomainInfo *)getDomainInfo:(NSString *)domainId refresh:(BOOL)refresh {
  3671. mars::stn::TDomainInfo tdomain = mars::stn::MessageDB::Instance()->GetDomainInfo([domainId UTF8String], refresh?true:false);
  3672. if(tdomain.domainId.size()) {
  3673. WFCCDomainInfo *domainInfo = [[WFCCDomainInfo alloc] init];
  3674. domainInfo.domainId = [NSString stringWithUTF8String:tdomain.domainId.c_str()];
  3675. domainInfo.name = [NSString stringWithUTF8String:tdomain.name.c_str()];
  3676. domainInfo.desc = [NSString stringWithUTF8String:tdomain.desc.c_str()];
  3677. domainInfo.email = [NSString stringWithUTF8String:tdomain.email.c_str()];
  3678. domainInfo.tel = [NSString stringWithUTF8String:tdomain.tel.c_str()];
  3679. domainInfo.address = [NSString stringWithUTF8String:tdomain.address.c_str()];
  3680. domainInfo.extra = [NSString stringWithUTF8String:tdomain.extra.c_str()];
  3681. domainInfo.updateDt = tdomain.updateDt;
  3682. return domainInfo;
  3683. }
  3684. return nil;
  3685. }
  3686. - (void)getRemoteDomains:(void (^)(NSArray<WFCCDomainInfo *> *domains))successBlock error:(void (^)(int errorCode))errorBlock {
  3687. mars::stn::loadRemoteDomains(new IMLoadRemoteDomainsCallback(successBlock, errorBlock));
  3688. }
  3689. - (void)createSecretChat:(NSString *)userId
  3690. success:(void(^)(NSString *targetId, int line))successBlock
  3691. error:(void(^)(int error_code))errorBlock {
  3692. mars::stn::createSecretChat([userId UTF8String], new IMCreateSecretChatCallback(successBlock, errorBlock));
  3693. }
  3694. - (void)destroySecretChat:(NSString *)targetId
  3695. success:(void(^)(void))successBlock
  3696. error:(void(^)(int error_code))errorBlock {
  3697. mars::stn::destroySecretChat([targetId UTF8String], new IMGeneralOperationCallback(successBlock, errorBlock));
  3698. }
  3699. - (WFCCSecretChatInfo *)getSecretChatInfo:(NSString *)targetId {
  3700. mars::stn::TSecretChatInfo t = mars::stn::MessageDB::Instance()->GetSecretChatInfo([targetId UTF8String]);
  3701. if(t.targetId.empty()) {
  3702. return nil;
  3703. }
  3704. WFCCSecretChatInfo *info = [[WFCCSecretChatInfo alloc] init];
  3705. info.targetId = targetId;
  3706. info.userId = [NSString stringWithUTF8String:t.userId.c_str()];
  3707. info.state = (WFCCSecretChatState)t.state;
  3708. info.burnTime = t.burnTime;
  3709. info.createTime = t.createTime;
  3710. return info;
  3711. }
  3712. - (NSData *)encodeSecretChat:(NSString *)targetId mediaData:(NSData *)data {
  3713. std::string sd = mars::stn::encodeSecretChatMediaData([targetId UTF8String], (const unsigned char *)data.bytes, (int)data.length);
  3714. if(sd.empty()) {
  3715. return nil;
  3716. }
  3717. return [[NSData alloc] initWithBytes:sd.data() length:sd.length()];
  3718. }
  3719. - (NSData *)decodeSecretChat:(NSString *)targetId mediaData:(NSData *)encryptData {
  3720. std::string sd = mars::stn::decodeSecretChatMediaData([targetId UTF8String], (const unsigned char *)encryptData.bytes, (int)encryptData.length);
  3721. if(sd.empty()) {
  3722. return nil;
  3723. }
  3724. return [[NSData alloc] initWithBytes:sd.data() length:sd.length()];
  3725. }
  3726. - (void)setSecretChat:(NSString *)targetId burnTime:(int)millisecond {
  3727. mars::stn::MessageDB::Instance()->SetSecretChatBurnTime([targetId UTF8String], millisecond);
  3728. }
  3729. - (NSArray<WFCCPCOnlineInfo *> *)getPCOnlineInfos {
  3730. NSString *pcOnline = [self getUserSetting:UserSettingScope_PC_Online key:@"PC"];
  3731. NSString *webOnline = [self getUserSetting:UserSettingScope_PC_Online key:@"Web"];
  3732. NSString *wxOnline = [self getUserSetting:UserSettingScope_PC_Online key:@"WX"];
  3733. NSString *padOnline = [self getUserSetting:UserSettingScope_PC_Online key:@"Pad"];
  3734. NSMutableArray *output = [[NSMutableArray alloc] init];
  3735. if (pcOnline.length) {
  3736. [output addObject:[WFCCPCOnlineInfo infoFromStr:pcOnline withType:PC_Online]];
  3737. }
  3738. if (webOnline.length) {
  3739. [output addObject:[WFCCPCOnlineInfo infoFromStr:webOnline withType:Web_Online]];
  3740. }
  3741. if (wxOnline.length) {
  3742. [output addObject:[WFCCPCOnlineInfo infoFromStr:wxOnline withType:WX_Online]];
  3743. }
  3744. if (padOnline.length) {
  3745. [output addObject:[WFCCPCOnlineInfo infoFromStr:padOnline withType:Pad_Online]];
  3746. }
  3747. return output;
  3748. }
  3749. - (void)kickoffPCClient:(NSString *)pcClientId
  3750. success:(void(^)(void))successBlock
  3751. error:(void(^)(int error_code))errorBlock {
  3752. if(!pcClientId) {
  3753. if(errorBlock) {
  3754. errorBlock(-1);
  3755. }
  3756. return;
  3757. }
  3758. mars::stn::KickoffPCClient([pcClientId UTF8String], new IMGeneralOperationCallback(successBlock, errorBlock));
  3759. }
  3760. - (BOOL)isMuteNotificationWhenPcOnline {
  3761. NSString *strValue = [[WFCCIMService sharedWFCIMService] getUserSetting:UserSettingScope_Mute_When_PC_Online key:@""];
  3762. if ([strValue isEqualToString:@"1"]) {
  3763. return !self.defaultSilentWhenPCOnline;
  3764. }
  3765. return self.defaultSilentWhenPCOnline;
  3766. }
  3767. - (void)setDefaultSilentWhenPcOnline:(BOOL)defaultSilent {
  3768. self.defaultSilentWhenPCOnline = defaultSilent;
  3769. }
  3770. - (void)muteNotificationWhenPcOnline:(BOOL)isMute
  3771. success:(void(^)(void))successBlock
  3772. error:(void(^)(int error_code))errorBlock {
  3773. if(!self.defaultSilentWhenPCOnline) {
  3774. isMute = !isMute;
  3775. }
  3776. [[WFCCIMService sharedWFCIMService] setUserSetting:UserSettingScope_Mute_When_PC_Online key:@"" value:isMute? @"0" : @"1" success:successBlock error:errorBlock];
  3777. }
  3778. - (void)getConversationFiles:(WFCCConversation *)conversation
  3779. fromUser:(NSString *)userId
  3780. beforeMessageUid:(long long)messageUid
  3781. order:(WFCCFileRecordOrder)order
  3782. count:(int)count
  3783. success:(void(^)(NSArray<WFCCFileRecord *> *files))successBlock
  3784. error:(void(^)(int error_code))errorBlock {
  3785. mars::stn::TConversation conv;
  3786. conv.target = conversation.target ? [conversation.target UTF8String] : "";
  3787. conv.line = conversation.line;
  3788. conv.conversationType = (int)conversation.type;
  3789. std::string fromUser = userId ? [userId UTF8String] : "";
  3790. mars::stn::loadConversationFileRecords(conv, fromUser, messageUid, (int)order, count, new IMLoadFileRecordCallback(successBlock, errorBlock));
  3791. }
  3792. - (void)getMyFiles:(long long)beforeMessageUid
  3793. order:(WFCCFileRecordOrder)order
  3794. count:(int)count
  3795. success:(void(^)(NSArray<WFCCFileRecord *> *files))successBlock
  3796. error:(void(^)(int error_code))errorBlock {
  3797. mars::stn::loadMyFileRecords(beforeMessageUid, (int)order, count, new IMLoadFileRecordCallback(successBlock, errorBlock));
  3798. }
  3799. - (void)searchMyFiles:(NSString *)keyword
  3800. beforeMessageUid:(long long)beforeMessageUid
  3801. order:(WFCCFileRecordOrder)order
  3802. count:(int)count
  3803. success:(void(^)(NSArray<WFCCFileRecord *> *files))successBlock
  3804. error:(void(^)(int error_code))errorBlock {
  3805. if (!keyword.length) {
  3806. if(errorBlock) {
  3807. errorBlock(-1);
  3808. }
  3809. return;
  3810. }
  3811. mars::stn::searchMyFileRecords(keyword?[keyword UTF8String]:"", beforeMessageUid, (int)order, count, new IMLoadFileRecordCallback(successBlock, errorBlock));
  3812. }
  3813. - (void)deleteFileRecord:(long long)messageUid
  3814. success:(void(^)(void))successBlock
  3815. error:(void(^)(int error_code))errorBlock {
  3816. mars::stn::deleteFileRecords(messageUid, new IMGeneralOperationCallback(successBlock, errorBlock));
  3817. }
  3818. - (void)searchFiles:(NSString *)keyword
  3819. conversation:(WFCCConversation *)conversation
  3820. fromUser:(NSString *)userId
  3821. beforeMessageUid:(long long)messageUid
  3822. order:(WFCCFileRecordOrder)order
  3823. count:(int)count
  3824. success:(void(^)(NSArray<WFCCFileRecord *> *files))successBlock
  3825. error:(void(^)(int error_code))errorBlock {
  3826. if (!keyword.length) {
  3827. if(errorBlock) {
  3828. errorBlock(-1);
  3829. }
  3830. return;
  3831. }
  3832. mars::stn::TConversation conv;
  3833. conv.target = conversation.target ? [conversation.target UTF8String] : "";
  3834. conv.line = conversation.line;
  3835. conv.conversationType = (int)conversation.type;
  3836. std::string fromUser = userId ? [userId UTF8String] : "";
  3837. mars::stn::searchConversationFileRecords(keyword?[keyword UTF8String]:"", conv, fromUser, messageUid, (int)order, count, new IMLoadFileRecordCallback(successBlock, errorBlock));
  3838. }
  3839. - (void)getAuthorizedMediaUrl:(long long)messageUid
  3840. mediaType:(WFCCMediaType)mediaType
  3841. mediaPath:(NSString *)mediaPath
  3842. success:(void(^)(NSString *authorizedUrl, NSString *backupAuthorizedUrl))successBlock
  3843. error:(void(^)(int error_code))errorBlock {
  3844. mars::stn::getAuthorizedMediaUrl(messageUid, (int)mediaType, [mediaPath UTF8String], new IMGetAuthorizedMediaUrlCallback(successBlock, errorBlock));
  3845. }
  3846. - (void)getAuthCode:(NSString *)applicationId
  3847. type:(int)type
  3848. host:(NSString *)host
  3849. success:(void(^)(NSString *authCode))successBlock
  3850. error:(void(^)(int error_code))errorBlock {
  3851. mars::stn::GetAuthCode([applicationId UTF8String], type, [host UTF8String], new IMGeneralStringCallback(successBlock, errorBlock));
  3852. }
  3853. - (void)configApplication:(NSString *)applicationId
  3854. type:(int)type
  3855. timestamp:(int64_t)timestamp
  3856. nonce:(NSString *)nonce
  3857. signature:(NSString *)signature
  3858. success:(void(^)(void))successBlock
  3859. error:(void(^)(int error_code))errorBlock {
  3860. mars::stn::ApplicationConfig([applicationId UTF8String], type, timestamp, [nonce UTF8String], [signature UTF8String], new IMGeneralOperationCallback(successBlock, errorBlock));
  3861. }
  3862. - (NSData *)getWavData:(NSString *)amrPath {
  3863. if (![@"amr" isEqualToString:[amrPath pathExtension]]) {
  3864. return [NSData dataWithContentsOfFile:amrPath];
  3865. } else {
  3866. NSMutableData *data = [[NSMutableData alloc] init];
  3867. decode_amr([amrPath UTF8String], data);
  3868. return data;
  3869. }
  3870. }
  3871. - (NSString *)imageThumbPara {
  3872. std::string cstr = mars::stn::GetImageThumbPara();
  3873. if (cstr.empty()) {
  3874. return nil;
  3875. }
  3876. return [NSString stringWithUTF8String:cstr.c_str()];
  3877. }
  3878. - (long)insertMessage:(WFCCMessage *)message {
  3879. mars::stn::TMessage tmsg;
  3880. tmsg.messageUid = message.messageUid;
  3881. fillTMessage(tmsg, message.conversation, message.content);
  3882. if(message.status >= Message_Status_Unread) {
  3883. tmsg.direction = 1;
  3884. }
  3885. if(!message.fromUser)
  3886. message.fromUser = [WFCCNetworkService sharedInstance].userId;
  3887. tmsg.from = [message.fromUser UTF8String];
  3888. tmsg.status = (mars::stn::MessageStatus)message.status;
  3889. tmsg.timestamp = message.serverTime;
  3890. tmsg.localExtra = message.localExtra ? [message.localExtra UTF8String] : "";
  3891. if(message.toUsers.count) {
  3892. for (NSString *toUser in message.toUsers) {
  3893. tmsg.to.push_back([toUser UTF8String]);
  3894. }
  3895. }
  3896. long msgId = mars::stn::MessageDB::Instance()->InsertMessage(tmsg);
  3897. message.messageId = msgId;
  3898. return msgId;
  3899. }
  3900. - (int)getMessageCount:(WFCCConversation *)conversation {
  3901. return mars::stn::MessageDB::Instance()->GetMsgTotalCount((int)conversation.type, conversation.target?[conversation.target UTF8String]:"", conversation.line);
  3902. }
  3903. - (int)getConversationMessageCount:(NSArray<NSNumber *> *)conversationTypes
  3904. lines:(NSArray<NSNumber *> *)lines {
  3905. std::list<int> types;
  3906. for (NSNumber *type in conversationTypes) {
  3907. types.push_back([type intValue]);
  3908. }
  3909. std::list<int> ls;
  3910. for (NSNumber *type in lines) {
  3911. ls.push_back([type intValue]);
  3912. }
  3913. return mars::stn::MessageDB::Instance()->GetConversationMessageCount(types, ls);
  3914. }
  3915. - (BOOL)beginTransaction {
  3916. return mars::stn::MessageDB::Instance()->BeginTransaction();
  3917. }
  3918. - (BOOL)commitTransaction {
  3919. return mars::stn::MessageDB::Instance()->CommitTransaction();
  3920. }
  3921. - (BOOL)rollbackTransaction {
  3922. return mars::stn::MessageDB::Instance()->RollbackTransaction();
  3923. }
  3924. - (BOOL)isCommercialServer {
  3925. return mars::stn::IsCommercialServer() == true;
  3926. }
  3927. - (BOOL)isReceiptEnabled {
  3928. return mars::stn::IsReceiptEnabled() == true;
  3929. }
  3930. - (BOOL)isGroupReceiptEnabled {
  3931. return mars::stn::IsGroupReceiptEnabled() == true;
  3932. }
  3933. - (BOOL)isGlobalDisableSyncDraft {
  3934. return mars::stn::IsGlobalDisableSyncDraft() == true;
  3935. }
  3936. - (BOOL)isMeshEnabled {
  3937. return mars::stn::IsEnableMesh() == true;
  3938. }
  3939. - (WFCCUserOnlineState *)getUserOnlineState:(NSString *)userId {
  3940. return self.useOnlineCacheMap[userId];
  3941. }
  3942. - (WFCCUserCustomState *)getMyCustomState {
  3943. NSString *strValue = [[WFCCIMService sharedWFCIMService] getUserSetting:UserSettingScope_Custom_State key:@""];
  3944. if(strValue.length) {
  3945. NSRange range = [strValue rangeOfString:@"-"];
  3946. if(range.location != NSNotFound) {
  3947. WFCCUserCustomState *state = [[WFCCUserCustomState alloc] init];
  3948. NSString *numStr = [strValue substringToIndex:range.length];
  3949. NSString *text = [strValue substringFromIndex:range.length+1];
  3950. state.state = [numStr intValue];
  3951. state.text = text;
  3952. return state;
  3953. }
  3954. }
  3955. return nil;
  3956. }
  3957. - (void)setMyCustomState:(WFCCUserCustomState *)state
  3958. success:(void(^)(void))successBlock
  3959. error:(void(^)(int error_code))errorBlock {
  3960. if (!state.text) {
  3961. state.text = @"";
  3962. }
  3963. NSString *strValue = [NSString stringWithFormat:@"%d-%@", state.state, state.text];
  3964. [self setUserSetting:UserSettingScope_Custom_State key:@"" value:strValue success:successBlock error:errorBlock];
  3965. }
  3966. - (void)watchOnlineState:(WFCCConversationType)conversationType
  3967. targets:(NSArray<NSString *> *)targets
  3968. duration:(int)watchDuration
  3969. success:(void(^)(NSArray<WFCCUserOnlineState *> *states))successBlock
  3970. error:(void(^)(int error_code))errorBlock {
  3971. std::list<std::string> ts;
  3972. for (NSString *t in targets) {
  3973. ts.push_back([t UTF8String]);
  3974. }
  3975. mars::stn::watchOnlineState((int)conversationType, ts, watchDuration, new IMWatchOnlineStateCallback(successBlock, errorBlock));
  3976. }
  3977. - (void)unwatchOnlineState:(WFCCConversationType)conversationType
  3978. targets:(NSArray<NSString *> *)targets
  3979. success:(void(^)(void))successBlock
  3980. error:(void(^)(int error_code))errorBlock {
  3981. std::list<std::string> ts;
  3982. for (NSString *t in targets) {
  3983. ts.push_back([t UTF8String]);
  3984. }
  3985. mars::stn::unwatchOnlineState((int)conversationType, ts, new IMGeneralOperationCallback(successBlock, errorBlock));
  3986. }
  3987. - (BOOL)isEnableUserOnlineState {
  3988. return mars::stn::IsEnableUserOnlineState();
  3989. }
  3990. - (BOOL)isEnableSecretChat {
  3991. return mars::stn::IsEnableSecretChat();
  3992. }
  3993. - (BOOL)isUserEnableSecretChat {
  3994. NSString *strValue = [[WFCCIMService sharedWFCIMService] getUserSetting:UserSettingScope_Disable_Secret_Chat key:@""];
  3995. return ![strValue isEqualToString:@"1"];
  3996. }
  3997. - (void)setUserEnableSecretChat:(BOOL)enable
  3998. success:(void(^)(void))successBlock
  3999. error:(void(^)(int error_code))errorBlock {
  4000. [[WFCCIMService sharedWFCIMService] setUserSetting:UserSettingScope_Disable_Secret_Chat key:@"" value:enable?@"0":@"1" success:successBlock error:errorBlock];
  4001. }
  4002. - (void)sendConferenceRequest:(long long)sessionId
  4003. room:(NSString *)roomId
  4004. request:(NSString *)request
  4005. data:(NSString *)data
  4006. success:(void(^)(NSString *authorizedUrl))successBlock
  4007. error:(void(^)(int error_code))errorBlock {
  4008. [self sendConferenceRequest:sessionId room:roomId request:request data:data success:successBlock error:errorBlock];
  4009. }
  4010. - (void)sendConferenceRequest:(long long)sessionId
  4011. room:(NSString *)roomId
  4012. request:(NSString *)request
  4013. advanced:(BOOL)advanced
  4014. data:(NSString *)data
  4015. success:(void(^)(NSString *authorizedUrl))successBlock
  4016. error:(void(^)(int error_code))errorBlock {
  4017. mars::stn::sendConferenceRequest(sessionId, roomId?[roomId UTF8String]:"", [request UTF8String], advanced?true:false, data ? [data UTF8String]:"", new IMGeneralStringCallback(successBlock, errorBlock));
  4018. }
  4019. - (NSArray<NSString *> *)getFavUsers {
  4020. NSDictionary *favUserDict = [[WFCCIMService sharedWFCIMService] getUserSettings:UserSettingScope_Favourite_User];
  4021. NSMutableArray *ids = [[NSMutableArray alloc] init];
  4022. [favUserDict enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
  4023. if ([obj isEqualToString:@"1"]) {
  4024. [ids addObject:key];
  4025. }
  4026. }];
  4027. return ids;
  4028. }
  4029. - (BOOL)isFavUser:(NSString *)userId {
  4030. NSString *strValue = [[WFCCIMService sharedWFCIMService] getUserSetting:UserSettingScope_Favourite_User key:userId];
  4031. if ([strValue isEqualToString:@"1"]) {
  4032. return YES;
  4033. }
  4034. return NO;
  4035. }
  4036. - (void)setFavUser:(NSString *)userId fav:(BOOL)fav success:(void(^)(void))successBlock error:(void(^)(int errorCode))errorBlock {
  4037. [[WFCCIMService sharedWFCIMService] setUserSetting:UserSettingScope_Favourite_User key:userId value:fav? @"1" : @"0" success:successBlock error:errorBlock];
  4038. }
  4039. - (void)requireLock:(NSString *)lockId
  4040. duration:(NSUInteger)duration
  4041. success:(void(^)(void))successBlock
  4042. error:(void(^)(int error_code))errorBlock {
  4043. mars::stn::requireLock([lockId UTF8String], duration, new IMGeneralOperationCallback(successBlock, errorBlock));
  4044. }
  4045. - (void)releaseLock:(NSString *)lockId
  4046. success:(void(^)(void))successBlock
  4047. error:(void(^)(int error_code))errorBlock {
  4048. mars::stn::releaseLock([lockId UTF8String], new IMGeneralOperationCallback(successBlock, errorBlock));
  4049. }
  4050. - (BOOL)onReceiveMessage:(WFCCMessage *)message {
  4051. if([message.content isKindOfClass:[WFCCMarkUnreadMessageContent class]] && [message.fromUser isEqualToString:[WFCCNetworkService sharedInstance].userId]) {
  4052. WFCCMarkUnreadMessageContent *markMsg = (WFCCMarkUnreadMessageContent*)message.content;
  4053. WFCCConversation *conversation = message.conversation;
  4054. mars::stn::MessageDB::Instance()->SetLastReceivedMessageUnRead((int)conversation.type, [conversation.target UTF8String], conversation.line, markMsg.messageUid, markMsg.timestamp);
  4055. WFCCMessage *msg = [self getMessageByUid:markMsg.messageUid];
  4056. NSLog(@"timestamp is %lld", msg.serverTime);
  4057. }
  4058. return NO;
  4059. }
  4060. - (void)putUseOnlineStates:(NSArray<WFCCUserOnlineState *> *)states {
  4061. [states enumerateObjectsUsingBlock:^(WFCCUserOnlineState * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  4062. [self.useOnlineCacheMap setObject:obj forKey:obj.userId];
  4063. }];
  4064. }
  4065. @end