CCMain.m 234 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294
  1. //
  2. // CCMain.m
  3. // Nextcloud iOS
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2017 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "CCMain.h"
  24. #import "AppDelegate.h"
  25. #import "CCPhotos.h"
  26. #import "CCSynchronize.h"
  27. #import "CCTransfersCell.h"
  28. #import "OCActivity.h"
  29. #import "OCNotifications.h"
  30. #import "OCNotificationsAction.h"
  31. #import "OCFrameworkConstants.h"
  32. #import "OCCapabilities.h"
  33. #import "CTAssetCheckmark.h"
  34. #import "JDStatusBarNotification.h"
  35. #import "NCAutoUpload.h"
  36. #import "NCBridgeSwift.h"
  37. #import "NCNetworkingSync.h"
  38. @interface CCMain () <CCActionsDeleteDelegate, CCActionsRenameDelegate, CCActionsSearchDelegate, CCActionsDownloadThumbnailDelegate, CCActionsSettingFavoriteDelegate, UITextViewDelegate, createFormUploadAssetsDelegate, MGSwipeTableCellDelegate, CCLoginDelegate, CCLoginDelegateWeb>
  39. {
  40. AppDelegate *appDelegate;
  41. tableMetadata *_metadata;
  42. BOOL _isRoot;
  43. BOOL _isViewDidLoad;
  44. BOOL _isSelectedMode;
  45. NSMutableDictionary *_selectedFileIDsMetadatas;
  46. NSUInteger _numSelectedFileIDsMetadatas;
  47. NSMutableArray *_queueSelector;
  48. NSMutableDictionary *_statusSwipeCell;
  49. UIImageView *_ImageTitleHomeCryptoCloud;
  50. UIView *_reMenuBackgroundView;
  51. UITapGestureRecognizer *_singleFingerTap;
  52. NSString *_directoryGroupBy;
  53. NSString *_directoryOrder;
  54. NSUInteger _failedAttempts;
  55. NSDate *_lockUntilDate;
  56. NSString *_fatherPermission;
  57. UIRefreshControl *_refreshControl;
  58. UIDocumentInteractionController *_docController;
  59. CCHud *_hud;
  60. // Datasource
  61. CCSectionDataSourceMetadata *_sectionDataSource;
  62. NSDate *_dateReadDataSource;
  63. // Search
  64. BOOL _isSearchMode;
  65. NSString *_searchFileName;
  66. NSMutableArray *_searchResultMetadatas;
  67. NSString *_noFilesSearchTitle;
  68. NSString *_noFilesSearchDescription;
  69. NSTimer *_timerWaitInput;
  70. // Login
  71. CCLoginWeb *_loginWeb;
  72. CCLogin *_loginVC;
  73. // Automatic Upload Folder
  74. NSString *_autoUploadFileName;
  75. NSString *_autoUploadDirectory;
  76. // Folder
  77. BOOL _loadingFolder;
  78. tableMetadata *_metadataFolder;
  79. }
  80. @end
  81. @implementation CCMain
  82. #pragma --------------------------------------------------------------------------------------------
  83. #pragma mark ===== Init =====
  84. #pragma --------------------------------------------------------------------------------------------
  85. - (id)initWithCoder:(NSCoder *)aDecoder
  86. {
  87. if (self = [super initWithCoder:aDecoder]) {
  88. appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  89. _directoryOrder = [CCUtility getOrderSettings];
  90. _directoryGroupBy = [CCUtility getGroupBySettings];
  91. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initializeMain:) name:@"initializeMain" object:nil];
  92. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearDateReadDataSource:) name:@"clearDateReadDataSource" object:nil];
  93. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTitle) name:@"setTitleMain" object:nil];
  94. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:@"NotificationProgressTask" object:nil];
  95. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheming) name:@"changeTheming" object:nil];
  96. }
  97. return self;
  98. }
  99. #pragma --------------------------------------------------------------------------------------------
  100. #pragma mark ===== View =====
  101. #pragma --------------------------------------------------------------------------------------------
  102. - (void)viewDidLoad
  103. {
  104. [super viewDidLoad];
  105. // init object
  106. _metadata = [tableMetadata new];
  107. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  108. _selectedFileIDsMetadatas = [NSMutableDictionary new];
  109. _statusSwipeCell = [NSMutableDictionary new];
  110. _queueSelector = [NSMutableArray new];
  111. _isViewDidLoad = YES;
  112. _fatherPermission = @"";
  113. _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
  114. _searchResultMetadatas = [NSMutableArray new];
  115. _searchFileName = @"";
  116. _noFilesSearchTitle = @"";
  117. _noFilesSearchDescription = @"";
  118. // delegate
  119. self.tableView.delegate = self;
  120. self.tableView.tableFooterView = [UIView new];
  121. self.tableView.separatorColor = [NCBrandColor sharedInstance].seperator;
  122. self.tableView.emptyDataSetDelegate = self;
  123. self.tableView.emptyDataSetSource = self;
  124. self.searchController.delegate = self;
  125. self.searchController.searchBar.delegate = self;
  126. [CCNetworking sharedNetworking].delegate = self;
  127. // Custom Cell
  128. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMain" bundle:nil] forCellReuseIdentifier:@"CellMain"];
  129. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMainTransfer" bundle:nil] forCellReuseIdentifier:@"CellMainTransfer"];
  130. // long press recognizer TableView
  131. UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPressTableView:)];
  132. [self.tableView addGestureRecognizer:longPressRecognizer];
  133. // Pull-to-Refresh
  134. [self createRefreshControl];
  135. // Register for 3D Touch Previewing if available
  136. if ([self.traitCollection respondsToSelector:@selector(forceTouchCapability)] && (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable))
  137. {
  138. [self registerForPreviewingWithDelegate:self sourceView:self.view];
  139. }
  140. // Back Button
  141. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]])
  142. self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationLogo"] style:UIBarButtonItemStylePlain target:nil action:nil];
  143. // reMenu Background
  144. _reMenuBackgroundView = [[UIView alloc] init];
  145. _reMenuBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
  146. // if this is not Main (the Main uses inizializeMain)
  147. if (_isRoot == NO && appDelegate.activeAccount.length > 0) {
  148. // Settings this folder & delegate & Loading datasource
  149. appDelegate.directoryUser = [CCUtility getDirectoryActiveUser:appDelegate.activeUser activeUrl:appDelegate.activeUrl];
  150. // Load Datasource
  151. [self reloadDatasource:_serverUrl];
  152. // Read (File) Folder
  153. [self readFileReloadFolder];
  154. }
  155. // Title
  156. [self setTitle];
  157. }
  158. // Apparirà
  159. - (void)viewWillAppear:(BOOL)animated
  160. {
  161. [super viewWillAppear:animated];
  162. // test
  163. if (appDelegate.activeAccount.length == 0)
  164. return;
  165. // Settings this folder & delegate & Loading datasource
  166. appDelegate.directoryUser = [CCUtility getDirectoryActiveUser:appDelegate.activeUser activeUrl:appDelegate.activeUrl];
  167. [CCNetworking sharedNetworking].delegate = self;
  168. // Color
  169. [appDelegate aspectNavigationControllerBar:self.navigationController.navigationBar online:[appDelegate.reachability isReachable] hidden:NO];
  170. [appDelegate aspectTabBar:self.tabBarController.tabBar hidden:NO];
  171. if (_isSelectedMode)
  172. [self setUINavigationBarSelected];
  173. else
  174. [self setUINavigationBarDefault];
  175. // If not editing mode remove _selectedFileIDs
  176. if (!self.tableView.editing)
  177. [_selectedFileIDsMetadatas removeAllObjects];
  178. // Plus Button
  179. [appDelegate plusButtonVisibile:true];
  180. // Search Bar
  181. if ([CCUtility isFolderEncrypted:self.serverUrl account:appDelegate.activeAccount]) {
  182. [self searchEnabled:NO];
  183. } else {
  184. [self searchEnabled:YES];
  185. }
  186. }
  187. // E' arrivato
  188. - (void)viewDidAppear:(BOOL)animated
  189. {
  190. [super viewDidAppear:animated];
  191. // Active Main
  192. appDelegate.activeMain = self;
  193. // Test viewDidLoad
  194. if (_isViewDidLoad) {
  195. _isViewDidLoad = NO;
  196. } else {
  197. if (appDelegate.activeAccount.length > 0 && [_selectedFileIDsMetadatas count] == 0) {
  198. // Load Datasource
  199. [self reloadDatasource:_serverUrl];
  200. // Read (file) Folder
  201. [self readFileReloadFolder];
  202. }
  203. }
  204. // Title
  205. [self setTitle];
  206. }
  207. - (void)viewWillDisappear:(BOOL)animated
  208. {
  209. [super viewWillDisappear:animated];
  210. [self closeAllMenu];
  211. }
  212. - (void)didReceiveMemoryWarning
  213. {
  214. [super didReceiveMemoryWarning];
  215. // Dispose of any resources that can be recreated.
  216. }
  217. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  218. {
  219. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  220. [self closeAllMenu];
  221. [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  222. if (self.view.frame.size.width == ([[UIScreen mainScreen] bounds].size.width*([[UIScreen mainScreen] bounds].size.width<[[UIScreen mainScreen] bounds].size.height))+([[UIScreen mainScreen] bounds].size.height*([[UIScreen mainScreen] bounds].size.width>[[UIScreen mainScreen] bounds].size.height))) {
  223. // Portrait
  224. } else {
  225. // Landscape
  226. }
  227. [self.tableView reloadData];
  228. }];
  229. }
  230. - (BOOL)prefersStatusBarHidden
  231. {
  232. return NO;
  233. }
  234. // detect scroll for remove keyboard in search mode
  235. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  236. {
  237. if (_isSearchMode && scrollView == self.tableView) {
  238. [self.searchController.searchBar endEditing:YES];
  239. }
  240. }
  241. - (void)changeTheming
  242. {
  243. if (self.isViewLoaded && self.view.window)
  244. [appDelegate changeTheming:self];
  245. // Refresh control
  246. _refreshControl.backgroundColor = [NCBrandColor sharedInstance].brand;
  247. // color searchbar
  248. self.searchController.searchBar.barTintColor = [NCBrandColor sharedInstance].brand;
  249. self.searchController.searchBar.backgroundColor = [NCBrandColor sharedInstance].brand;
  250. // Title
  251. [self setTitle];
  252. // Reload Table View
  253. [self tableViewReloadData];
  254. }
  255. #pragma --------------------------------------------------------------------------------------------
  256. #pragma mark ===== Initizlize Mail =====
  257. #pragma --------------------------------------------------------------------------------------------
  258. - (void)initializeMain:(NSNotification *)notification
  259. {
  260. _directoryGroupBy = nil;
  261. _directoryOrder = nil;
  262. _dateReadDataSource = nil;
  263. // test
  264. if (appDelegate.activeAccount.length == 0)
  265. return;
  266. if ([appDelegate.listMainVC count] == 0 || _isRoot) {
  267. // This is Root home main add list
  268. appDelegate.homeMain = self;
  269. _isRoot = YES;
  270. _serverUrl = [CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl];
  271. appDelegate.directoryUser = [CCUtility getDirectoryActiveUser:appDelegate.activeUser activeUrl:appDelegate.activeUrl];
  272. [appDelegate.listMainVC setObject:self forKey:_serverUrl];
  273. // go Home
  274. [self.navigationController popToRootViewControllerAnimated:NO];
  275. // setting Networking
  276. [CCNetworking sharedNetworking].delegate = self;
  277. [[CCNetworking sharedNetworking] settingAccount];
  278. // Remove search mode
  279. [self cancelSearchBar];
  280. // populate shared Link & User
  281. NSArray *results = [[NCManageDatabase sharedInstance] getShares];
  282. if (results) {
  283. appDelegate.sharesLink = results[0];
  284. appDelegate.sharesUserAndGroup = results[1];
  285. }
  286. // Load Datasource
  287. [self reloadDatasource:_serverUrl];
  288. // Read (File) Folder
  289. [self readFileReloadFolder];
  290. // Setting Theming
  291. [appDelegate settingThemingColorBrand];
  292. // Load photo datasorce
  293. if (appDelegate.activePhotos)
  294. [appDelegate.activePhotos reloadDatasourceForced];
  295. // remove all of detail
  296. if (appDelegate.activeDetail)
  297. [appDelegate.activeDetail removeAllView];
  298. // remove all Notification Messages
  299. [appDelegate.listOfNotifications removeAllObjects];
  300. // Not Photos Video in library ? then align
  301. NSArray *recordsPhotoLibrary = [[NCManageDatabase sharedInstance] getPhotoLibraryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", appDelegate.activeAccount]];
  302. if ([recordsPhotoLibrary count] == 0) {
  303. [[NCAutoUpload sharedInstance] alignPhotoLibrary];
  304. }
  305. // Initializations
  306. [appDelegate applicationInitialized];
  307. } else {
  308. // reload datasource
  309. [self reloadDatasource:_serverUrl];
  310. }
  311. }
  312. #pragma --------------------------------------------------------------------------------------------
  313. #pragma mark ==== DZNEmptyDataSetSource ====
  314. #pragma --------------------------------------------------------------------------------------------
  315. - (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
  316. {
  317. if (_loadingFolder)
  318. return NO;
  319. else
  320. return YES;
  321. }
  322. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  323. {
  324. return [UIColor whiteColor];
  325. }
  326. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  327. {
  328. if (_isSearchMode)
  329. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"searchBig"] color:[NCBrandColor sharedInstance].brandElement];
  330. else
  331. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"filesNoFiles"] color:[NCBrandColor sharedInstance].brandElement];
  332. }
  333. - (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView
  334. {
  335. if (_loadingFolder && _refreshControl.isRefreshing == NO) {
  336. UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
  337. activityView.transform = CGAffineTransformMakeScale(1.5f, 1.5f);
  338. activityView.color = [NCBrandColor sharedInstance].brandElement;
  339. [activityView startAnimating];
  340. return activityView;
  341. }
  342. return nil;
  343. }
  344. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  345. {
  346. NSString *text;
  347. if (_isSearchMode) {
  348. text = _noFilesSearchTitle;
  349. } else {
  350. text = [NSString stringWithFormat:@"%@", NSLocalizedString(@"_files_no_files_", nil)];
  351. }
  352. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:[UIColor lightGrayColor]};
  353. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  354. }
  355. - (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
  356. {
  357. NSString *text;
  358. if (_isSearchMode) {
  359. text = _noFilesSearchDescription;
  360. } else {
  361. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_no_file_pull_down_", nil)];
  362. }
  363. NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
  364. paragraph.lineBreakMode = NSLineBreakByWordWrapping;
  365. paragraph.alignment = NSTextAlignmentCenter;
  366. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor lightGrayColor], NSParagraphStyleAttributeName: paragraph};
  367. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  368. }
  369. #pragma --------------------------------------------------------------------------------------------
  370. #pragma mark ===== Text Field =====
  371. #pragma --------------------------------------------------------------------------------------------
  372. - (void)minCharTextFieldDidChange:(UITextField *)sender
  373. {
  374. UIAlertController *alertController = (UIAlertController *)self.presentedViewController;
  375. if (alertController)
  376. {
  377. UITextField *fileName = alertController.textFields.firstObject;
  378. UIAlertAction *okAction = alertController.actions.lastObject;
  379. okAction.enabled = fileName.text.length > 0;
  380. }
  381. }
  382. - (void)textFieldDidBeginEditing:(UITextField *)textField{
  383. [textField selectAll:textField];
  384. }
  385. #pragma --------------------------------------------------------------------------------------------
  386. #pragma mark ===== Graphic Window =====
  387. #pragma --------------------------------------------------------------------------------------------
  388. - (void)createRefreshControl
  389. {
  390. _refreshControl = [UIRefreshControl new];
  391. _refreshControl.tintColor = [NCBrandColor sharedInstance].brandElement;
  392. _refreshControl.backgroundColor = [NCBrandColor sharedInstance].brand;
  393. [self setRefreshControl:_refreshControl];
  394. [_refreshControl addTarget:self action:@selector(refreshControlTarget) forControlEvents:UIControlEventValueChanged];
  395. }
  396. - (void)deleteRefreshControl
  397. {
  398. [_refreshControl endRefreshing];
  399. self.refreshControl = nil;
  400. }
  401. - (void)refreshControlTarget
  402. {
  403. [self readFolder:_serverUrl];
  404. // Actuate `Peek` feedback (weak boom)
  405. AudioServicesPlaySystemSound(1519);
  406. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  407. }
  408. - (void)setTitle
  409. {
  410. // Color text self.navigationItem.title
  411. [appDelegate aspectNavigationControllerBar:self.navigationController.navigationBar online:[appDelegate.reachability isReachable] hidden:NO];
  412. if (_isSelectedMode) {
  413. NSUInteger totali = [_sectionDataSource.allRecordsDataSource count];
  414. NSUInteger selezionati = [[self.tableView indexPathsForSelectedRows] count];
  415. self.navigationItem.titleView = nil;
  416. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)selezionati, (unsigned long)totali];
  417. } else {
  418. // we are in home : LOGO BRAND
  419. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]]) {
  420. self.navigationItem.title = nil;
  421. if ([appDelegate.reachability isReachable] == NO) {
  422. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigationLogoOffline"]];
  423. } else {
  424. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilites];
  425. if ([capabilities.themingColor isEqualToString:@"#FFFFFF"])
  426. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"navigationLogo"] color:[UIColor blackColor]]];
  427. else
  428. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"navigationLogo"] color:[UIColor whiteColor]]];
  429. }
  430. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  431. UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(menuLogo:)];
  432. [singleTap setNumberOfTapsRequired:1];
  433. [_ImageTitleHomeCryptoCloud addGestureRecognizer:singleTap];
  434. self.navigationItem.titleView = _ImageTitleHomeCryptoCloud;
  435. } else {
  436. NSString *shareLink, *shareUserAndGroup;
  437. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadataFolder.directoryID];
  438. if (serverUrl) {
  439. shareLink = [appDelegate.sharesLink objectForKey:[serverUrl stringByAppendingString:_metadataFolder.fileName]];
  440. shareUserAndGroup = [appDelegate.sharesUserAndGroup objectForKey:[serverUrl stringByAppendingString:_metadataFolder.fileName]];
  441. }
  442. if (_metadataFolder.e2eEncrypted) {
  443. [CCGraphics addImageToTile:_titleMain colorTitle:[NCBrandColor sharedInstance].brandText imageTitle:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"titleEncrypted"] color:[NCBrandColor sharedInstance].brandText] navigationItem:self.navigationItem];
  444. } else if ([[[NCManageDatabase sharedInstance] getAccountAutoUploadPath:appDelegate.activeUrl] isEqualToString:self.serverUrl]) {
  445. [CCGraphics addImageToTile:_titleMain colorTitle:[NCBrandColor sharedInstance].brandText imageTitle:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"titlePhotos"] color:[NCBrandColor sharedInstance].brandText] navigationItem:self.navigationItem];
  446. } else if ([_metadataFolder.permissions containsString:k_permission_shared] || [_metadataFolder.permissions containsString:k_permission_mounted] || shareLink.length > 0 || shareUserAndGroup.length > 0) {
  447. [CCGraphics addImageToTile:_titleMain colorTitle:[NCBrandColor sharedInstance].brandText imageTitle:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"titleShare"] color:[NCBrandColor sharedInstance].brandText] navigationItem:self.navigationItem];
  448. } else {
  449. self.navigationItem.title = _titleMain;
  450. }
  451. }
  452. }
  453. }
  454. - (void)setUINavigationBarDefault
  455. {
  456. [appDelegate aspectNavigationControllerBar:self.navigationController.navigationBar online:[appDelegate.reachability isReachable] hidden:NO];
  457. UIBarButtonItem *buttonMore, *buttonNotification;
  458. // =
  459. buttonMore = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationControllerMenu"] style:UIBarButtonItemStylePlain target:self action:@selector(toggleReMainMenu)];
  460. buttonMore.enabled = true;
  461. // <
  462. self.navigationController.navigationBar.hidden = NO;
  463. // Notification
  464. if ([appDelegate.listOfNotifications count] > 0) {
  465. buttonNotification = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"notification"] style:UIBarButtonItemStylePlain target:self action:@selector(viewNotification)];
  466. buttonNotification.tintColor = [NCBrandColor sharedInstance].brandText;
  467. buttonNotification.enabled = true;
  468. }
  469. if (buttonNotification)
  470. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, buttonNotification, nil];
  471. else
  472. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  473. self.navigationItem.leftBarButtonItem = nil;
  474. }
  475. - (void)setUINavigationBarSelected
  476. {
  477. [appDelegate aspectNavigationControllerBar:self.navigationController.navigationBar online:[appDelegate.reachability isReachable] hidden:NO];
  478. UIImage *icon = [UIImage imageNamed:@"navigationControllerMenu"];
  479. UIBarButtonItem *buttonMore = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(toggleReSelectMenu)];
  480. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(cancelSelect)];
  481. self.navigationItem.leftBarButtonItem = leftButton;
  482. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  483. }
  484. - (void)cancelSelect
  485. {
  486. [self tableViewSelect:NO];
  487. [appDelegate.reSelectMenu close];
  488. }
  489. - (void)closeAllMenu
  490. {
  491. // close Menu
  492. [appDelegate.reSelectMenu close];
  493. [appDelegate.reMainMenu close];
  494. // Close Menu Logo
  495. [CCMenuAccount dismissMenu];
  496. }
  497. #pragma --------------------------------------------------------------------------------------------
  498. #pragma mark ===== Document Picker =====
  499. #pragma --------------------------------------------------------------------------------------------
  500. - (void)documentMenuWasCancelled:(UIDocumentMenuViewController *)documentMenu
  501. {
  502. NSLog(@"[LOG] Cancelled");
  503. }
  504. - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller
  505. {
  506. NSLog(@"[LOG] Cancelled");
  507. }
  508. - (void)documentMenu:(UIDocumentMenuViewController *)documentMenu didPickDocumentPicker:(UIDocumentPickerViewController *)documentPicker
  509. {
  510. documentPicker.delegate = self;
  511. [self presentViewController:documentPicker animated:YES completion:nil];
  512. }
  513. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
  514. {
  515. if (controller.documentPickerMode == UIDocumentPickerModeImport) {
  516. NSString *serverUrl = [appDelegate getTabBarControllerActiveServerUrl];
  517. NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
  518. __block NSError *error;
  519. [coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
  520. NSString *fileName = [url lastPathComponent];
  521. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, fileName];
  522. NSData *data = [NSData dataWithContentsOfURL:newURL];
  523. if (data && error == nil) {
  524. if ([data writeToFile:fileNamePath options:NSDataWritingAtomic error:&error]) {
  525. // Upload File
  526. [[CCNetworking sharedNetworking] uploadFile:fileName serverUrl:serverUrl session:k_upload_session taskStatus: k_taskStatusResume selector:@"" selectorPost:@"" errorCode:0 delegate:nil];
  527. } else {
  528. [appDelegate messageNotification:@"_error_" description:error.description visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  529. }
  530. } else {
  531. [appDelegate messageNotification:@"_error_" description:@"_read_file_error_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  532. }
  533. }];
  534. }
  535. }
  536. - (void)openImportDocumentPicker
  537. {
  538. UIDocumentMenuViewController *documentProviderMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:@[@"public.data"] inMode:UIDocumentPickerModeImport];
  539. documentProviderMenu.modalPresentationStyle = UIModalPresentationFormSheet;
  540. documentProviderMenu.popoverPresentationController.sourceView = self.view;
  541. documentProviderMenu.popoverPresentationController.sourceRect = self.view.bounds;
  542. documentProviderMenu.delegate = self;
  543. [self presentViewController:documentProviderMenu animated:YES completion:nil];
  544. }
  545. #pragma --------------------------------------------------------------------------------------------
  546. #pragma mark ===== Assets Picker =====
  547. #pragma --------------------------------------------------------------------------------------------
  548. -(void)dismissFormUploadAssets
  549. {
  550. [self reloadDatasource];
  551. }
  552. - (void)openAssetsPickerController
  553. {
  554. CTAssetCheckmark *checkmark = [CTAssetCheckmark appearance];
  555. checkmark.tintColor = [NCBrandColor sharedInstance].brandElement;
  556. [checkmark setMargin:0.0 forVerticalEdge:NSLayoutAttributeRight horizontalEdge:NSLayoutAttributeTop];
  557. //UINavigationBar *navBar = [UINavigationBar appearanceWhenContainedIn:[CTAssetsPickerController class], nil]; // DEPRECATED iOS9
  558. UINavigationBar *navBar = [UINavigationBar appearanceWhenContainedInInstancesOfClasses:@[[CTAssetsPickerController class]]];
  559. [appDelegate aspectNavigationControllerBar:navBar online:YES hidden:NO];
  560. [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status){
  561. dispatch_async(dispatch_get_main_queue(), ^{
  562. CTAssetCheckmark *checkmark = [CTAssetCheckmark appearance];
  563. [checkmark setMargin:0.0 forVerticalEdge:NSLayoutAttributeRight horizontalEdge:NSLayoutAttributeBottom];
  564. // init picker
  565. CTAssetsPickerController *picker = [CTAssetsPickerController new];
  566. // set delegate
  567. picker.delegate = self;
  568. // to show selection order
  569. //picker.showsSelectionIndex = YES;
  570. // to present picker as a form sheet in iPad
  571. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  572. picker.modalPresentationStyle = UIModalPresentationFormSheet;
  573. // present picker
  574. [self presentViewController:picker animated:YES completion:nil];
  575. });
  576. }];
  577. }
  578. - (BOOL)assetsPickerController:(CTAssetsPickerController *)picker shouldSelectAsset:(PHAsset *)asset
  579. {
  580. if (picker.selectedAssets.count > k_pickerControllerMax) {
  581. [appDelegate messageNotification:@"_info_" description:@"_limited_dimension_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  582. return NO;
  583. }
  584. return YES;
  585. }
  586. - (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSMutableArray *)assets
  587. {
  588. [picker dismissViewControllerAnimated:YES completion:^{
  589. NSString *serverUrl = [appDelegate getTabBarControllerActiveServerUrl];
  590. CreateFormUploadAssets *form = [[CreateFormUploadAssets alloc] initWithServerUrl:serverUrl assets:assets cryptated:NO session:k_upload_session delegate:self];
  591. form.title = NSLocalizedString(@"_upload_photos_videos_", nil);
  592. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:form];
  593. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  594. [self presentViewController:navigationController animated:YES completion:nil];
  595. }];
  596. }
  597. // New folder or new photo or video
  598. - (void)returnCreate:(NSInteger)type
  599. {
  600. switch (type) {
  601. case k_returnCreateFolderPlain: {
  602. NSString *serverUrl = [appDelegate getTabBarControllerActiveServerUrl];
  603. NSString *message;
  604. UIAlertController *alertController;
  605. if ([serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]]) {
  606. message = @"/";
  607. } else {
  608. message = [serverUrl lastPathComponent];
  609. }
  610. alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_create_folder_on_",nil) message:message preferredStyle:UIAlertControllerStyleAlert];
  611. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  612. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  613. textField.autocapitalizationType = UITextAutocapitalizationTypeWords;
  614. }];
  615. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  616. NSLog(@"[LOG] Cancel action");
  617. }];
  618. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  619. UITextField *fileName = alertController.textFields.firstObject;
  620. [self createFolder:fileName.text serverUrl:serverUrl];
  621. }];
  622. okAction.enabled = NO;
  623. [alertController addAction:cancelAction];
  624. [alertController addAction:okAction];
  625. [self presentViewController:alertController animated:YES completion:nil];
  626. }
  627. break;
  628. case k_returnCreateFotoVideoPlain: {
  629. [self openAssetsPickerController];
  630. }
  631. break;
  632. case k_returnCreateFilePlain: {
  633. [self openImportDocumentPicker];
  634. }
  635. break;
  636. case k_returnCreateFotoVideoEncrypted: {
  637. [self openAssetsPickerController];
  638. }
  639. break;
  640. case k_returnCreateFileEncrypted: {
  641. [self openImportDocumentPicker];
  642. }
  643. break;
  644. case k_returnCreateFileText: {
  645. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"NCText" bundle:nil] instantiateViewControllerWithIdentifier:@"NCText"];
  646. navigationController.modalPresentationStyle = UIModalPresentationPageSheet;
  647. [self presentViewController:navigationController animated:YES completion:nil];
  648. }
  649. break;
  650. }
  651. }
  652. #pragma --------------------------------------------------------------------------------------------
  653. #pragma mark ===== Save selected File =====
  654. #pragma --------------------------------------------------------------------------------------------
  655. -(void)saveSelectedFilesSelector:(NSString *)path didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
  656. {
  657. if (error)
  658. [appDelegate messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  659. else
  660. [appDelegate messageNotification:@"_save_selected_files_" description:@"_file_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:error.code];
  661. }
  662. - (void)saveSelectedFiles
  663. {
  664. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  665. return;
  666. NSLog(@"[LOG] Start download selected files ...");
  667. [_hud visibleHudTitle:@"" mode:MBProgressHUDModeIndeterminate color:nil];
  668. NSArray *metadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  669. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  670. for (tableMetadata *metadata in metadatas) {
  671. if (metadata.directory == NO && ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])) {
  672. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  673. if (serverUrl)
  674. [[CCNetworking sharedNetworking] downloadFile:metadata.fileName fileID:metadata.fileID serverUrl:serverUrl selector:selectorSave selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  675. }
  676. }
  677. [_hud hideHud];
  678. });
  679. [self tableViewSelect:NO];
  680. }
  681. #pragma --------------------------------------------------------------------------------------------
  682. #pragma mark === Delegate Login ===
  683. #pragma --------------------------------------------------------------------------------------------
  684. - (void)loginSuccess:(NSInteger)loginType
  685. {
  686. [self readFolder:_serverUrl];
  687. }
  688. - (void)loginDisappear
  689. {
  690. appDelegate.activeLogin = nil;
  691. }
  692. #pragma mark -
  693. #pragma --------------------------------------------------------------------------------------------
  694. #pragma mark ===== Peek & Pop =====
  695. #pragma --------------------------------------------------------------------------------------------
  696. - (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
  697. {
  698. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  699. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  700. if (metadata.thumbnailExists && _metadataFolder.e2eEncrypted == NO) {
  701. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  702. if (cell) {
  703. previewingContext.sourceRect = cell.frame;
  704. CCPeekPop *vc = [[UIStoryboard storyboardWithName:@"CCPeekPop" bundle:nil] instantiateViewControllerWithIdentifier:@"PeekPopImagePreview"];
  705. vc.delegate = self;
  706. vc.metadata = metadata;
  707. return vc;
  708. }
  709. }
  710. return nil;
  711. }
  712. - (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
  713. {
  714. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:previewingContext.sourceRect.origin];
  715. [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
  716. }
  717. #pragma mark -
  718. #pragma --------------------------------------------------------------------------------------------
  719. #pragma mark ==== External Sites ====
  720. #pragma --------------------------------------------------------------------------------------------
  721. - (void)getExternalSitesServerSuccess:(NSArray *)listOfExternalSites
  722. {
  723. [[NCManageDatabase sharedInstance] deleteExternalSites];
  724. for (OCExternalSites *tableExternalSites in listOfExternalSites)
  725. [[NCManageDatabase sharedInstance] addExternalSites:tableExternalSites];
  726. }
  727. - (void)getExternalSitesServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  728. {
  729. NSString *error = [NSString stringWithFormat:@"Get external site failure error %d, %@", (int)errorCode, message];
  730. NSLog(@"[LOG] %@", error);
  731. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionCapabilities selector:@"Get External Sites Server" note:error type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:appDelegate.activeUrl];
  732. }
  733. #pragma --------------------------------------------------------------------------------------------
  734. #pragma mark ==== Activity ====
  735. #pragma --------------------------------------------------------------------------------------------
  736. - (void)getActivityServerSuccess:(NSArray *)listOfActivity
  737. {
  738. [[NCManageDatabase sharedInstance] addActivityServer:listOfActivity];
  739. // Reload Activity Data Source
  740. [appDelegate.activeActivity reloadDatasource];
  741. }
  742. - (void)getActivityServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  743. {
  744. NSString *error = [NSString stringWithFormat:@"Get Activity Server failure error %d, %@", (int)errorCode, message];
  745. NSLog(@"[LOG] %@", error);
  746. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionCapabilities selector:@"Get Activity Server" note:error type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:appDelegate.activeUrl];
  747. }
  748. #pragma --------------------------------------------------------------------------------------------
  749. #pragma mark ==== Notification ====
  750. #pragma --------------------------------------------------------------------------------------------
  751. - (void)getNotificationServerSuccess:(NSArray *)listOfNotifications
  752. {
  753. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  754. // Order by date
  755. NSArray *sortedListOfNotifications = [listOfNotifications sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
  756. OCNotifications *notification1 = obj1, *notification2 = obj2;
  757. return [notification2.date compare: notification1.date];
  758. }];
  759. // verify if listOfNotifications is changed
  760. NSString *old = @"", *new = @"";
  761. for (OCNotifications *notification in listOfNotifications)
  762. new = [new stringByAppendingString:@(notification.idNotification).stringValue];
  763. for (OCNotifications *notification in appDelegate.listOfNotifications)
  764. old = [old stringByAppendingString:@(notification.idNotification).stringValue];
  765. if (![new isEqualToString:old]) {
  766. appDelegate.listOfNotifications = [[NSMutableArray alloc] initWithArray:sortedListOfNotifications];
  767. // reload Notification view
  768. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"notificationReloadData" object:nil];
  769. }
  770. // Update NavigationBar
  771. if (!_isSelectedMode) {
  772. [self performSelectorOnMainThread:@selector(setUINavigationBarDefault) withObject:nil waitUntilDone:NO];
  773. }
  774. });
  775. }
  776. - (void)getNotificationServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  777. {
  778. NSString *error = [NSString stringWithFormat:@"Get Notification Server failure error %d, %@", (int)errorCode, message];
  779. NSLog(@"[LOG] %@", error);
  780. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionCapabilities selector:@"Get Notification Server" note:error type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:appDelegate.activeUrl];
  781. // Update NavigationBar
  782. if (!_isSelectedMode)
  783. [self setUINavigationBarDefault];
  784. }
  785. - (void)viewNotification
  786. {
  787. if ([appDelegate.listOfNotifications count] > 0) {
  788. CCNotification *notificationVC = [[UIStoryboard storyboardWithName:@"CCNotification" bundle:nil] instantiateViewControllerWithIdentifier:@"CCNotification"];
  789. [notificationVC setModalPresentationStyle:UIModalPresentationFormSheet];
  790. [self presentViewController:notificationVC animated:YES completion:nil];
  791. }
  792. }
  793. #pragma --------------------------------------------------------------------------------------------
  794. #pragma mark ==== User Profile ====
  795. #pragma --------------------------------------------------------------------------------------------
  796. - (void)getUserProfileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  797. {
  798. NSString *error = [NSString stringWithFormat:@"Get user profile failure error %d, %@", (int)errorCode, message];
  799. NSLog(@"[LOG] %@", error);
  800. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionCapabilities selector:@"Get user profile Server" note:error type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:appDelegate.activeUrl];
  801. }
  802. - (void)getUserProfileSuccess:(CCMetadataNet *)metadataNet userProfile:(OCUserProfile *)userProfile
  803. {
  804. // Update User (+ userProfile.id)
  805. [[NCManageDatabase sharedInstance] setAccountsUserProfile:userProfile];
  806. // Get Account Active
  807. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  808. // Setting appDelegate active account
  809. [appDelegate settingActiveAccount:account.account activeUrl:account.url activeUser:account.user activeUserID:account.userID activePassword:account.password];
  810. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  811. NSString *address = [NSString stringWithFormat:@"%@/index.php/avatar/%@/128", appDelegate.activeUrl, appDelegate.activeUser];
  812. //UIImage *avatar = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]]; DEPRECATED iOS9
  813. UIImage *avatar = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[address stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]]]];
  814. if (avatar)
  815. [UIImagePNGRepresentation(avatar) writeToFile:[NSString stringWithFormat:@"%@/avatar.png", appDelegate.directoryUser] atomically:YES];
  816. else
  817. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/avatar.png", appDelegate.directoryUser] error:nil];
  818. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"changeUserProfile" object:nil];
  819. });
  820. }
  821. #pragma --------------------------------------------------------------------------------------------
  822. #pragma mark ==== Capabilities ====
  823. #pragma --------------------------------------------------------------------------------------------
  824. - (void)getCapabilitiesOfServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  825. {
  826. // Unauthorized
  827. if (errorCode == kOCErrorServerUnauthorized)
  828. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  829. NSString *error = [NSString stringWithFormat:@"Get Capabilities failure error %d, %@", (int)errorCode, message];
  830. NSLog(@"[LOG] %@", error);
  831. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionCapabilities selector:@"Get Capabilities of Server" note:error type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:appDelegate.activeUrl];
  832. // Change Theming color
  833. [appDelegate settingThemingColorBrand];
  834. }
  835. - (void)getCapabilitiesOfServerSuccess:(OCCapabilities *)capabilities
  836. {
  837. // Update capabilities db
  838. [[NCManageDatabase sharedInstance] addCapabilities:capabilities];
  839. // ------ THEMING -----------------------------------------------------------------------
  840. // Download Theming Background & Change Theming color
  841. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  842. if ([NCBrandOptions sharedInstance].use_themingBackground == YES) {
  843. //UIImage *themingBackground = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[capabilities.themingBackground stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]]; DEPRECATED iOS9
  844. UIImage *themingBackground = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[capabilities.themingBackground stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]]]];
  845. if (themingBackground) {
  846. dispatch_async(dispatch_get_main_queue(), ^{
  847. [UIImagePNGRepresentation(themingBackground) writeToFile:[NSString stringWithFormat:@"%@/themingBackground.png", appDelegate.directoryUser] atomically:YES];
  848. });
  849. } else {
  850. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/themingBackground.png", appDelegate.directoryUser] error:nil];
  851. }
  852. }
  853. dispatch_async(dispatch_get_main_queue(), ^{
  854. [appDelegate settingThemingColorBrand];
  855. });
  856. });
  857. // ------ SEARCH ------------------------------------------------------------------------
  858. // Search bar if change version
  859. if ([[NCManageDatabase sharedInstance] getServerVersion] != capabilities.versionMajor) {
  860. [self cancelSearchBar];
  861. }
  862. // ------ GET SERVICE SERVER ------------------------------------------------------------
  863. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  864. // Read External Sites
  865. if (capabilities.isExternalSitesServerEnabled) {
  866. metadataNet.action = actionGetExternalSitesServer;
  867. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  868. }
  869. // Read Share
  870. if (capabilities.isFilesSharingAPIEnabled) {
  871. [appDelegate.sharesID removeAllObjects];
  872. metadataNet.action = actionReadShareServer;
  873. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  874. }
  875. // Read Notification
  876. metadataNet.action = actionGetNotificationServer;
  877. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  878. // Read User Profile
  879. metadataNet.action = actionGetUserProfile;
  880. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  881. // Read Activity
  882. metadataNet.action = actionGetActivityServer;
  883. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  884. }
  885. #pragma mark -
  886. #pragma --------------------------------------------------------------------------------------------
  887. #pragma mark ==== Request Server Information ====
  888. #pragma --------------------------------------------------------------------------------------------
  889. - (void)requestServerCapabilities
  890. {
  891. // test
  892. if (appDelegate.activeAccount.length == 0)
  893. return;
  894. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  895. metadataNet.action = actionGetCapabilities;
  896. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  897. }
  898. #pragma mark -
  899. #pragma --------------------------------------------------------------------------------------------
  900. #pragma mark ==== Middleware Ping ====
  901. #pragma --------------------------------------------------------------------------------------------
  902. - (void)middlewarePing
  903. {
  904. // test
  905. if (appDelegate.activeAccount.length == 0)
  906. return;
  907. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  908. metadataNet.action = actionMiddlewarePing;
  909. metadataNet.serverUrl = [[NCBrandOptions sharedInstance] middlewarePingUrl];
  910. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  911. }
  912. #pragma mark -
  913. #pragma --------------------------------------------------------------------------------------------
  914. #pragma mark ==== Download Thumbnail Delegate ====
  915. #pragma --------------------------------------------------------------------------------------------
  916. - (void)downloadThumbnailFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  917. {
  918. NSLog(@"[LOG] Download Thumbnail Failure error %d, %@", (int)errorCode, message);
  919. }
  920. - (void)downloadThumbnailSuccess:(CCMetadataNet *)metadataNet
  921. {
  922. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadataNet.fileID];
  923. if ([self indexPathIsValid:indexPath]) {
  924. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, metadataNet.fileID]])
  925. [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
  926. }
  927. }
  928. #pragma --------------------------------------------------------------------------------------------
  929. #pragma mark ==== Download ====
  930. #pragma --------------------------------------------------------------------------------------------
  931. - (void)downloadFileSuccessFailure:(NSString *)fileName fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost errorMessage:(NSString *)errorMessage errorCode:(NSInteger)errorCode
  932. {
  933. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  934. if (metadata == nil)
  935. return;
  936. if (errorCode == 0) {
  937. // Synchronized
  938. if ([selector isEqualToString:selectorDownloadSynchronize]) {
  939. [self reloadDatasource:serverUrl];
  940. }
  941. // add Favorite
  942. if ([selector isEqualToString:selectorAddFavorite]) {
  943. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  944. }
  945. // open View File
  946. if ([selector isEqualToString:selectorLoadFileView] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  947. [self reloadDatasource:serverUrl];
  948. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_compress]) {
  949. selector = selectorOpenIn;
  950. //[self performSelector:@selector(unZipFile:) withObject:metadata.fileID];
  951. } else if ([metadata.typeFile isEqualToString: k_metadataTypeFile_unknown]) {
  952. selector = selectorOpenIn;
  953. } else {
  954. _metadata = metadata;
  955. if ([self shouldPerformSegue])
  956. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  957. }
  958. }
  959. // Open with...
  960. if ([selector isEqualToString:selectorOpenIn] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  961. [self reloadDatasource:serverUrl];
  962. [[NSFileManager defaultManager] removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNameView] error:nil];
  963. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadata.fileID] toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNameView] error:nil];
  964. NSURL *url = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNameView]];
  965. _docController = [UIDocumentInteractionController interactionControllerWithURL:url];
  966. _docController.delegate = self;
  967. [_docController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  968. }
  969. // Save to Photo Album
  970. if ([selector isEqualToString:selectorSave] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  971. NSString *file = [NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadata.fileID];
  972. PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
  973. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] && status == PHAuthorizationStatusAuthorized) {
  974. UIImage *image = [UIImage imageWithContentsOfFile:file];
  975. if (image)
  976. UIImageWriteToSavedPhotosAlbum(image, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  977. else
  978. [appDelegate messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  979. }
  980. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video] && status == PHAuthorizationStatusAuthorized) {
  981. [[NSFileManager defaultManager] linkItemAtPath:file toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNameView] error:nil];
  982. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileNameView])) {
  983. UISaveVideoAtPathToSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileNameView], self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  984. } else {
  985. [appDelegate messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  986. }
  987. }
  988. if (status != PHAuthorizationStatusAuthorized) {
  989. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  990. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  991. [alertController addAction:okAction];
  992. [self presentViewController:alertController animated:YES completion:nil];
  993. }
  994. [self reloadDatasource:serverUrl];
  995. }
  996. // Copy File
  997. if ([selector isEqualToString:selectorLoadCopy]) {
  998. [self reloadDatasource:serverUrl];
  999. [self copyFileToPasteboard:metadata];
  1000. }
  1001. //selectorLoadViewImage
  1002. if ([selector isEqualToString:selectorLoadViewImage]) {
  1003. // Detail
  1004. if (appDelegate.activeDetail)
  1005. [appDelegate.activeDetail downloadPhotoBrowserSuccessFailure:metadata selector:selector errorCode:0];
  1006. // Photos
  1007. if (appDelegate.activePhotos)
  1008. [appDelegate.activePhotos downloadFileSuccessFailure:metadata.fileName fileID:metadata.fileID serverUrl:serverUrl selector:selector selectorPost:selectorPost errorMessage:errorMessage errorCode:errorCode];
  1009. [self reloadDatasource:serverUrl];
  1010. }
  1011. // if exists postselector call self with selectorPost
  1012. if ([selectorPost length] > 0)
  1013. [self downloadFileSuccessFailure:fileName fileID:fileID serverUrl:serverUrl selector:selectorPost selectorPost:nil errorMessage:@"" errorCode:0];
  1014. // Auto Download Upload
  1015. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1016. // ONLY BACKGROUND
  1017. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUploadBackground] waitUntilDone:NO];
  1018. } else {
  1019. // ONLY FOREFROUND
  1020. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUpload] waitUntilDone:NO];
  1021. }
  1022. } else {
  1023. // File do not exists on server, remove in local
  1024. if (errorCode == kOCErrorServerPathNotFound || errorCode == kCFURLErrorBadServerResponse) {
  1025. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, fileID] error:nil];
  1026. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, fileID] error:nil];
  1027. if (metadata.directory && serverUrl) {
  1028. NSString *dirForDelete = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName];
  1029. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:dirForDelete];
  1030. }
  1031. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID] clearDateReadDirectoryID:nil];
  1032. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1033. }
  1034. if ([selector isEqualToString:selectorLoadViewImage]) {
  1035. dispatch_async(dispatch_get_main_queue(), ^{
  1036. // Updating Detail
  1037. if (appDelegate.activeDetail)
  1038. [appDelegate.activeDetail downloadPhotoBrowserSuccessFailure:metadata selector:selector errorCode:errorCode];
  1039. // Updating Photos
  1040. if (appDelegate.activePhotos)
  1041. [appDelegate.activePhotos downloadFileSuccessFailure:metadata.fileName fileID:metadata.fileID serverUrl:serverUrl selector:selector selectorPost:selectorPost errorMessage:errorMessage errorCode:errorCode];
  1042. });
  1043. } else {
  1044. if (errorCode != kCFURLErrorCancelled && errorCode != kOCErrorServerUnauthorized && errorCode != k_CCErrorFileAlreadyInDownload)
  1045. [appDelegate messageNotification:@"_download_file_" description:errorMessage visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1046. }
  1047. [self reloadDatasource:serverUrl];
  1048. }
  1049. }
  1050. - (void)downloadSelectedFilesFolders
  1051. {
  1052. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1053. return;
  1054. NSLog(@"[LOG] Start download selected ...");
  1055. [_hud visibleHudTitle:NSLocalizedString(@"_downloading_progress_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1056. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1057. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1058. for (tableMetadata *metadata in selectedMetadatas) {
  1059. if (metadata.directory) {
  1060. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1061. if (serverUrl) {
  1062. serverUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName];
  1063. [[CCSynchronize sharedSynchronize] readFolder:serverUrl selector:selectorReadFolderWithDownload];
  1064. }
  1065. } else {
  1066. [[CCSynchronize sharedSynchronize] readFile:metadata selector:selectorReadFileWithDownload];
  1067. }
  1068. }
  1069. [_hud hideHud];
  1070. });
  1071. [self tableViewSelect:NO];
  1072. }
  1073. #pragma --------------------------------------------------------------------------------------------
  1074. #pragma mark ===== Upload new Photos/Videos =====
  1075. #pragma --------------------------------------------------------------------------------------------
  1076. - (void)uploadFileSuccessFailure:(NSString *)fileName fileID:(NSString *)fileID assetLocalIdentifier:(NSString *)assetLocalIdentifier serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost errorMessage:(NSString *)errorMessage errorCode:(NSInteger)errorCode
  1077. {
  1078. if (errorCode == 0) {
  1079. // Auto Download Upload
  1080. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1081. // ONLY BACKGROUND
  1082. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUploadBackground] waitUntilDone:NO];
  1083. } else {
  1084. // ONLY FOREFROUND
  1085. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUpload] waitUntilDone:NO];
  1086. }
  1087. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1088. if ([selectorPost isEqualToString:selectorReadFolderForced] ) {
  1089. [self readFolder:serverUrl];
  1090. } else {
  1091. [self reloadDatasource:serverUrl];
  1092. }
  1093. });
  1094. } else {
  1095. // Auto Download Upload
  1096. if([selector isEqualToString:selectorUploadAutoUpload] || [selector isEqualToString:selectorUploadAutoUploadAll] || [selector isEqualToString:selectorUploadFile]) {
  1097. // Delete record on Table Auto Upload
  1098. [[NCManageDatabase sharedInstance] deleteQueueUploadWithAssetLocalIdentifier:assetLocalIdentifier selector:selector];
  1099. // Activity
  1100. [[NCManageDatabase sharedInstance] addActivityClient:fileName fileID:assetLocalIdentifier action:k_activityDebugActionUpload selector:selector note:errorMessage type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:appDelegate.activeUrl];
  1101. if (errorCode != -999)
  1102. [appDelegate messageNotification:@"_upload_file_" description:errorMessage visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1103. } else {
  1104. // Read File test do not exists
  1105. if (errorCode == k_CCErrorFileUploadNotFound && fileID) {
  1106. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1107. // reUpload
  1108. if (metadata)
  1109. [[CCNetworking sharedNetworking] uploadFileMetadata:metadata taskStatus:k_taskStatusResume];
  1110. }
  1111. // Print error
  1112. else if (errorCode != kCFURLErrorCancelled && errorCode != kOCErrorServerUnauthorized) {
  1113. [appDelegate messageNotification:@"_upload_file_" description:errorMessage visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1114. }
  1115. }
  1116. [self reloadDatasource:serverUrl];
  1117. }
  1118. }
  1119. //
  1120. // This procedure with performSelectorOnMainThread it's necessary after (Bridge) for use the function "Sync" in OCNetworking
  1121. //
  1122. - (void)uploadFileAsset:(NSMutableArray *)assets serverUrl:(NSString *)serverUrl useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  1123. {
  1124. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
  1125. [self performSelectorOnMainThread:@selector(uploadFileAssetBridge:) withObject:@[assets, serverUrl, [NSNumber numberWithBool:useSubFolder], session] waitUntilDone:NO];
  1126. });
  1127. }
  1128. - (void)uploadFileAssetBridge:(NSArray *)arguments
  1129. {
  1130. NSArray *assets = [arguments objectAtIndex:0];
  1131. __block NSString *serverUrl = [arguments objectAtIndex:1];
  1132. BOOL useSubFolder = [[arguments objectAtIndex:2] boolValue];
  1133. NSString *session = [arguments objectAtIndex:3];
  1134. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:appDelegate.activeUrl];
  1135. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  1136. if (!directoryID) return;
  1137. // if request create the folder for Photos & the subfolders
  1138. if ([autoUploadPath isEqualToString:serverUrl])
  1139. if (![[NCAutoUpload sharedInstance] createFolderSubFolderAutoUploadFolderPhotos:autoUploadPath useSubFolder:useSubFolder assets:(PHFetchResult *)assets selector:selectorUploadFile])
  1140. return;
  1141. for (PHAsset *asset in assets) {
  1142. NSString *fileName = [CCUtility createFileName:[asset valueForKey:@"filename"] fileDate:asset.creationDate fileType:asset.mediaType keyFileName:k_keyFileNameMask keyFileNameType:k_keyFileNameType];
  1143. NSDate *assetDate = asset.creationDate;
  1144. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  1145. // Create serverUrl if use sub folder
  1146. if (useSubFolder) {
  1147. [formatter setDateFormat:@"yyyy"];
  1148. NSString *yearString = [formatter stringFromDate:assetDate];
  1149. [formatter setDateFormat:@"MM"];
  1150. NSString *monthString = [formatter stringFromDate:assetDate];
  1151. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", autoUploadPath, yearString, monthString];
  1152. }
  1153. // Check if is in upload
  1154. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileName = %@ AND session != ''", appDelegate.activeAccount, directoryID, fileName];
  1155. NSArray *isRecordInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1156. if ([isRecordInSessions count] > 0)
  1157. continue;
  1158. // Prepare record metadataNet
  1159. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1160. metadataNet.assetLocalIdentifier = asset.localIdentifier;
  1161. metadataNet.fileName = fileName;
  1162. metadataNet.session = session;
  1163. metadataNet.selector = selectorUploadFile;
  1164. metadataNet.selectorPost = nil;
  1165. metadataNet.serverUrl = serverUrl;
  1166. metadataNet.taskStatus = k_taskStatusResume;
  1167. // Check il file already exists
  1168. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileNameView = %@", appDelegate.activeAccount, directoryID, fileName]];
  1169. if (metadata) {
  1170. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:fileName message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1171. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  1172. // NO OVERWITE
  1173. }];
  1174. UIAlertAction *overwriteAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_overwrite_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  1175. // Send to Upload Queue
  1176. (void)[[NCManageDatabase sharedInstance] addQueueUploadWithMetadataNet:metadataNet];
  1177. }];
  1178. [alertController addAction:cancelAction];
  1179. [alertController addAction:overwriteAction];
  1180. UIWindow *alertWindow = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
  1181. alertWindow.rootViewController = [[UIViewController alloc]init];
  1182. alertWindow.windowLevel = UIWindowLevelAlert + 1;
  1183. [alertWindow makeKeyAndVisible];
  1184. [alertWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
  1185. } else {
  1186. // Send to Upload Queue
  1187. (void)[[NCManageDatabase sharedInstance] addQueueUploadWithMetadataNet:metadataNet];
  1188. }
  1189. }
  1190. }
  1191. #pragma --------------------------------------------------------------------------------------------
  1192. #pragma mark ==== Read File ====
  1193. #pragma --------------------------------------------------------------------------------------------
  1194. - (void)readFileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1195. {
  1196. // Unauthorized
  1197. if (errorCode == kOCErrorServerUnauthorized)
  1198. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  1199. }
  1200. - (void)readFileSuccess:(CCMetadataNet *)metadataNet metadata:(tableMetadata *)metadata
  1201. {
  1202. // Read Folder
  1203. if ([metadataNet.selector isEqualToString:selectorReadFileReloadFolder]) {
  1204. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", metadataNet.account, metadataNet.serverUrl]];
  1205. if ([metadata.etag isEqualToString:directory.etag] == NO) {
  1206. [self readFolder:metadataNet.serverUrl];
  1207. } else {
  1208. // E2E Is encrypted folder get metadata
  1209. if (_metadataFolder.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount])
  1210. [appDelegate.endToEndInterface getEndToEndMetadata:_metadataFolder.fileName fileID:_metadataFolder.fileID serverUrl:self.serverUrl];
  1211. }
  1212. }
  1213. }
  1214. - (void)readFileReloadFolder
  1215. {
  1216. if (!_serverUrl || !appDelegate.activeAccount || appDelegate.maintenanceMode)
  1217. return;
  1218. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1219. metadataNet.action = actionReadFile;
  1220. metadataNet.priority = NSOperationQueuePriorityHigh;
  1221. metadataNet.selector = selectorReadFileReloadFolder;
  1222. metadataNet.serverUrl = _serverUrl;
  1223. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1224. }
  1225. #pragma --------------------------------------------------------------------------------------------
  1226. #pragma mark ==== Read Folder ====
  1227. #pragma --------------------------------------------------------------------------------------------
  1228. - (void)readFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1229. {
  1230. // stoprefresh
  1231. [_refreshControl endRefreshing];
  1232. // Unauthorized
  1233. if (errorCode == kOCErrorServerUnauthorized)
  1234. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  1235. _loadingFolder = NO;
  1236. [self tableViewReloadData];
  1237. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1238. // verify active user
  1239. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1240. if (message && [record.account isEqualToString:metadataNet.account])
  1241. [appDelegate messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1242. [self reloadDatasource:metadataNet.serverUrl];
  1243. }
  1244. - (void)readFolderSuccess:(CCMetadataNet *)metadataNet metadataFolder:(tableMetadata *)metadataFolder metadatas:(NSArray *)metadatas
  1245. {
  1246. // stoprefresh
  1247. [_refreshControl endRefreshing];
  1248. // verify active user
  1249. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1250. if (![record.account isEqualToString:metadataNet.account])
  1251. return;
  1252. // save metadataFolder
  1253. _metadataFolder = metadataFolder;
  1254. // save father e update permission
  1255. if(!_isSearchMode && metadataFolder)
  1256. _fatherPermission = metadataFolder.permissions;
  1257. NSArray *recordsInSessions;
  1258. NSMutableArray *metadatasToInsertInDB = [NSMutableArray new];
  1259. if (_isSearchMode) {
  1260. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session != ''", metadataNet.account] sorted:nil ascending:NO];
  1261. } else {
  1262. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:metadataNet.serverUrl serverUrlTo:nil etag:metadataFolder.etag fileID:metadataFolder.fileID encrypted:metadataFolder.e2eEncrypted];
  1263. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session = ''", metadataNet.account, metadataNet.directoryID] clearDateReadDirectoryID:metadataNet.directoryID];
  1264. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session != ''", metadataNet.account, metadataNet.directoryID] sorted:nil ascending:NO];
  1265. [[NCManageDatabase sharedInstance] setDateReadDirectoryWithDirectoryID:metadataNet.directoryID];
  1266. }
  1267. for (tableMetadata *metadata in metadatas) {
  1268. // verify if the record is in download/upload progress
  1269. if (metadata.directory == NO && [recordsInSessions count] > 0) {
  1270. tableMetadata *metadataTransfer = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileName = %@", appDelegate.activeAccount, metadataNet.directoryID, metadata.fileName]];
  1271. // is in Download or Upload
  1272. if ([metadataTransfer.session containsString:@"upload"] || [metadataTransfer.session containsString:@"download"]) {
  1273. continue;
  1274. }
  1275. }
  1276. // Insert in Array
  1277. [metadatasToInsertInDB addObject:metadata];
  1278. }
  1279. // insert in Database
  1280. metadatasToInsertInDB = (NSMutableArray *)[[NCManageDatabase sharedInstance] addMetadatas:metadatasToInsertInDB serverUrl:metadataNet.serverUrl];
  1281. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1282. // File is changed ??
  1283. if (!_isSearchMode && metadatasToInsertInDB)
  1284. [[CCSynchronize sharedSynchronize] verifyChangeMedatas:metadatasToInsertInDB serverUrl:metadataNet.serverUrl account:appDelegate.activeAccount withDownload:NO];
  1285. });
  1286. // Search Mode
  1287. if (_isSearchMode) {
  1288. // Fix managed -> Unmanaged _searchResultMetadatas
  1289. if (metadatasToInsertInDB)
  1290. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatasToInsertInDB];
  1291. [self reloadDatasource:metadataNet.serverUrl];
  1292. }
  1293. // this is the same directory
  1294. if ([metadataNet.serverUrl isEqualToString:_serverUrl] && !_isSearchMode) {
  1295. // reload
  1296. [self reloadDatasource:metadataNet.serverUrl];
  1297. // Enable change user
  1298. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1299. _loadingFolder = NO;
  1300. [self tableViewReloadData];
  1301. }
  1302. // E2E Is encrypted folder get metadata
  1303. if (_metadataFolder.e2eEncrypted) {
  1304. // Read Metadata
  1305. if ([CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  1306. [appDelegate.endToEndInterface getEndToEndMetadata:_metadataFolder.fileName fileID:_metadataFolder.fileID serverUrl:self.serverUrl];
  1307. } else {
  1308. [appDelegate messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  1309. }
  1310. }
  1311. // rewrite title
  1312. [self setTitle];
  1313. }
  1314. - (void)readFolder:(NSString *)serverUrl
  1315. {
  1316. // init control
  1317. if (!serverUrl || !appDelegate.activeAccount || appDelegate.maintenanceMode) {
  1318. [_refreshControl endRefreshing];
  1319. return;
  1320. }
  1321. // Search Mode
  1322. if (_isSearchMode) {
  1323. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrl directoryID:nil];
  1324. _searchFileName = @""; // forced reload searchg
  1325. [self updateSearchResultsForSearchController:self.searchController];
  1326. return;
  1327. }
  1328. _loadingFolder = YES;
  1329. [self tableViewReloadData];
  1330. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, serverUrl]];
  1331. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1332. metadataNet.action = actionReadFolder;
  1333. metadataNet.date = [NSDate date];
  1334. metadataNet.depth = @"1";
  1335. metadataNet.directoryID = directory.directoryID;
  1336. metadataNet.priority = NSOperationQueuePriorityHigh;
  1337. metadataNet.selector = selectorReadFolder;
  1338. metadataNet.serverUrl = serverUrl;
  1339. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1340. }
  1341. #pragma mark -
  1342. #pragma --------------------------------------------------------------------------------------------
  1343. #pragma mark ===== Search =====
  1344. #pragma --------------------------------------------------------------------------------------------
  1345. - (void)searchEnabled:(BOOL)enabled
  1346. {
  1347. if (enabled) {
  1348. if (self.tableView.tableHeaderView != nil)
  1349. return;
  1350. self.definesPresentationContext = YES;
  1351. self.searchController.searchResultsUpdater = self;
  1352. self.searchController.dimsBackgroundDuringPresentation = NO;
  1353. self.searchController.searchBar.translucent = NO;
  1354. self.searchController.searchBar.barTintColor = [NCBrandColor sharedInstance].brand;
  1355. [self.searchController.searchBar sizeToFit];
  1356. self.searchController.searchBar.delegate = self;
  1357. self.searchController.searchBar.backgroundColor = [NCBrandColor sharedInstance].brand;
  1358. self.searchController.searchBar.backgroundImage = [UIImage new];
  1359. // Color Text "Cancel"
  1360. [[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTintColor:[NCBrandColor sharedInstance].brandText];
  1361. self.tableView.tableHeaderView = self.searchController.searchBar;
  1362. [self.tableView setContentOffset:CGPointMake(0, self.searchController.searchBar.frame.size.height - self.tableView.contentOffset.y)];
  1363. } else {
  1364. self.tableView.tableHeaderView = nil;
  1365. }
  1366. }
  1367. - (void)searchStartTimer
  1368. {
  1369. NSString *home = [CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl];
  1370. [[CCActions sharedInstance] search:home fileName:_searchFileName depth:@"infinity" date:nil selector:selectorSearch delegate:self];
  1371. _noFilesSearchTitle = @"";
  1372. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  1373. [self.tableView reloadEmptyDataSet];
  1374. }
  1375. - (void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1376. {
  1377. //[self setNeedsStatusBarAppearanceUpdate];
  1378. _isSearchMode = YES;
  1379. [self deleteRefreshControl];
  1380. NSString *fileName = [CCUtility removeForbiddenCharactersServer:searchController.searchBar.text];
  1381. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1382. _searchFileName = fileName;
  1383. // First : filter
  1384. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1385. if (!directoryID) return;
  1386. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"directoryID = %@ AND account = %@ AND fileNameView CONTAINS[cd] %@", directoryID, appDelegate.activeAccount, fileName];
  1387. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1388. [_searchResultMetadatas removeAllObjects];
  1389. for (tableMetadata *record in records)
  1390. [_searchResultMetadatas addObject:record];
  1391. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1392. metadataNet.account = appDelegate.activeAccount;
  1393. metadataNet.directoryID = directoryID;
  1394. metadataNet.selector = selectorSearch;
  1395. metadataNet.serverUrl = _serverUrl;
  1396. [self readFolderSuccess:metadataNet metadataFolder:nil metadatas:_searchResultMetadatas];
  1397. // Version >= 12
  1398. if ([[NCManageDatabase sharedInstance] getServerVersion] >= 12) {
  1399. [_timerWaitInput invalidate];
  1400. _timerWaitInput = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(searchStartTimer) userInfo:nil repeats:NO];
  1401. }
  1402. }
  1403. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1404. [self reloadDatasource];
  1405. }
  1406. }
  1407. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1408. {
  1409. [self cancelSearchBar];
  1410. [self readFolder:_serverUrl];
  1411. }
  1412. - (void)searchFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1413. {
  1414. // Unauthorized
  1415. if (errorCode == kOCErrorServerUnauthorized)
  1416. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  1417. if (message && errorCode != kOCErrorServerUnauthorized)
  1418. [appDelegate messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1419. _searchFileName = @"";
  1420. }
  1421. - (void)searchSuccess:(CCMetadataNet *)metadataNet metadatas:(NSArray *)metadatas
  1422. {
  1423. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatas];
  1424. [self readFolderSuccess:metadataNet metadataFolder:nil metadatas:metadatas];
  1425. }
  1426. - (void)cancelSearchBar
  1427. {
  1428. if (self.searchController.active) {
  1429. [self.searchController setActive:NO];
  1430. [self createRefreshControl];
  1431. _isSearchMode = NO;
  1432. _searchFileName = @"";
  1433. _dateReadDataSource = nil;
  1434. _searchResultMetadatas = [NSMutableArray new];
  1435. [self reloadDatasource];
  1436. }
  1437. //[self setNeedsStatusBarAppearanceUpdate];
  1438. }
  1439. #pragma mark -
  1440. #pragma --------------------------------------------------------------------------------------------
  1441. #pragma mark ===== Delete File or Folder =====
  1442. #pragma --------------------------------------------------------------------------------------------
  1443. - (void)deleteFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1444. {
  1445. // Unauthorized
  1446. if (errorCode == kOCErrorServerUnauthorized)
  1447. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  1448. NSLog(@"[LOG] Delete File failure error %d, %@", (int)errorCode, message);
  1449. [self deleteFileOrFolderSuccess:metadataNet];
  1450. }
  1451. - (void)deleteFileOrFolderSuccess:(CCMetadataNet *)metadataNet
  1452. {
  1453. [_queueSelector removeObject:metadataNet.selector];
  1454. if ([_queueSelector count] == 0) {
  1455. [_hud hideHud];
  1456. // next
  1457. [_selectedFileIDsMetadatas removeObjectForKey:metadataNet.fileID];
  1458. if ([_selectedFileIDsMetadatas count] > 0) {
  1459. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1460. [self deleteFileOrFolder:[metadatas objectAtIndex:0] numFile:[_selectedFileIDsMetadatas count] ofFile:_numSelectedFileIDsMetadatas];
  1461. } else {
  1462. // E2E
  1463. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1464. [[CCNetworking sharedNetworking] rebuildAndSendEndToEndMetadataOnServerUrl:self.serverUrl];
  1465. });
  1466. // End Select Table View
  1467. [self tableViewSelect:NO];
  1468. // Reload
  1469. if (_isSearchMode)
  1470. [self readFolder:metadataNet.serverUrl];
  1471. else
  1472. [self reloadDatasource:metadataNet.serverUrl];
  1473. }
  1474. }
  1475. }
  1476. - (void)deleteFileOrFolder:(tableMetadata *)metadata numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  1477. {
  1478. [_queueSelector addObject:selectorDelete];
  1479. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self];
  1480. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1481. }
  1482. - (void)deleteFile
  1483. {
  1484. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1485. return;
  1486. [_queueSelector removeAllObjects];
  1487. if ([_selectedFileIDsMetadatas count] > 0) {
  1488. _numSelectedFileIDsMetadatas = [_selectedFileIDsMetadatas count];
  1489. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1490. [self deleteFileOrFolder:[metadatas objectAtIndex:0] numFile:[_selectedFileIDsMetadatas count] ofFile:_numSelectedFileIDsMetadatas];
  1491. } else {
  1492. _numSelectedFileIDsMetadatas = 1;
  1493. [self deleteFileOrFolder:_metadata numFile:1 ofFile:_numSelectedFileIDsMetadatas];
  1494. }
  1495. }
  1496. #pragma --------------------------------------------------------------------------------------------
  1497. #pragma mark ===== Rename / Move =====
  1498. #pragma --------------------------------------------------------------------------------------------
  1499. - (void)renameSuccess:(CCMetadataNet *)metadataNet
  1500. {
  1501. [self readFolder:metadataNet.serverUrl];
  1502. }
  1503. - (void)renameFile:(NSArray *)arguments
  1504. {
  1505. tableMetadata* metadata = [arguments objectAtIndex:0];
  1506. NSString *fileName = [arguments objectAtIndex:1];
  1507. // E2E
  1508. if ([CCUtility isFolderEncrypted:self.serverUrl account:appDelegate.activeAccount]) {
  1509. // verify if exists the new fileName
  1510. if ([[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@ AND fileName = %@", appDelegate.activeAccount, self.serverUrl, fileName]]) {
  1511. [appDelegate messageNotification:@"_error_" description:@"_file_already_exists_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1512. return;
  1513. }
  1514. if ([[NCManageDatabase sharedInstance] renameFileE2eEncryptionWithServerUrl:self.serverUrl fileNameIdentifier:metadata.fileName newFileName:fileName newFileNamePath:[CCUtility returnFileNamePathFromFileName:fileName serverUrl:self.serverUrl activeUrl:appDelegate.activeUrl]]) {
  1515. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  1516. NSError *error = [[CCNetworking sharedNetworking] SendEndToEndMetadataOnServerUrl:self.serverUrl];
  1517. if (error == nil) {
  1518. dispatch_async(dispatch_get_main_queue(), ^{
  1519. [[NCManageDatabase sharedInstance] setMetadataFileNameViewWithDirectoryID:metadata.directoryID fileName:metadata.fileName newFileNameView:fileName];
  1520. [self reloadDatasource];
  1521. });
  1522. } else {
  1523. // Restore previuos fileName on DB
  1524. (void)[[NCManageDatabase sharedInstance] renameFileE2eEncryptionWithServerUrl:self.serverUrl fileNameIdentifier:metadata.fileName newFileName:metadata.fileNameView newFileNamePath:[CCUtility returnFileNamePathFromFileName:metadata.fileNameView serverUrl:self.serverUrl activeUrl:appDelegate.activeUrl]];
  1525. [appDelegate messageNotification:@"_error_" description:[NSString stringWithFormat:@"Error to send metadata %d", (int)error.code] visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1526. }
  1527. });
  1528. } else {
  1529. [appDelegate messageNotification:@"_error_" description:@"Error file not found" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1530. }
  1531. } else {
  1532. // Plain
  1533. [[CCActions sharedInstance] renameFileOrFolder:metadata fileName:fileName delegate:self];
  1534. }
  1535. }
  1536. - (void)renameMoveFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1537. {
  1538. if ([metadataNet.selector isEqualToString:selectorMove]) {
  1539. [_hud hideHud];
  1540. if (message && errorCode != kOCErrorServerUnauthorized)
  1541. [appDelegate messageNotification:@"_move_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1542. // End Select Table View
  1543. [self tableViewSelect:NO];
  1544. // reload Datasource
  1545. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1546. [self readFolder:metadataNet.serverUrl];
  1547. else
  1548. [self reloadDatasource];
  1549. }
  1550. }
  1551. - (void)moveSuccess:(CCMetadataNet *)metadataNet
  1552. {
  1553. [_queueSelector removeObject:metadataNet.selector];
  1554. if ([_queueSelector count] == 0) {
  1555. [_hud hideHud];
  1556. NSString *fileName = metadataNet.fileName;
  1557. NSString *directoryID = metadataNet.directoryID;
  1558. NSString *directoryIDTo = metadataNet.directoryIDTo;
  1559. NSString *serverUrlTo = [[NCManageDatabase sharedInstance] getServerUrl:directoryIDTo];
  1560. if (!serverUrlTo) return;
  1561. // FILE -> Metadata
  1562. if (metadataNet.directory == NO)
  1563. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1564. // DIRECTORY -> Directory - CCMetadata
  1565. if (metadataNet.directory == YES) {
  1566. // delete all dir / subdir
  1567. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:[CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:fileName]];
  1568. // move metadata
  1569. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1570. // Add new directory
  1571. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrlTo, fileName];
  1572. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:newDirectory permissions:nil encrypted:false];
  1573. }
  1574. // next
  1575. [_selectedFileIDsMetadatas removeObjectForKey:metadataNet.fileID];
  1576. if ([_selectedFileIDsMetadatas count] > 0) {
  1577. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1578. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrlTo, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1579. } else {
  1580. // End Select Table View
  1581. [self tableViewSelect:NO];
  1582. // reload Datasource
  1583. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1584. [self readFolder:metadataNet.serverUrl];
  1585. else
  1586. [self reloadDatasource];
  1587. }
  1588. }
  1589. }
  1590. - (void)moveFileOrFolderMetadata:(NSArray *)arguments
  1591. {
  1592. tableMetadata *metadata = [arguments objectAtIndex:0];
  1593. NSString *serverUrlTo = [arguments objectAtIndex:1];
  1594. NSInteger numFile = [[arguments objectAtIndex:2] integerValue];
  1595. NSInteger ofFile = [[arguments objectAtIndex:3] integerValue];
  1596. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1597. if (!serverUrl) return;
  1598. NSString *directoryIDTo = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrlTo];
  1599. if (!directoryIDTo) return;
  1600. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  1601. NSArray *items;
  1602. NSError *error = [[NCNetworkingSync sharedManager] readFile:[NSString stringWithFormat:@"%@/%@", serverUrlTo, metadata.fileName] user:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword items:&items];
  1603. if(!error) {
  1604. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1605. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1606. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1607. }];
  1608. [alert addAction:ok];
  1609. [self presentViewController:alert animated:YES completion:nil];
  1610. // End Select Table View
  1611. [self tableViewSelect:NO];
  1612. // reload Datasource
  1613. [self readFileReloadFolder];
  1614. });
  1615. return;
  1616. }
  1617. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1618. metadataNet.action = actionMoveFileOrFolder;
  1619. metadataNet.directory = metadata.directory;
  1620. metadataNet.fileID = metadata.fileID;
  1621. metadataNet.directoryID = metadata.directoryID;
  1622. metadataNet.directoryIDTo = directoryIDTo;
  1623. metadataNet.fileName = metadata.fileName;
  1624. metadataNet.fileNameView = metadata.fileNameView;
  1625. metadataNet.fileNameTo = metadata.fileName;
  1626. metadataNet.etag = metadata.etag;
  1627. metadataNet.selector = selectorMove;
  1628. metadataNet.serverUrl = serverUrl;
  1629. metadataNet.serverUrlTo = serverUrlTo;
  1630. [_queueSelector addObject:metadataNet.selector];
  1631. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1632. dispatch_async(dispatch_get_main_queue(), ^{
  1633. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_move_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1634. });
  1635. });
  1636. }
  1637. // DELEGATE : Move
  1638. - (void)dismissMove
  1639. {
  1640. [self reloadDatasource];
  1641. }
  1642. // DELEGATE : Move
  1643. - (void)moveServerUrlTo:(NSString *)serverUrlTo title:(NSString *)title
  1644. {
  1645. [_queueSelector removeAllObjects];
  1646. // E2E DENIED
  1647. if ([CCUtility isFolderEncrypted:serverUrlTo account:appDelegate.activeAccount]) {
  1648. [appDelegate messageNotification:@"_move_" description:@"Not possible move files to encrypted directory" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  1649. return;
  1650. }
  1651. if ([_selectedFileIDsMetadatas count] > 0) {
  1652. _numSelectedFileIDsMetadatas = [_selectedFileIDsMetadatas count];
  1653. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1654. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrlTo, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1655. } else {
  1656. _numSelectedFileIDsMetadatas = 1;
  1657. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[_metadata, serverUrlTo, [NSNumber numberWithInteger:1], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1658. }
  1659. }
  1660. - (void)moveOpenWindow:(NSArray *)indexPaths
  1661. {
  1662. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1663. return;
  1664. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"CCMove" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMove"];
  1665. CCMove *viewController = (CCMove *)navigationController.topViewController;
  1666. viewController.delegate = self;
  1667. viewController.move.title = NSLocalizedString(@"_move_", nil);
  1668. viewController.tintColor = [NCBrandColor sharedInstance].brandText;
  1669. viewController.barTintColor = [NCBrandColor sharedInstance].brand;
  1670. viewController.tintColorTitle = [NCBrandColor sharedInstance].brandText;
  1671. viewController.networkingOperationQueue = appDelegate.netQueue;
  1672. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  1673. [self presentViewController:navigationController animated:YES completion:nil];
  1674. }
  1675. #pragma --------------------------------------------------------------------------------------------
  1676. #pragma mark ===== Create folder =====
  1677. #pragma --------------------------------------------------------------------------------------------
  1678. - (void)createFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1679. {
  1680. // Unauthorized
  1681. if (errorCode == kOCErrorServerUnauthorized)
  1682. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  1683. if (message && errorCode != kOCErrorServerUnauthorized)
  1684. [appDelegate messageNotification:@"_create_folder_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1685. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID] clearDateReadDirectoryID:nil];
  1686. [self reloadDatasource];
  1687. // We are in directory fail ?
  1688. CCMain *vc = [appDelegate.listMainVC objectForKey:[CCUtility stringAppendServerUrl:_serverUrl addFileName:metadataNet.fileName]];
  1689. if (vc)
  1690. [vc.navigationController popViewControllerAnimated:YES];
  1691. }
  1692. - (void)createFolderSuccess:(CCMetadataNet *)metadataNet
  1693. {
  1694. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", metadataNet.serverUrl, metadataNet.fileName];
  1695. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:newDirectory permissions:nil encrypted:false];
  1696. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileName = %@ AND directoryID = %@", metadataNet.fileName, metadataNet.directoryID]];
  1697. if (metadata) {
  1698. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileName = %@ AND directoryID = %@", metadataNet.fileName, metadataNet.directoryID] clearDateReadDirectoryID:nil];
  1699. metadata.fileID = metadataNet.fileID;
  1700. metadata.date = metadataNet.date;
  1701. metadata.permissions = @"RDNVCK";
  1702. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1703. [self reloadDatasource];
  1704. } else {
  1705. [self readFileReloadFolder];
  1706. }
  1707. }
  1708. - (void)createFolder:(NSString *)fileNameFolder serverUrl:(NSString *)serverUrl
  1709. {
  1710. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1711. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1712. if (![fileNameFolder length]) return;
  1713. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1714. if (!directoryID) return;
  1715. metadataNet.action = actionCreateFolder;
  1716. metadataNet.directoryID = directoryID;
  1717. metadataNet.fileID = [[NSUUID UUID] UUIDString];
  1718. metadataNet.fileName = fileNameFolder;
  1719. metadataNet.selector = selectorCreateFolder;
  1720. metadataNet.serverUrl = serverUrl;
  1721. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1722. // Create Directory on metadata
  1723. tableMetadata *metadata = [CCUtility createMetadataWithAccount:appDelegate.activeAccount date:[NSDate date] directory:YES fileID:metadataNet.fileID directoryID:metadataNet.directoryID fileName:metadataNet.fileName etag:@"" size:0 status:k_metadataStatusNormal];
  1724. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1725. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:_serverUrl directoryID:nil];
  1726. [self reloadDatasource];
  1727. }
  1728. #pragma --------------------------------------------------------------------------------------------
  1729. #pragma mark ===== Progress & Task Button =====
  1730. #pragma --------------------------------------------------------------------------------------------
  1731. - (void)triggerProgressTask:(NSNotification *)notification
  1732. {
  1733. NSDictionary *dict = notification.userInfo;
  1734. NSString *fileID = [dict valueForKey:@"fileID"];
  1735. NSString *serverUrl = [dict valueForKey:@"serverUrl"];
  1736. float progress = [[dict valueForKey:@"progress"] floatValue];
  1737. // Check
  1738. if (!fileID || [fileID isEqualToString: @""])
  1739. return;
  1740. [appDelegate.listProgressMetadata setObject:[NSNumber numberWithFloat:progress] forKey:fileID];
  1741. if (![serverUrl isEqualToString:_serverUrl])
  1742. return;
  1743. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:fileID];
  1744. if ([self indexPathIsValid:indexPath]) {
  1745. CCTransfersCell *cell = (CCTransfersCell *)[self.tableView cellForRowAtIndexPath:indexPath];
  1746. cell.progressView.progressTintColor = [UIColor blackColor];
  1747. cell.progressView.hidden = NO;
  1748. [cell.progressView setProgress:progress];
  1749. }
  1750. }
  1751. - (void)reloadTaskButton:(id)sender withEvent:(UIEvent *)event
  1752. {
  1753. UITouch * touch = [[event allTouches] anyObject];
  1754. CGPoint location = [touch locationInView:self.tableView];
  1755. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1756. if ([self indexPathIsValid:indexPath]) {
  1757. tableMetadata *metadataSection = [self getMetadataFromSectionDataSource:indexPath];
  1758. if (metadataSection) {
  1759. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataSection.fileID]];
  1760. if (metadata)
  1761. [self reloadTaskButton:metadata];
  1762. }
  1763. }
  1764. }
  1765. - (void)reloadTaskButton:(tableMetadata *)metadata
  1766. {
  1767. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1768. __block NSURLSessionTask *findTask;
  1769. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1770. NSString *fileID = metadata.fileID;
  1771. // DOWNLOAD
  1772. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  1773. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1774. for (NSURLSessionUploadTask *task in downloadTasks)
  1775. if (task.taskIdentifier == sessionTaskIdentifier) {
  1776. findTask = task;
  1777. [appDelegate.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  1778. [task cancel];
  1779. }
  1780. if (!findTask) {
  1781. [appDelegate.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  1782. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1783. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1784. }
  1785. }];
  1786. }
  1787. // UPLOAD
  1788. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1789. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1790. for (NSURLSessionUploadTask *task in uploadTasks)
  1791. if (task.taskIdentifier == sessionTaskIdentifier) {
  1792. findTask = task;
  1793. [appDelegate.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  1794. [task cancel];
  1795. }
  1796. if (!findTask) {
  1797. [appDelegate.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  1798. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1799. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1800. }
  1801. }];
  1802. }
  1803. }
  1804. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  1805. {
  1806. UITouch * touch = [[event allTouches] anyObject];
  1807. CGPoint location = [touch locationInView:self.tableView];
  1808. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1809. if ([self indexPathIsValid:indexPath]) {
  1810. tableMetadata *metadataSection = [self getMetadataFromSectionDataSource:indexPath];
  1811. if (metadataSection) {
  1812. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataSection.fileID]];
  1813. if (metadata)
  1814. [self cancelTaskButton:metadata reloadTable:YES];
  1815. }
  1816. }
  1817. }
  1818. - (void)cancelTaskButton:(tableMetadata *)metadata reloadTable:(BOOL)reloadTable
  1819. {
  1820. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1821. __block NSURLSessionTask *findTask;
  1822. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1823. NSString *fileID = metadata.fileID;
  1824. // DOWNLOAD
  1825. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  1826. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1827. for (NSURLSessionTask *task in downloadTasks)
  1828. if (task.taskIdentifier == sessionTaskIdentifier) {
  1829. findTask = task;
  1830. [appDelegate.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  1831. [task cancel];
  1832. }
  1833. if (!findTask) {
  1834. [appDelegate.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  1835. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1836. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1837. }
  1838. }];
  1839. }
  1840. // UPLOAD
  1841. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1842. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1843. for (NSURLSessionUploadTask *task in uploadTasks)
  1844. if (task.taskIdentifier == sessionTaskIdentifier) {
  1845. findTask = task;
  1846. [appDelegate.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  1847. [task cancel];
  1848. }
  1849. if (!findTask) {
  1850. [appDelegate.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  1851. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1852. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1853. }
  1854. }];
  1855. }
  1856. }
  1857. - (void)stopTaskButton:(id)sender withEvent:(UIEvent *)event
  1858. {
  1859. UITouch * touch = [[event allTouches] anyObject];
  1860. CGPoint location = [touch locationInView:self.tableView];
  1861. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1862. if ([self indexPathIsValid:indexPath]) {
  1863. tableMetadata *metadataSection = [self getMetadataFromSectionDataSource:indexPath];
  1864. if (metadataSection) {
  1865. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataSection.fileID]];
  1866. if (metadata)
  1867. [self stopTaskButton:metadata];
  1868. }
  1869. }
  1870. }
  1871. - (void)stopTaskButton:(tableMetadata *)metadata
  1872. {
  1873. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1874. __block NSURLSessionTask *findTask;
  1875. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1876. NSString *fileID = metadata.fileID;
  1877. // UPLOAD
  1878. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1879. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1880. for (NSURLSessionUploadTask *task in uploadTasks)
  1881. if (task.taskIdentifier == sessionTaskIdentifier) {
  1882. [appDelegate.listChangeTask setObject:@"stopUpload" forKey:fileID];
  1883. findTask = task;
  1884. [task cancel];
  1885. }
  1886. if (!findTask) {
  1887. [appDelegate.listChangeTask setObject:@"stopUpload" forKey:fileID];
  1888. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1889. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1890. }
  1891. }];
  1892. }
  1893. }
  1894. #pragma --------------------------------------------------------------------------------------------
  1895. #pragma mark ===== Shared =====
  1896. #pragma --------------------------------------------------------------------------------------------
  1897. - (void)readSharedSuccess:(CCMetadataNet *)metadataNet items:(NSDictionary *)items openWindow:(BOOL)openWindow
  1898. {
  1899. [_hud hideHud];
  1900. // change account ?
  1901. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1902. if([record.account isEqualToString:metadataNet.account] == NO)
  1903. return;
  1904. NSArray *result = [[NCManageDatabase sharedInstance] updateShare:items activeUrl:appDelegate.activeUrl];
  1905. if (result) {
  1906. appDelegate.sharesLink = result[0];
  1907. appDelegate.sharesUserAndGroup = result[1];
  1908. }
  1909. // Notify Shares View
  1910. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"SharesReloadDatasource" object:nil userInfo:nil];
  1911. if (openWindow) {
  1912. if (_shareOC) {
  1913. [_shareOC reloadData];
  1914. } else {
  1915. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  1916. // Apriamo la view
  1917. _shareOC = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareOC"];
  1918. _shareOC.delegate = self;
  1919. _shareOC.metadata = metadata;
  1920. _shareOC.serverUrl = metadataNet.serverUrl;
  1921. _shareOC.shareLink = [appDelegate.sharesLink objectForKey:metadata.fileID];
  1922. _shareOC.shareUserAndGroup = [appDelegate.sharesUserAndGroup objectForKey:metadata.fileID];
  1923. [_shareOC setModalPresentationStyle:UIModalPresentationFormSheet];
  1924. [self presentViewController:_shareOC animated:YES completion:nil];
  1925. }
  1926. }
  1927. [self tableViewReloadData];
  1928. }
  1929. - (void)shareFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1930. {
  1931. [_hud hideHud];
  1932. // Unauthorized
  1933. if (errorCode == kOCErrorServerUnauthorized)
  1934. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  1935. if (errorCode != kOCErrorServerUnauthorized)
  1936. [appDelegate messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1937. if (_shareOC)
  1938. [_shareOC reloadData];
  1939. [self tableViewReloadData];
  1940. }
  1941. - (void)share:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password
  1942. {
  1943. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1944. metadataNet.action = actionShare;
  1945. metadataNet.fileID = metadata.fileID;
  1946. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:appDelegate.activeUrl];
  1947. metadataNet.fileNameView = metadata.fileNameView;
  1948. metadataNet.password = password;
  1949. metadataNet.selector = selectorShare;
  1950. metadataNet.serverUrl = serverUrl;
  1951. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1952. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1953. }
  1954. - (void)unShareSuccess:(CCMetadataNet *)metadataNet
  1955. {
  1956. [_hud hideHud];
  1957. // rimuoviamo la condivisione da db
  1958. NSArray *result = [[NCManageDatabase sharedInstance] unShare:metadataNet.share fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl sharesLink:appDelegate.sharesLink sharesUserAndGroup:appDelegate.sharesUserAndGroup];
  1959. if (result) {
  1960. appDelegate.sharesLink = result[0];
  1961. appDelegate.sharesUserAndGroup = result[1];
  1962. }
  1963. if (_shareOC)
  1964. [_shareOC reloadData];
  1965. [self tableViewReloadData];
  1966. }
  1967. - (void)unShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl
  1968. {
  1969. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1970. metadataNet.action = actionUnShare;
  1971. metadataNet.fileID = metadata.fileID;
  1972. metadataNet.fileName = metadata.fileName;
  1973. metadataNet.fileNameView = metadata.fileNameView;
  1974. metadataNet.selector = selectorUnshare;
  1975. metadataNet.serverUrl = serverUrl;
  1976. metadataNet.share = share;
  1977. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1978. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1979. }
  1980. - (void)updateShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password expirationTime:(NSString *)expirationTime permission:(NSInteger)permission
  1981. {
  1982. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1983. metadataNet.action = actionUpdateShare;
  1984. metadataNet.fileID = metadata.fileID;
  1985. metadataNet.expirationTime = expirationTime;
  1986. metadataNet.password = password;
  1987. metadataNet.selector = selectorUpdateShare;
  1988. metadataNet.serverUrl = serverUrl;
  1989. metadataNet.share = share;
  1990. metadataNet.sharePermission = permission;
  1991. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1992. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1993. }
  1994. - (void)getUserAndGroupSuccess:(CCMetadataNet *)metadataNet items:(NSArray *)items
  1995. {
  1996. [_hud hideHud];
  1997. if (_shareOC)
  1998. [_shareOC reloadUserAndGroup:items];
  1999. }
  2000. - (void)getUserAndGroupFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2001. {
  2002. [_hud hideHud];
  2003. // Unauthorized
  2004. if (errorCode == kOCErrorServerUnauthorized)
  2005. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  2006. if (errorCode != kOCErrorServerUnauthorized)
  2007. [appDelegate messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  2008. }
  2009. - (void)getUserAndGroup:(NSString *)find
  2010. {
  2011. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  2012. metadataNet.action = actionGetUserAndGroup;
  2013. metadataNet.options = find;
  2014. metadataNet.selector = selectorGetUserAndGroup;
  2015. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  2016. [_hud visibleIndeterminateHud];
  2017. }
  2018. - (void)shareUserAndGroup:(NSString *)user shareeType:(NSInteger)shareeType permission:(NSInteger)permission metadata:(tableMetadata *)metadata directoryID:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  2019. {
  2020. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  2021. metadataNet.action = actionShareWith;
  2022. metadataNet.fileID = metadata.fileID;
  2023. metadataNet.directoryID = directoryID;
  2024. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:appDelegate.activeUrl];
  2025. metadataNet.fileNameView = metadata.fileNameView;
  2026. metadataNet.serverUrl = serverUrl;
  2027. metadataNet.selector = selectorShare;
  2028. metadataNet.share = user;
  2029. metadataNet.shareeType = shareeType;
  2030. metadataNet.sharePermission = permission;
  2031. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  2032. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2033. }
  2034. - (void)openWindowShare:(tableMetadata *)metadata
  2035. {
  2036. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2037. if (!serverUrl) return;
  2038. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  2039. metadataNet.action = actionReadShareServer;
  2040. metadataNet.fileID = metadata.fileID;
  2041. metadataNet.fileName = metadata.fileName;
  2042. metadataNet.fileNameView = metadata.fileNameView;
  2043. metadataNet.selector = selectorOpenWindowShare;
  2044. metadataNet.serverUrl = serverUrl;
  2045. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  2046. [_hud visibleIndeterminateHud];
  2047. }
  2048. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  2049. {
  2050. CGPoint location = [tapGesture locationInView:self.tableView];
  2051. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  2052. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2053. if (metadata)
  2054. [self openWindowShare:metadata];
  2055. }
  2056. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  2057. {
  2058. CGPoint location = [tapGesture locationInView:self.tableView];
  2059. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  2060. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2061. if (metadata) {
  2062. CCShareInfoCMOC *vc = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareInfoCMOC"];
  2063. vc.metadata = metadata;
  2064. [vc setModalPresentationStyle:UIModalPresentationFormSheet];
  2065. [self presentViewController:vc animated:YES completion:nil];
  2066. }
  2067. }
  2068. #pragma --------------------------------------------------------------------------------------------
  2069. #pragma mark ===== Favorite =====
  2070. #pragma --------------------------------------------------------------------------------------------
  2071. - (void)settingFavoriteSuccess:(CCMetadataNet *)metadataNet
  2072. {
  2073. _dateReadDataSource = nil;
  2074. [[NCManageDatabase sharedInstance] setMetadataFavoriteWithFileID:metadataNet.fileID favorite:[metadataNet.options boolValue]];
  2075. if (_isSearchMode)
  2076. [self readFolder:metadataNet.serverUrl];
  2077. else
  2078. [self reloadDatasource:metadataNet.serverUrl];
  2079. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  2080. if (metadata.directory && metadata.favorite) {
  2081. NSString *dir = [CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:metadata.fileName];
  2082. [appDelegate.activeFavorites addFavoriteFolder:dir];
  2083. }
  2084. }
  2085. - (void)settingFavoriteFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2086. {
  2087. // Unauthorized
  2088. if (errorCode == kOCErrorServerUnauthorized)
  2089. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  2090. NSLog(@"[LOG] Setting Favorite failure error %d, %@", (int)errorCode, message);
  2091. }
  2092. - (void)addFavorite:(tableMetadata *)metadata
  2093. {
  2094. if (metadata.directory) {
  2095. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  2096. } else {
  2097. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2098. if (serverUrl)
  2099. [[CCNetworking sharedNetworking] downloadFile:metadata.fileName fileID:metadata.fileID serverUrl:serverUrl selector:selectorAddFavorite selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2100. }
  2101. }
  2102. - (void)removeFavorite:(tableMetadata *)metadata
  2103. {
  2104. [[CCActions sharedInstance] settingFavorite:metadata favorite:NO delegate:self];
  2105. }
  2106. #pragma --------------------------------------------------------------------------------------------
  2107. #pragma mark ===== E2E Encryption =====
  2108. #pragma --------------------------------------------------------------------------------------------
  2109. - (void)unlockEndToEndFolderEncryptedSuccess:(CCMetadataNet *)metadataNet
  2110. {
  2111. [[NCManageDatabase sharedInstance] setDirectoryE2ETokenLockWithFileID:metadataNet.fileID token:@""];
  2112. [appDelegate messageNotification:@"_success_" description:@"_e2e_remove_folder_lock_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:0];
  2113. }
  2114. - (void)unlockEndToEndFolderEncryptedFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2115. {
  2116. if (errorCode == 404)
  2117. [[NCManageDatabase sharedInstance] setDirectoryE2ETokenLockWithFileID:metadataNet.fileID token:@""];
  2118. [appDelegate messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  2119. }
  2120. #pragma --------------------------------------------------------------------------------------------
  2121. #pragma mark ===== Open in... =====
  2122. #pragma --------------------------------------------------------------------------------------------
  2123. - (void)openIn:(tableMetadata *)metadata
  2124. {
  2125. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2126. if (!serverUrl) return;
  2127. [[CCNetworking sharedNetworking] downloadFile:metadata.fileName fileID:metadata.fileID serverUrl:serverUrl selector:selectorOpenIn selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2128. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2129. if ([self indexPathIsValid:indexPath])
  2130. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2131. }
  2132. #pragma --------------------------------------------------------------------------------------------
  2133. #pragma mark ===== Remove Local File =====
  2134. #pragma --------------------------------------------------------------------------------------------
  2135. - (void)removeLocalFile:(tableMetadata *)metadata
  2136. {
  2137. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2138. if (!serverUrl) return;
  2139. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  2140. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadata.fileID] error:nil];
  2141. [self reloadDatasource:serverUrl];
  2142. }
  2143. #pragma --------------------------------------------------------------------------------------------
  2144. #pragma mark ===== Order Table & GroupBy & DirectoryOnTop =====
  2145. #pragma --------------------------------------------------------------------------------------------
  2146. - (void)orderTable:(NSString *)order
  2147. {
  2148. [CCUtility setOrderSettings:order];
  2149. // Clear data-read of DataSource
  2150. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2151. }
  2152. - (void)ascendingTable:(BOOL)ascending
  2153. {
  2154. [CCUtility setAscendingSettings:ascending];
  2155. // Clear data-read of DataSource
  2156. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2157. }
  2158. - (void)directoryOnTop:(BOOL)directoryOnTop
  2159. {
  2160. [CCUtility setDirectoryOnTop:directoryOnTop];
  2161. // Clear data-read of DataSource
  2162. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2163. }
  2164. - (void)tableGroupBy:(NSString *)groupBy
  2165. {
  2166. [CCUtility setGroupBySettings:groupBy];
  2167. // Clear data-read of DataSource
  2168. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2169. }
  2170. #pragma --------------------------------------------------------------------------------------------
  2171. #pragma mark ==== Menu LOGO ====
  2172. #pragma --------------------------------------------------------------------------------------------
  2173. - (void)menuLogo:(UIGestureRecognizer *)theGestureRecognizer
  2174. {
  2175. if (appDelegate.reSelectMenu.isOpen || appDelegate.reMainMenu.isOpen)
  2176. return;
  2177. // Brand
  2178. if ([NCBrandOptions sharedInstance].disable_multiaccount)
  2179. return;
  2180. NSUInteger numInSession = [[[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session != ''", appDelegate.activeAccount] sorted:nil ascending:NO] count];
  2181. NSUInteger numInQueue = [appDelegate.netQueue operationCount];
  2182. if (numInSession+numInQueue > 0) {
  2183. [JDStatusBarNotification showWithStatus:NSLocalizedString(@"_transfers_in_queue_", nil) dismissAfter:k_dismissAfterSecond styleName:JDStatusBarStyleDefault];
  2184. return;
  2185. }
  2186. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  2187. NSMutableArray *menuArray = [NSMutableArray new];
  2188. for (NSString *account in listAccount) {
  2189. if ([account isEqualToString:appDelegate.activeAccount]) continue;
  2190. CCMenuItem *item = [[CCMenuItem alloc] init];
  2191. item.title = [account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  2192. item.argument = account;
  2193. item.image = [UIImage imageNamed:@"menuLogoUser"];
  2194. item.target = self;
  2195. item.action = @selector(changeDefaultAccount:);
  2196. [menuArray addObject:item];
  2197. }
  2198. if ([menuArray count] == 0)
  2199. return;
  2200. OptionalConfiguration options;
  2201. Color textColor, backgroundColor;
  2202. textColor.R = 0;
  2203. textColor.G = 0;
  2204. textColor.B = 0;
  2205. backgroundColor.R = 1;
  2206. backgroundColor.G = 1;
  2207. backgroundColor.B = 1;
  2208. options.arrowSize = 9;
  2209. options.marginXSpacing = 7;
  2210. options.marginYSpacing = 10;
  2211. options.intervalSpacing = 20;
  2212. options.menuCornerRadius = 6.5;
  2213. options.maskToBackground = NO;
  2214. options.shadowOfMenu = YES;
  2215. options.hasSeperatorLine = YES;
  2216. options.seperatorLineHasInsets = YES;
  2217. options.textColor = textColor;
  2218. options.menuBackgroundColor = backgroundColor;
  2219. CGRect rect = self.view.frame;
  2220. CGFloat locationY = [theGestureRecognizer locationInView: self.navigationController.navigationBar].y;
  2221. CGFloat safeAreaTop = 0;
  2222. CGFloat offsetY = 35;
  2223. if (@available(iOS 11, *)) {
  2224. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top / 2;
  2225. }
  2226. rect.origin.y = locationY + safeAreaTop + offsetY;
  2227. rect.size.height = rect.size.height - locationY - safeAreaTop - offsetY;
  2228. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  2229. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  2230. }
  2231. - (void)changeDefaultAccount:(CCMenuItem *)sender
  2232. {
  2233. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  2234. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2235. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:[sender argument]];
  2236. if (tableAccount) {
  2237. [appDelegate settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activeUserID:tableAccount.userID activePassword:tableAccount.password];
  2238. // go to home sweet home
  2239. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initializeMain" object:nil];
  2240. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  2241. }
  2242. });
  2243. }
  2244. #pragma --------------------------------------------------------------------------------------------
  2245. #pragma mark ==== ReMenu ====
  2246. #pragma --------------------------------------------------------------------------------------------
  2247. - (void)createReMenuBackgroundView:(REMenu *)menu
  2248. {
  2249. CGFloat safeAreaBottom = 0;
  2250. CGFloat safeAreaTop = 0;
  2251. CGFloat statusBar = 0;
  2252. if (@available(iOS 11, *)) {
  2253. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top;
  2254. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  2255. }
  2256. if ([UIApplication sharedApplication].isStatusBarHidden) {
  2257. statusBar = 13;
  2258. }
  2259. CGFloat computeNavigationBarOffset = [menu computeNavigationBarOffset];
  2260. UIViewController *rootController = [[[[UIApplication sharedApplication]delegate] window] rootViewController];
  2261. CGRect globalPositionMenu = [menu.menuView convertRect:menu.menuView.bounds toView:rootController.view];
  2262. _reMenuBackgroundView.frame = CGRectMake(0, computeNavigationBarOffset, globalPositionMenu.size.width, rootController.view.frame.size.height);
  2263. [UIView animateWithDuration:0.2 animations:^{
  2264. CGFloat minimum = safeAreaBottom + self.tabBarController.tabBar.frame.size.height;
  2265. CGFloat y = rootController.view.frame.size.height - menu.menuView.frame.size.height - globalPositionMenu.origin.y + statusBar;
  2266. if (y>minimum) {
  2267. _reMenuBackgroundView.frame = CGRectMake(0, rootController.view.frame.size.height, globalPositionMenu.size.width, - y);
  2268. [self.tabBarController.view addSubview:_reMenuBackgroundView];
  2269. }
  2270. }];
  2271. }
  2272. - (void)createReMainMenu
  2273. {
  2274. NSString *ordinamento;
  2275. NSString *groupBy = _directoryGroupBy;
  2276. __block NSString *nuovoOrdinamento;
  2277. NSString *titoloNuovo, *titoloAttuale;
  2278. BOOL ascendente;
  2279. __block BOOL nuovoAscendente;
  2280. UIImage *image;
  2281. // ITEM SELECT ----------------------------------------------------------------------------------------------------
  2282. appDelegate.selezionaItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_", nil)subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"seleziona"] color:[NCBrandColor sharedInstance].brandElement] highlightedImage:nil action:^(REMenuItem *item) {
  2283. if ([_sectionDataSource.allRecordsDataSource count] > 0) {
  2284. [self tableViewSelect:YES];
  2285. }
  2286. }];
  2287. // ITEM ORDER ----------------------------------------------------------------------------------------------------
  2288. ordinamento = _directoryOrder;
  2289. if ([ordinamento isEqualToString:@"fileName"]) {
  2290. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdeyByDate"] color:[NCBrandColor sharedInstance].brandElement];
  2291. titoloNuovo = NSLocalizedString(@"_order_by_date_", nil);
  2292. titoloAttuale = NSLocalizedString(@"_current_order_name_", nil);
  2293. nuovoOrdinamento = @"date";
  2294. }
  2295. if ([ordinamento isEqualToString:@"date"]) {
  2296. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrderByFileName"] color:[NCBrandColor sharedInstance].brandElement];
  2297. titoloNuovo = NSLocalizedString(@"_order_by_name_", nil);
  2298. titoloAttuale = NSLocalizedString(@"_current_order_date_", nil);
  2299. nuovoOrdinamento = @"fileName";
  2300. }
  2301. appDelegate.ordinaItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2302. [self orderTable:nuovoOrdinamento];
  2303. }];
  2304. // ITEM ASCENDING -----------------------------------------------------------------------------------------------------
  2305. ascendente = [CCUtility getAscendingSettings];
  2306. if (ascendente) {
  2307. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoDiscendente"] color:[NCBrandColor sharedInstance].brandElement];
  2308. titoloNuovo = NSLocalizedString(@"_sort_descending_", nil);
  2309. titoloAttuale = NSLocalizedString(@"_current_sort_ascending_", nil);
  2310. nuovoAscendente = false;
  2311. }
  2312. if (!ascendente) {
  2313. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoAscendente"] color:[NCBrandColor sharedInstance].brandElement];
  2314. titoloNuovo = NSLocalizedString(@"_sort_ascending_", nil);
  2315. titoloAttuale = NSLocalizedString(@"_current_sort_descending_", nil);
  2316. nuovoAscendente = true;
  2317. }
  2318. appDelegate.ascendenteItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2319. [self ascendingTable:nuovoAscendente];
  2320. }];
  2321. // ITEM ALPHABETIC -----------------------------------------------------------------------------------------------------
  2322. if ([groupBy isEqualToString:@"alphabetic"]) { titoloNuovo = NSLocalizedString(@"_group_alphabetic_yes_", nil); }
  2323. else { titoloNuovo = NSLocalizedString(@"_group_alphabetic_no_", nil); }
  2324. appDelegate.alphabeticItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByAlphabetic"] color:[NCBrandColor sharedInstance].brandElement] highlightedImage:nil action:^(REMenuItem *item) {
  2325. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  2326. else [self tableGroupBy:@"alphabetic"];
  2327. }];
  2328. // ITEM TYPEFILE -------------------------------------------------------------------------------------------------------
  2329. if ([groupBy isEqualToString:@"typefile"]) { titoloNuovo = NSLocalizedString(@"_group_typefile_yes_", nil); }
  2330. else { titoloNuovo = NSLocalizedString(@"_group_typefile_no_", nil); }
  2331. appDelegate.typefileItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByTypeFile"] color:[NCBrandColor sharedInstance].brandElement] highlightedImage:nil action:^(REMenuItem *item) {
  2332. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  2333. else [self tableGroupBy:@"typefile"];
  2334. }];
  2335. // ITEM DATE -------------------------------------------------------------------------------------------------------
  2336. if ([groupBy isEqualToString:@"date"]) { titoloNuovo = NSLocalizedString(@"_group_date_yes_", nil); }
  2337. else { titoloNuovo = NSLocalizedString(@"_group_date_no_", nil); }
  2338. appDelegate.dateItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByDate"] color:[NCBrandColor sharedInstance].brandElement] highlightedImage:nil action:^(REMenuItem *item) {
  2339. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  2340. else [self tableGroupBy:@"date"];
  2341. }];
  2342. // ITEM DIRECTORY ON TOP ------------------------------------------------------------------------------------------------
  2343. if ([CCUtility getDirectoryOnTop]) { titoloNuovo = NSLocalizedString(@"_directory_on_top_yes_", nil); }
  2344. else { titoloNuovo = NSLocalizedString(@"_directory_on_top_no_", nil); }
  2345. appDelegate.directoryOnTopItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"menuDirectoryOnTop"] color:[NCBrandColor sharedInstance].brandElement] highlightedImage:nil action:^(REMenuItem *item) {
  2346. if ([CCUtility getDirectoryOnTop])
  2347. [self directoryOnTop:NO];
  2348. else
  2349. [self directoryOnTop:YES];
  2350. }];
  2351. // REMENU --------------------------------------------------------------------------------------------------------------
  2352. appDelegate.reMainMenu = [[REMenu alloc] initWithItems:@[appDelegate.selezionaItem, appDelegate.ordinaItem, appDelegate.ascendenteItem, appDelegate.alphabeticItem, appDelegate.typefileItem, appDelegate.dateItem, appDelegate.directoryOnTopItem]];
  2353. appDelegate.reMainMenu.imageOffset = CGSizeMake(5, -1);
  2354. appDelegate.reMainMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2355. appDelegate.reMainMenu.imageOffset = CGSizeMake(0, 0);
  2356. appDelegate.reMainMenu.waitUntilAnimationIsComplete = NO;
  2357. appDelegate.reMainMenu.separatorHeight = 0.5;
  2358. appDelegate.reMainMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2359. appDelegate.reMainMenu.backgroundColor = [NCBrandColor sharedInstance].backgroundView;
  2360. appDelegate.reMainMenu.textColor = [UIColor blackColor];
  2361. appDelegate.reMainMenu.textAlignment = NSTextAlignmentLeft;
  2362. appDelegate.reMainMenu.textShadowColor = nil;
  2363. appDelegate.reMainMenu.textOffset = CGSizeMake(50, 0.0);
  2364. appDelegate.reMainMenu.font = [UIFont systemFontOfSize:14.0];
  2365. appDelegate.reMainMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2366. appDelegate.reMainMenu.highlightedSeparatorColor = nil;
  2367. appDelegate.reMainMenu.highlightedTextColor = [UIColor blackColor];
  2368. appDelegate.reMainMenu.highlightedTextShadowColor = nil;
  2369. appDelegate.reMainMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2370. appDelegate.reMainMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  2371. appDelegate.reMainMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2372. appDelegate.reMainMenu.subtitleTextShadowColor = nil;
  2373. appDelegate.reMainMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2374. appDelegate.reMainMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2375. appDelegate.reMainMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2376. appDelegate.reMainMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2377. appDelegate.reMainMenu.subtitleHighlightedTextShadowColor = nil;
  2378. appDelegate.reMainMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2379. appDelegate.reMainMenu.borderWidth = 0.3;
  2380. appDelegate.reMainMenu.borderColor = [UIColor lightGrayColor];
  2381. appDelegate.reMainMenu.animationDuration = 0.2;
  2382. appDelegate.reMainMenu.closeAnimationDuration = 0.2;
  2383. appDelegate.reMainMenu.bounce = NO;
  2384. [appDelegate.reMainMenu setClosePreparationBlock:^{
  2385. // Backgroun reMenu (Gesture)
  2386. [_reMenuBackgroundView removeFromSuperview];
  2387. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2388. }];
  2389. }
  2390. - (void)toggleReMainMenu
  2391. {
  2392. if (appDelegate.reMainMenu.isOpen) {
  2393. [appDelegate.reMainMenu close];
  2394. } else {
  2395. [self createReMainMenu];
  2396. [appDelegate.reMainMenu showFromNavigationController:self.navigationController];
  2397. // Backgroun reMenu & (Gesture)
  2398. [self createReMenuBackgroundView:appDelegate.reMainMenu];
  2399. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReMainMenu)];
  2400. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2401. }
  2402. }
  2403. - (void)createReSelectMenu
  2404. {
  2405. // ITEM DELETE ------------------------------------------------------------------------------------------------------
  2406. appDelegate.deleteItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_delete_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"deleteSelectedFiles"] color:[NCBrandColor sharedInstance].brandElement] highlightedImage:nil action:^(REMenuItem *item) {
  2407. [self deleteFile];
  2408. }];
  2409. // ITEM MOVE ------------------------------------------------------------------------------------------------------
  2410. appDelegate.moveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_move_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"moveSelectedFiles"] color:[NCBrandColor sharedInstance].brandElement] highlightedImage:nil action:^(REMenuItem *item) {
  2411. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2412. }];
  2413. // ITEM DOWNLOAD ----------------------------------------------------------------------------------------------------
  2414. appDelegate.downloadItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_download_selected_files_folders_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"downloadSelectedFiles"] color:[NCBrandColor sharedInstance].brandElement] highlightedImage:nil action:^(REMenuItem *item) {
  2415. [self downloadSelectedFilesFolders];
  2416. }];
  2417. // ITEM SAVE IMAGE & VIDEO -------------------------------------------------------------------------------------------
  2418. appDelegate.saveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_save_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"saveSelectedFiles"] color:[NCBrandColor sharedInstance].brandElement] highlightedImage:nil action:^(REMenuItem *item) {
  2419. [self saveSelectedFiles];
  2420. }];
  2421. appDelegate.reSelectMenu = [[REMenu alloc] initWithItems:@[appDelegate.deleteItem,appDelegate.moveItem, appDelegate.downloadItem, appDelegate.saveItem]];
  2422. appDelegate.reSelectMenu.imageOffset = CGSizeMake(5, -1);
  2423. appDelegate.reSelectMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2424. appDelegate.reSelectMenu.imageOffset = CGSizeMake(0, 0);
  2425. appDelegate.reSelectMenu.waitUntilAnimationIsComplete = NO;
  2426. appDelegate.reSelectMenu.separatorHeight = 0.5;
  2427. appDelegate.reSelectMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2428. appDelegate.reSelectMenu.backgroundColor = [NCBrandColor sharedInstance].backgroundView;
  2429. appDelegate.reSelectMenu.textColor = [UIColor blackColor];
  2430. appDelegate.reSelectMenu.textAlignment = NSTextAlignmentLeft;
  2431. appDelegate.reSelectMenu.textShadowColor = nil;
  2432. appDelegate.reSelectMenu.textOffset = CGSizeMake(50, 0.0);
  2433. appDelegate.reSelectMenu.font = [UIFont systemFontOfSize:14.0];
  2434. appDelegate.reSelectMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2435. appDelegate.reSelectMenu.highlightedSeparatorColor = nil;
  2436. appDelegate.reSelectMenu.highlightedTextColor = [UIColor blackColor];
  2437. appDelegate.reSelectMenu.highlightedTextShadowColor = nil;
  2438. appDelegate.reSelectMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2439. appDelegate.reSelectMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1.000];
  2440. appDelegate.reSelectMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2441. appDelegate.reSelectMenu.subtitleTextShadowColor = nil;
  2442. appDelegate.reSelectMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2443. appDelegate.reSelectMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2444. appDelegate.reSelectMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2445. appDelegate.reSelectMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2446. appDelegate.reSelectMenu.subtitleHighlightedTextShadowColor = nil;
  2447. appDelegate.reSelectMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2448. appDelegate.reSelectMenu.borderWidth = 0.3;
  2449. appDelegate.reSelectMenu.borderColor = [UIColor lightGrayColor];
  2450. appDelegate.reSelectMenu.closeAnimationDuration = 0.2;
  2451. appDelegate.reSelectMenu.animationDuration = 0.2;
  2452. appDelegate.reSelectMenu.bounce = NO;
  2453. [appDelegate.reSelectMenu setClosePreparationBlock:^{
  2454. // Backgroun reMenu (Gesture)
  2455. [_reMenuBackgroundView removeFromSuperview];
  2456. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2457. }];
  2458. }
  2459. - (void)toggleReSelectMenu
  2460. {
  2461. if (appDelegate.reSelectMenu.isOpen) {
  2462. [appDelegate.reSelectMenu close];
  2463. } else {
  2464. [self createReSelectMenu];
  2465. [appDelegate.reSelectMenu showFromNavigationController:self.navigationController];
  2466. // Backgroun reMenu & (Gesture)
  2467. [self createReMenuBackgroundView:appDelegate.reSelectMenu];
  2468. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReSelectMenu)];
  2469. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2470. }
  2471. }
  2472. #pragma --------------------------------------------------------------------------------------------
  2473. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  2474. #pragma --------------------------------------------------------------------------------------------
  2475. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  2476. {
  2477. if (recognizer.state == UIGestureRecognizerStateBegan) {
  2478. UITableView *tableView = (UITableView*)self.view;
  2479. CGPoint touchPoint = [recognizer locationInView:self.view];
  2480. NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:touchPoint];
  2481. if ([self indexPathIsValid:indexPath])
  2482. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2483. else
  2484. _metadata = nil;
  2485. [self becomeFirstResponder];
  2486. UIMenuController *menuController = [UIMenuController sharedMenuController];
  2487. UIMenuItem *copyFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)];
  2488. UIMenuItem *copyFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)];
  2489. UIMenuItem *openinFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)];
  2490. UIMenuItem *pasteFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)];
  2491. UIMenuItem *pasteFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)];
  2492. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, nil]];
  2493. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:tableView];
  2494. [menuController setMenuVisible:YES animated:YES];
  2495. }
  2496. }
  2497. - (BOOL)canBecomeFirstResponder
  2498. {
  2499. return YES;
  2500. }
  2501. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  2502. {
  2503. // For copy file, copy files, Open in ... :
  2504. //
  2505. // NO Directory
  2506. // NO Error Passcode
  2507. // NO In Session mode (download/upload)
  2508. // NO Template
  2509. if (@selector(copyFile:) == action || @selector(openinFile:) == action) {
  2510. if (_isSelectedMode == NO && _metadata && !_metadata.directory && [_metadata.session length] == 0) return YES;
  2511. else return NO;
  2512. }
  2513. if (@selector(copyFiles:) == action) {
  2514. if (_isSelectedMode) {
  2515. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2516. for (tableMetadata *metadata in selectedMetadatas) {
  2517. if (!metadata.directory && metadata.session.length == 0)
  2518. return YES;
  2519. }
  2520. }
  2521. return NO;
  2522. }
  2523. if (@selector(pasteFile:) == action) {
  2524. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2525. NSArray *items = [pasteboard items];
  2526. if ([items count] == 1) {
  2527. // Value : (NSData) fileID
  2528. NSDictionary *dic = [items objectAtIndex:0];
  2529. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2530. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2531. if (fileID) {
  2532. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2533. if (metadata) {
  2534. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", metadata.account]];
  2535. if (account) {
  2536. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2537. if (directoryUser)
  2538. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]])
  2539. return YES;
  2540. }
  2541. }
  2542. }
  2543. }
  2544. return NO;
  2545. }
  2546. if (@selector(pasteFiles:) == action) {
  2547. BOOL isValid = NO;
  2548. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2549. NSArray *items = [pasteboard items];
  2550. if ([items count] <= 1) return NO;
  2551. for (NSDictionary *dic in items) {
  2552. // Value : (NSData) fileID
  2553. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2554. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2555. if (fileID) {
  2556. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2557. if (metadata) {
  2558. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", metadata.account]];
  2559. if (account) {
  2560. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2561. if (directoryUser) {
  2562. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]]) {
  2563. isValid = YES;
  2564. } else {
  2565. isValid = NO;
  2566. break;
  2567. }
  2568. } else {
  2569. isValid = NO;
  2570. break;
  2571. }
  2572. } else {
  2573. isValid = NO;
  2574. break;
  2575. }
  2576. } else {
  2577. isValid = NO;
  2578. break;
  2579. }
  2580. } else {
  2581. isValid = NO;
  2582. break;
  2583. }
  2584. }
  2585. return isValid;
  2586. }
  2587. return NO;
  2588. }
  2589. /************************************ COPY ************************************/
  2590. - (void)copyFile:(id)sender
  2591. {
  2592. // Remove all item
  2593. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2594. pasteboard.items = [[NSArray alloc] init];
  2595. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser,_metadata.fileID]]) {
  2596. [self copyFileToPasteboard:_metadata];
  2597. } else {
  2598. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2599. if (serverUrl)
  2600. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileName fileID:_metadata.fileID serverUrl:serverUrl selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2601. }
  2602. }
  2603. - (void)copyFiles:(id)sender
  2604. {
  2605. // Remove all item
  2606. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2607. pasteboard.items = [[NSArray alloc] init];
  2608. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2609. for (tableMetadata *metadata in selectedMetadatas) {
  2610. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadata.fileID]]) {
  2611. [self copyFileToPasteboard:metadata];
  2612. } else {
  2613. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2614. if (serverUrl)
  2615. [[CCNetworking sharedNetworking] downloadFile:metadata.fileName fileID:metadata.fileID serverUrl:serverUrl selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2616. }
  2617. }
  2618. [self tableViewSelect:NO];
  2619. }
  2620. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  2621. {
  2622. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2623. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  2624. // Value : (NSData) fileID
  2625. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata.fileID], k_metadataKeyedUnarchiver,nil];
  2626. [items addObject:item];
  2627. [pasteboard setItems:items];
  2628. }
  2629. /************************************ OPEN IN ... ******************************/
  2630. - (void)openinFile:(id)sender
  2631. {
  2632. [self openIn:_metadata];
  2633. }
  2634. /************************************ PASTE ************************************/
  2635. - (void)pasteFile:(id)sender
  2636. {
  2637. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2638. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2639. }
  2640. - (void)pasteFiles:(id)sender
  2641. {
  2642. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2643. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2644. }
  2645. - (void)uploadFilePasteArray:(NSArray *)items cryptated:(BOOL)cryptated
  2646. {
  2647. float timer = 0;
  2648. for (NSDictionary *dic in items) {
  2649. // Value : (NSData) fileID
  2650. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2651. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2652. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2653. if (metadata) {
  2654. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", metadata.account]];
  2655. if (account) {
  2656. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2657. if (directoryUser) {
  2658. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]]) {
  2659. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadata.fileNameView]];
  2660. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timer * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2661. [[CCNetworking sharedNetworking] uploadFile:metadata.fileNameView serverUrl:_serverUrl session:k_upload_session taskStatus:k_taskStatusResume selector:@"" selectorPost:@"" errorCode:0 delegate:nil];
  2662. });
  2663. timer += 0.1;
  2664. }
  2665. }
  2666. }
  2667. }
  2668. }
  2669. }
  2670. #pragma --------------------------------------------------------------------------------------------
  2671. #pragma mark ===== Lock Passcode =====
  2672. #pragma --------------------------------------------------------------------------------------------
  2673. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  2674. {
  2675. return _failedAttempts;
  2676. }
  2677. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  2678. {
  2679. return _lockUntilDate;
  2680. }
  2681. - (void)passcodeViewCloseButtonPressed:(id)sender
  2682. {
  2683. [self dismissViewControllerAnimated:YES completion:nil];
  2684. }
  2685. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  2686. {
  2687. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  2688. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  2689. _lockUntilDate = nil;
  2690. _failedAttempts = 0;
  2691. aResultHandler(YES);
  2692. } else aResultHandler(NO);
  2693. } else aResultHandler(YES);
  2694. }
  2695. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  2696. {
  2697. [aViewController dismissViewControllerAnimated:YES completion:nil];
  2698. switch (aViewController.type) {
  2699. case BKPasscodeViewControllerCheckPasscodeType: {
  2700. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  2701. // possiamo procedere alla prossima directory
  2702. [self performSegueDirectoryWithControlPasscode:false];
  2703. // avviamo la sessione Passcode Lock con now
  2704. appDelegate.sessionePasscodeLock = [NSDate date];
  2705. }
  2706. // disattivazione lock cartella
  2707. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  2708. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2709. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2710. if (![[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:NO]) {
  2711. [appDelegate messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2712. }
  2713. [self tableViewReloadData];
  2714. }
  2715. }
  2716. break;
  2717. default:
  2718. break;
  2719. }
  2720. }
  2721. - (void)comandoLockPassword
  2722. {
  2723. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2724. if (!serverUrl) return;
  2725. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2726. // se non è abilitato il Lock Passcode esci
  2727. if ([[CCUtility getBlockCode] length] == 0) {
  2728. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) preferredStyle:UIAlertControllerStyleAlert];
  2729. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  2730. [alertController addAction:okAction];
  2731. [self presentViewController:alertController animated:YES completion:nil];
  2732. return;
  2733. }
  2734. // se è richiesta la disattivazione si chiede la password
  2735. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, lockServerUrl]];
  2736. if (directory.lock) {
  2737. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2738. viewController.delegate = self;
  2739. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  2740. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2741. viewController.inputViewTitlePassword = YES;
  2742. if ([CCUtility getSimplyBlockCode]) {
  2743. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2744. viewController.passcodeInputView.maximumLength = 6;
  2745. } else {
  2746. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2747. viewController.passcodeInputView.maximumLength = 64;
  2748. }
  2749. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  2750. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2751. viewController.touchIDManager = touchIDManager;
  2752. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  2753. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2754. viewController.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
  2755. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2756. [self presentViewController:navigationController animated:YES completion:nil];
  2757. return;
  2758. }
  2759. // ---------------- ACTIVATE PASSWORD
  2760. if ([[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:YES]) {
  2761. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  2762. if ([self indexPathIsValid:indexPath])
  2763. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2764. } else {
  2765. [appDelegate messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2766. }
  2767. }
  2768. #pragma mark -
  2769. #pragma --------------------------------------------------------------------------------------------
  2770. #pragma mark ===== Swipe Tablet -> menu =====
  2771. #pragma --------------------------------------------------------------------------------------------
  2772. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell canSwipe:(MGSwipeDirection)direction
  2773. {
  2774. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2775. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2776. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  2777. return NO;
  2778. if (metadata == nil || metadata.sessionTaskIdentifier != k_taskIdentifierDone)
  2779. return NO;
  2780. else
  2781. return YES;
  2782. }
  2783. -(void)swipeTableCell:(nonnull MGSwipeTableCell *)cell didChangeSwipeState:(MGSwipeState)state gestureIsActive:(BOOL)gestureIsActive
  2784. {
  2785. }
  2786. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell tappedButtonAtIndex:(NSInteger)index direction:(MGSwipeDirection)direction fromExpansion:(BOOL)fromExpansion
  2787. {
  2788. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2789. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2790. if (direction == MGSwipeDirectionRightToLeft) {
  2791. // Delete
  2792. if (index == 0)
  2793. [self swipeDelete:indexPath];
  2794. // More
  2795. if (index == 1)
  2796. [self swipeMore:indexPath];
  2797. }
  2798. if (direction == MGSwipeDirectionLeftToRight) {
  2799. if (_metadata.favorite)
  2800. [self removeFavorite:_metadata];
  2801. else
  2802. [self addFavorite:_metadata];
  2803. }
  2804. return YES;
  2805. }
  2806. - (void)swipeDelete:(NSIndexPath *)indexPath
  2807. {
  2808. // Directory locked ?
  2809. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:[[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID] addFileName:_metadata.fileName];
  2810. if (!lockServerUrl) return;
  2811. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, lockServerUrl]];
  2812. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil) {
  2813. [appDelegate messageNotification:@"_error_" description:@"_folder_blocked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2814. return;
  2815. }
  2816. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  2817. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  2818. [self performSelector:@selector(deleteFile) withObject:nil];
  2819. }]];
  2820. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2821. [alertController dismissViewControllerAnimated:YES completion:nil];
  2822. }]];
  2823. alertController.popoverPresentationController.sourceView = self.view;
  2824. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  2825. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  2826. [alertController.view layoutIfNeeded];
  2827. [self presentViewController:alertController animated:YES completion:nil];
  2828. }
  2829. - (void)swipeMore:(NSIndexPath *)indexPath
  2830. {
  2831. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2832. if (!serverUrl) return;
  2833. NSString *titoloLock, *titleFavorite;
  2834. if (_metadata.favorite) {
  2835. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_remove_favorites_", nil)];
  2836. } else {
  2837. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_add_favorites_", nil)];
  2838. }
  2839. if (_metadata.directory) {
  2840. // calcolo lockServerUrl
  2841. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2842. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, lockServerUrl]];
  2843. if (directory.lock)
  2844. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_remove_passcode_", nil)];
  2845. else
  2846. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_protect_passcode_", nil)];
  2847. }
  2848. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", _metadata.fileID]];
  2849. // ******************************************* AHKActionSheet *******************************************
  2850. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.tabBarController.view title:nil];
  2851. actionSheet.animationDuration = 0.2;
  2852. actionSheet.buttonHeight = 50.0;
  2853. actionSheet.cancelButtonHeight = 50.0f;
  2854. actionSheet.separatorHeight = 5.0f;
  2855. actionSheet.automaticallyTintButtonImages = @(NO);
  2856. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].encrypted };
  2857. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  2858. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont boldSystemFontOfSize:17], NSForegroundColorAttributeName:[UIColor blackColor] };
  2859. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor darkGrayColor] };
  2860. actionSheet.separatorColor = [NCBrandColor sharedInstance].seperator;
  2861. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  2862. // ******************************************* DIRECTORY *******************************************
  2863. if (_metadata.directory) {
  2864. BOOL lockDirectory = NO;
  2865. NSString *dirServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2866. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:[NSString stringWithFormat:@"%@/%@", self.serverUrl, _metadata.fileName] account:appDelegate.activeAccount];
  2867. // Directory bloccata ?
  2868. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, dirServerUrl]];
  2869. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil) lockDirectory = YES;
  2870. [actionSheet addButtonWithTitle:_metadata.fileNameView
  2871. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder"] color:[NCBrandColor sharedInstance].brandElement]
  2872. backgroundColor:[NCBrandColor sharedInstance].tabBar
  2873. height:50.0
  2874. type:AHKActionSheetButtonTypeDisabled
  2875. handler:nil
  2876. ];
  2877. if (!lockDirectory && !isFolderEncrypted) {
  2878. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  2879. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brandElement]
  2880. backgroundColor:[UIColor whiteColor]
  2881. height:50.0
  2882. type:AHKActionSheetButtonTypeDefault
  2883. handler:^(AHKActionSheet *as) {
  2884. [self openWindowShare:_metadata];
  2885. }];
  2886. }
  2887. if (!([_metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES) && !lockDirectory && !_metadata.e2eEncrypted) {
  2888. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  2889. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brandElement]
  2890. backgroundColor:[UIColor whiteColor]
  2891. height:50.0
  2892. type:AHKActionSheetButtonTypeDefault
  2893. handler:^(AHKActionSheet *as) {
  2894. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  2895. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  2896. textField.text = _metadata.fileNameView;
  2897. //textField.selectedTextRange = [textField textRangeFromPosition:textField.beginningOfDocument toPosition:textField.endOfDocument];
  2898. //textField.delegate = self;
  2899. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  2900. }];
  2901. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2902. NSLog(@"[LOG] Cancel action");
  2903. }];
  2904. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  2905. UITextField *fileName = alertController.textFields.firstObject;
  2906. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  2907. }];
  2908. okAction.enabled = NO;
  2909. [alertController addAction:cancelAction];
  2910. [alertController addAction:okAction];
  2911. [self presentViewController:alertController animated:YES completion:nil];
  2912. }];
  2913. }
  2914. if (!([_metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES) && !lockDirectory && !isFolderEncrypted) {
  2915. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  2916. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brandElement]
  2917. backgroundColor:[UIColor whiteColor]
  2918. height:50.0
  2919. type:AHKActionSheetButtonTypeDefault
  2920. handler:^(AHKActionSheet *as) {
  2921. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  2922. }];
  2923. }
  2924. if (!([_metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES) && !isFolderEncrypted) {
  2925. [actionSheet addButtonWithTitle:NSLocalizedString(@"_folder_automatic_upload_", nil)
  2926. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderphotocamera"] color:[NCBrandColor sharedInstance].brandElement]
  2927. backgroundColor:[UIColor whiteColor]
  2928. height:50.0
  2929. type:AHKActionSheetButtonTypeDefault
  2930. handler:^(AHKActionSheet *as) {
  2931. // Settings new folder Automatatic upload
  2932. [[NCManageDatabase sharedInstance] setAccountAutoUploadFileName:_metadata.fileName];
  2933. [[NCManageDatabase sharedInstance] setAccountAutoUploadDirectory:serverUrl activeUrl:appDelegate.activeUrl];
  2934. // Clear data (old) Auto Upload
  2935. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:_autoUploadDirectory directoryID:nil];
  2936. if (appDelegate.activeAccount.length > 0 && appDelegate.activePhotos)
  2937. [appDelegate.activePhotos reloadDatasourceForced];
  2938. [self readFolder:serverUrl];
  2939. NSLog(@"[LOG] Update Folder Photo");
  2940. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:appDelegate.activeUrl];
  2941. if ([autoUploadPath length] > 0) {
  2942. [[CCSynchronize sharedSynchronize] readFileForFolder:_metadata.fileName serverUrl:serverUrl selector:selectorReadFileFolder];
  2943. }
  2944. }];
  2945. }
  2946. if (!([_metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES)) {
  2947. [actionSheet addButtonWithTitle:titoloLock
  2948. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"settingsPasscodeYES"] color:[NCBrandColor sharedInstance].brandElement]
  2949. backgroundColor:[UIColor whiteColor]
  2950. height:50.0
  2951. type:AHKActionSheetButtonTypeDefault
  2952. handler:^(AHKActionSheet *as) {
  2953. [self performSelector:@selector(comandoLockPassword) withObject:nil];
  2954. }];
  2955. }
  2956. if ([CCUtility isEndToEndEnabled:appDelegate.activeAccount] && !_metadata.e2eEncrypted && !([_metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES)) {
  2957. [actionSheet addButtonWithTitle:NSLocalizedString(@"_e2e_set_folder_encrypted_", nil)
  2958. image:[UIImage imageNamed:@"encrypted_empty"]
  2959. backgroundColor:[UIColor whiteColor]
  2960. height:50.0
  2961. type:AHKActionSheetButtonTypeEncrypted
  2962. handler:^(AHKActionSheet *as) {
  2963. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  2964. if ([appDelegate.endToEndInterface markEndToEndFolderEncrypted:appDelegate.activeUrl fileID:_metadata.fileID serverUrl:[NSString stringWithFormat:@"%@/%@", self.serverUrl, _metadata.fileName]]) {
  2965. dispatch_async(dispatch_get_main_queue(), ^{
  2966. [self readFolder:self.serverUrl];
  2967. });
  2968. }
  2969. });
  2970. }];
  2971. }
  2972. if ([CCUtility isEndToEndEnabled:appDelegate.activeAccount] && _metadata.e2eEncrypted) {
  2973. [actionSheet addButtonWithTitle:NSLocalizedString(@"_e2e_remove_folder_encrypted_", nil)
  2974. image:[UIImage imageNamed:@"encrypted_empty"]
  2975. backgroundColor:[UIColor whiteColor]
  2976. height:50.0
  2977. type:AHKActionSheetButtonTypeEncrypted
  2978. handler:^(AHKActionSheet *as) {
  2979. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  2980. if ([appDelegate.endToEndInterface deletemarkEndToEndFolderEncrypted:appDelegate.activeUrl fileID:_metadata.fileID serverUrl:[NSString stringWithFormat:@"%@/%@", self.serverUrl, _metadata.fileName]]) {
  2981. dispatch_async(dispatch_get_main_queue(), ^{
  2982. [self readFolder:self.serverUrl];
  2983. });
  2984. }
  2985. });
  2986. }];
  2987. }
  2988. if ([CCUtility isEndToEndEnabled:appDelegate.activeAccount] && directory.e2eTokenLock.length > 0) {
  2989. [actionSheet addButtonWithTitle:NSLocalizedString(@"_e2e_remove_folder_lock_", nil)
  2990. image:[UIImage imageNamed:@"encrypted_empty"]
  2991. backgroundColor:[UIColor whiteColor]
  2992. height:50.0
  2993. type:AHKActionSheetButtonTypeEncrypted
  2994. handler:^(AHKActionSheet *as) {
  2995. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  2996. metadataNet.action = actionUnlockEndToEndFolderEncrypted;
  2997. metadataNet.fileID = _metadata.fileID;
  2998. metadataNet.serverUrl = directory.serverUrl;
  2999. metadataNet.token = directory.e2eTokenLock;
  3000. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  3001. }];
  3002. }
  3003. [actionSheet show];
  3004. }
  3005. // ******************************************* FILE *******************************************
  3006. if (!_metadata.directory) {
  3007. UIImage *iconHeader;
  3008. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:self.serverUrl account:appDelegate.activeAccount];
  3009. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3010. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, _metadata.fileID]])
  3011. iconHeader = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, _metadata.fileID]];
  3012. else
  3013. iconHeader = [UIImage imageNamed:_metadata.iconName];
  3014. [actionSheet addButtonWithTitle: _metadata.fileNameView
  3015. image: iconHeader
  3016. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3017. height: 50.0
  3018. type: AHKActionSheetButtonTypeDisabled
  3019. handler: nil
  3020. ];
  3021. if (!isFolderEncrypted) {
  3022. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3023. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"]color:[NCBrandColor sharedInstance].brandElement]
  3024. backgroundColor:[UIColor whiteColor]
  3025. height: 50.0
  3026. type:AHKActionSheetButtonTypeDefault
  3027. handler:^(AHKActionSheet *as) {
  3028. [self openWindowShare:_metadata];
  3029. }];
  3030. }
  3031. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil)
  3032. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetOpenIn"] color:[NCBrandColor sharedInstance].brandElement]
  3033. backgroundColor:[UIColor whiteColor]
  3034. height: 50.0
  3035. type:AHKActionSheetButtonTypeDefault
  3036. handler:^(AHKActionSheet *as) {
  3037. [self performSelector:@selector(openIn:) withObject:_metadata];
  3038. }];
  3039. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3040. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brandElement]
  3041. backgroundColor:[UIColor whiteColor]
  3042. height: 50.0
  3043. type:AHKActionSheetButtonTypeDefault
  3044. handler:^(AHKActionSheet *as) {
  3045. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  3046. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  3047. textField.text = _metadata.fileNameView;
  3048. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  3049. }];
  3050. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  3051. NSLog(@"[LOG] Cancel action");
  3052. }];
  3053. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  3054. UITextField *fileName = alertController.textFields.firstObject;
  3055. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  3056. }];
  3057. okAction.enabled = NO;
  3058. [alertController addAction:cancelAction];
  3059. [alertController addAction:okAction];
  3060. [self presentViewController:alertController animated:YES completion:nil];
  3061. }];
  3062. if (!isFolderEncrypted) {
  3063. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3064. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brandElement]
  3065. backgroundColor:[UIColor whiteColor]
  3066. height: 50.0
  3067. type:AHKActionSheetButtonTypeDefault
  3068. handler:^(AHKActionSheet *as) {
  3069. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3070. }];
  3071. }
  3072. if (localFile || [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, _metadata.fileID]]) {
  3073. [actionSheet addButtonWithTitle:NSLocalizedString(@"_remove_local_file_", nil)
  3074. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRemoveLocal"] color:[NCBrandColor sharedInstance].brandElement]
  3075. backgroundColor:[UIColor whiteColor]
  3076. height: 50.0
  3077. type:AHKActionSheetButtonTypeDefault
  3078. handler:^(AHKActionSheet *as) {
  3079. [self performSelector:@selector(removeLocalFile:) withObject:_metadata];
  3080. }];
  3081. }
  3082. [actionSheet show];
  3083. }
  3084. }
  3085. #pragma --------------------------------------------------------------------------------------------
  3086. #pragma mark - ==== Datasource ====
  3087. #pragma --------------------------------------------------------------------------------------------
  3088. - (void)clearDateReadDataSource:(NSNotification *)notification
  3089. {
  3090. _dateReadDataSource = Nil;
  3091. [self reloadDatasource];
  3092. }
  3093. - (void)reloadDatasource
  3094. {
  3095. [self reloadDatasource:_serverUrl];
  3096. }
  3097. - (void)reloadDatasource:(NSString *)serverUrl
  3098. {
  3099. // test
  3100. if (appDelegate.activeAccount.length == 0 || serverUrl.length == 0 || serverUrl == nil)
  3101. return;
  3102. // Search Mode
  3103. if (_isSearchMode) {
  3104. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:_searchResultMetadatas listProgressMetadata:nil e2eEncryptions:nil groupByField:_directoryGroupBy activeAccount:appDelegate.activeAccount];
  3105. [self tableViewReloadData];
  3106. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  3107. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  3108. _noFilesSearchDescription = @"";
  3109. }
  3110. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  3111. _noFilesSearchTitle = @"";
  3112. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  3113. }
  3114. [self.tableView reloadEmptyDataSet];
  3115. return;
  3116. }
  3117. // Reload -> Self se non siamo nella dir appropriata cercala e se è in memoria reindirizza il reload
  3118. if ([serverUrl isEqualToString:_serverUrl] == NO || _serverUrl == nil) {
  3119. CCMain *main = [appDelegate.listMainVC objectForKey:serverUrl];
  3120. if (main) {
  3121. [main reloadDatasource];
  3122. } else {
  3123. [self tableViewReloadData];
  3124. [appDelegate.activeTransfers reloadDatasource];
  3125. }
  3126. return;
  3127. }
  3128. [appDelegate.activeTransfers reloadDatasource];
  3129. // Settaggio variabili per le ottimizzazioni
  3130. _directoryGroupBy = [CCUtility getGroupBySettings];
  3131. _directoryOrder = [CCUtility getOrderSettings];
  3132. // Remove optimization for encrypted directory
  3133. if ([CCUtility isFolderEncrypted:self.serverUrl account:appDelegate.activeAccount])
  3134. _dateReadDataSource = nil;
  3135. // current directoryID
  3136. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  3137. // Controllo data lettura Data Source
  3138. tableDirectory *tableDirectory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, serverUrl]];
  3139. // Get MetadataFolder
  3140. _metadataFolder = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND fileID = %@", appDelegate.activeAccount, tableDirectory.fileID]];
  3141. NSDate *dateDateRecordDirectory = tableDirectory.dateReadDirectory;
  3142. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  3143. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  3144. _dateReadDataSource = [NSDate date];
  3145. // Data Source
  3146. NSString *sorted = _directoryOrder;
  3147. if ([sorted isEqualToString:@"fileName"])
  3148. sorted = @"fileName";
  3149. if (directoryID) {
  3150. NSArray *recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND status = %i", appDelegate.activeAccount, directoryID, k_metadataStatusNormal] sorted:sorted ascending:[CCUtility getAscendingSettings]];
  3151. NSArray *recordsTableE2eEncryption = [[NCManageDatabase sharedInstance] getE2eEncryptionsWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, serverUrl]];
  3152. _sectionDataSource = [CCSectionDataSourceMetadata new];
  3153. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil e2eEncryptions:recordsTableE2eEncryption groupByField:_directoryGroupBy activeAccount:appDelegate.activeAccount];
  3154. // get auto upload folder
  3155. _autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  3156. _autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:appDelegate.activeUrl];
  3157. }
  3158. } else {
  3159. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  3160. }
  3161. [self tableViewReloadData];
  3162. }
  3163. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  3164. {
  3165. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  3166. if (selectedRows.count > 0) {
  3167. for (NSIndexPath *selectionIndex in selectedRows) {
  3168. NSString *fileID = [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  3169. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3170. [metadatas addObject:metadata];
  3171. }
  3172. }
  3173. return metadatas;
  3174. }
  3175. - (tableMetadata *)getMetadataFromSectionDataSource:(NSIndexPath *)indexPath
  3176. {
  3177. NSInteger section = indexPath.section + 1;
  3178. NSInteger row = indexPath.row + 1;
  3179. NSInteger totSections = [_sectionDataSource.sections count] ;
  3180. if ((totSections < section) || (section > totSections)) {
  3181. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [0] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section]);
  3182. return nil;
  3183. }
  3184. id valueSection = [_sectionDataSource.sections objectAtIndex:indexPath.section];
  3185. NSArray *fileIDs = [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3186. if (fileIDs) {
  3187. NSInteger totRows =[fileIDs count] ;
  3188. if ((totRows < row) || (row > totRows)) {
  3189. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [1] : error row, totRows = %lu - row = %lu", (long)totRows, (long)row]);
  3190. return nil;
  3191. }
  3192. } else {
  3193. NSLog(@"[LOG] DEBUG [2] : fileIDs is NIL");
  3194. return nil;
  3195. }
  3196. NSString *fileID = [fileIDs objectAtIndex:indexPath.row];
  3197. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3198. return metadata;
  3199. }
  3200. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  3201. {
  3202. NSInteger totSections =[_sectionDataSource.sections count] ;
  3203. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  3204. return nil;
  3205. }
  3206. id valueSection = [_sectionDataSource.sections objectAtIndex:section];
  3207. return [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3208. }
  3209. #pragma --------------------------------------------------------------------------------------------
  3210. #pragma mark - ==== Table ====
  3211. #pragma --------------------------------------------------------------------------------------------
  3212. - (void)tableViewSelect:(BOOL)edit
  3213. {
  3214. // chiudiamo eventuali swipe aperti
  3215. if (edit)
  3216. [self.tableView setEditing:NO animated:NO];
  3217. [self.tableView setAllowsMultipleSelectionDuringEditing:edit];
  3218. [self.tableView setEditing:edit animated:YES];
  3219. _isSelectedMode = edit;
  3220. if (edit)
  3221. [self setUINavigationBarSelected];
  3222. else
  3223. [self setUINavigationBarDefault];
  3224. [_selectedFileIDsMetadatas removeAllObjects];
  3225. [self setTitle];
  3226. }
  3227. - (void)tableViewReloadData
  3228. {
  3229. // store selected cells before relod
  3230. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  3231. //store swipeOffset before relod
  3232. [_statusSwipeCell removeAllObjects];
  3233. for (MGSwipeTableCell *cell in self.tableView.visibleCells) {
  3234. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  3235. [_statusSwipeCell setObject:[NSNumber numberWithDouble:cell.swipeOffset] forKey:indexPath];
  3236. }
  3237. // reload table view
  3238. [self.tableView reloadData];
  3239. // selected cells stored
  3240. for (NSIndexPath *path in indexPaths)
  3241. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  3242. [self setTableViewFooter];
  3243. if (self.tableView.editing)
  3244. [self setTitle];
  3245. }
  3246. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  3247. {
  3248. if (tableView.editing == 1) {
  3249. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3250. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  3251. return NO;
  3252. if (metadata == nil || metadata.sessionTaskIdentifier != k_taskIdentifierDone)
  3253. return NO;
  3254. else
  3255. return YES;
  3256. } else {
  3257. [_selectedFileIDsMetadatas removeAllObjects];
  3258. }
  3259. return YES;
  3260. }
  3261. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  3262. {
  3263. return 60;
  3264. }
  3265. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  3266. {
  3267. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  3268. }
  3269. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  3270. {
  3271. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  3272. }
  3273. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  3274. {
  3275. NSArray *sections = [_sectionDataSource.sectionArrayRow allKeys];
  3276. NSString *sectionTitle = [sections objectAtIndex:section];
  3277. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  3278. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  3279. if ([_directoryGroupBy isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  3280. return 20.f;
  3281. }
  3282. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  3283. {
  3284. float shift;
  3285. UIVisualEffectView *visualEffectView;
  3286. NSString *titleSection;
  3287. if (![self indexPathIsValid:[NSIndexPath indexPathForRow:0 inSection:section]])
  3288. return nil;
  3289. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]])
  3290. titleSection = [_sectionDataSource.sections objectAtIndex:section];
  3291. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]])
  3292. titleSection = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:section]];
  3293. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  3294. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  3295. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  3296. else titleSection = NSLocalizedString(titleSection,nil);
  3297. // Format title
  3298. NSString *currentDevice = [CCUtility currentDevice];
  3299. if ([currentDevice rangeOfString:@"iPad3"].location != NSNotFound) {
  3300. visualEffectView = [[UIVisualEffectView alloc] init];
  3301. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.3];
  3302. } else {
  3303. UIVisualEffect *blurEffect;
  3304. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  3305. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  3306. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.2];
  3307. }
  3308. if ([_directoryGroupBy isEqualToString:@"alphabetic"]) {
  3309. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  3310. shift = - 35;
  3311. else
  3312. shift = - 20;
  3313. } else shift = - 10;
  3314. // Title
  3315. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  3316. titleLabel.backgroundColor = [UIColor clearColor];
  3317. titleLabel.textColor = [UIColor blackColor];
  3318. titleLabel.font = [UIFont systemFontOfSize:12];
  3319. titleLabel.textAlignment = NSTextAlignmentLeft;
  3320. titleLabel.text = titleSection;
  3321. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3322. [visualEffectView.contentView addSubview:titleLabel];
  3323. // Elements
  3324. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  3325. elementLabel.backgroundColor = [UIColor clearColor];
  3326. elementLabel.textColor = [UIColor blackColor];;
  3327. elementLabel.font = [UIFont systemFontOfSize:12];
  3328. elementLabel.textAlignment = NSTextAlignmentRight;
  3329. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3330. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  3331. NSUInteger rowsCount = [metadatas count];
  3332. if (rowsCount == 0) return nil;
  3333. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  3334. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  3335. [visualEffectView.contentView addSubview:elementLabel];
  3336. return visualEffectView;
  3337. }
  3338. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  3339. {
  3340. return [_sectionDataSource.sections indexOfObject:title];
  3341. }
  3342. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  3343. {
  3344. if ([_directoryGroupBy isEqualToString:@"alphabetic"])
  3345. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  3346. else
  3347. return nil;
  3348. }
  3349. /*
  3350. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  3351. {
  3352. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  3353. }
  3354. }
  3355. */
  3356. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  3357. {
  3358. NSString *typeCell;
  3359. NSString *dataFile;
  3360. NSString *lunghezzaFile;
  3361. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3362. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  3363. return [tableView dequeueReusableCellWithIdentifier:@"CellMain"];
  3364. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  3365. if (!serverUrl)
  3366. return [tableView dequeueReusableCellWithIdentifier:@"CellMain"];
  3367. if ([metadata.session isEqualToString:@""] || metadata.session == nil) typeCell = @"CellMain";
  3368. else typeCell = @"CellMainTransfer";
  3369. CCCellMainTransfer *cell = (CCCellMainTransfer *)[tableView dequeueReusableCellWithIdentifier:typeCell forIndexPath:indexPath];
  3370. // variable base
  3371. cell.delegate = self;
  3372. cell.indexPath = indexPath;
  3373. // separator
  3374. cell.separatorInset = UIEdgeInsetsMake(0.f, 60.f, 0.f, 0.f);
  3375. // change color selection
  3376. UIView *selectionColor = [[UIView alloc] init];
  3377. selectionColor.backgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  3378. cell.selectedBackgroundView = selectionColor;
  3379. if ([typeCell isEqualToString:@"CellMain"]) cell.backgroundColor = [UIColor whiteColor];
  3380. if ([typeCell isEqualToString:@"CellMainTransfer"]) cell.backgroundColor = [NCBrandColor sharedInstance].transferBackground;
  3381. // ----------------------------------------------------------------------------------------------------------
  3382. // DEFAULT
  3383. // ----------------------------------------------------------------------------------------------------------
  3384. cell.file.image = nil;
  3385. cell.status.image = nil;
  3386. cell.favorite.image = nil;
  3387. cell.shared.image = nil;
  3388. cell.local.image = nil;
  3389. cell.labelTitle.enabled = YES;
  3390. cell.labelTitle.text = @"";
  3391. cell.labelInfoFile.enabled = YES;
  3392. cell.labelInfoFile.text = @"";
  3393. cell.progressView.progress = 0.0;
  3394. cell.progressView.hidden = YES;
  3395. cell.cancelTaskButton.hidden = YES;
  3396. cell.reloadTaskButton.hidden = YES;
  3397. cell.stopTaskButton.hidden = YES;
  3398. cell.labelTitle.textColor = [UIColor blackColor];
  3399. // ----------------------------------------------------------------------------------------------------------
  3400. // File Name & Folder
  3401. // ----------------------------------------------------------------------------------------------------------
  3402. // nome del file
  3403. cell.labelTitle.text = metadata.fileNameView;
  3404. // è una directory
  3405. if (metadata.directory) {
  3406. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  3407. cell.labelInfoFile.text = [CCUtility dateDiff:metadata.date];
  3408. lunghezzaFile = @" ";
  3409. // ----------------------------------------------------------------------------------------------------------
  3410. // Favorite Folder
  3411. // ----------------------------------------------------------------------------------------------------------
  3412. if (metadata.favorite) {
  3413. cell.favorite.image = [UIImage imageNamed:@"favorite"];
  3414. }
  3415. } else {
  3416. // File
  3417. dataFile = [CCUtility dateDiff:metadata.date];
  3418. lunghezzaFile = [CCUtility transformedSize:metadata.size];
  3419. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  3420. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  3421. [dateFormatter setDateStyle:NSDateFormatterShortStyle];
  3422. [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
  3423. if (localFile && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadata.fileID]])
  3424. cell.local.image = [UIImage imageNamed:@"local"];
  3425. else
  3426. cell.local.image = nil;
  3427. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ %@", dataFile, lunghezzaFile];
  3428. cell.accessoryType = UITableViewCellAccessoryNone;
  3429. }
  3430. // ----------------------------------------------------------------------------------------------------------
  3431. // File Image View
  3432. // ----------------------------------------------------------------------------------------------------------
  3433. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3434. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, metadata.fileID]]) {
  3435. cell.file.image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, metadata.fileID]];
  3436. } else {
  3437. if (metadata.directory) {
  3438. if (metadata.e2eEncrypted)
  3439. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderEncrypted"] color:[NCBrandColor sharedInstance].brandElement];
  3440. else if ([metadata.fileName isEqualToString:_autoUploadFileName] && [self.serverUrl isEqualToString:_autoUploadDirectory])
  3441. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderphotocamera"] color:[NCBrandColor sharedInstance].brandElement];
  3442. else
  3443. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder"] color:[NCBrandColor sharedInstance].brandElement];
  3444. } else {
  3445. cell.file.image = [UIImage imageNamed:metadata.iconName];
  3446. }
  3447. if (metadata.thumbnailExists && _metadataFolder.e2eEncrypted == NO)
  3448. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  3449. }
  3450. // ----------------------------------------------------------------------------------------------------------
  3451. // Image Status Lock Passcode
  3452. // ----------------------------------------------------------------------------------------------------------
  3453. // Directory con passcode lock attivato
  3454. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName];
  3455. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, lockServerUrl]];
  3456. if (metadata.directory && (directory.lock && [[CCUtility getBlockCode] length]))
  3457. cell.status.image = [UIImage imageNamed:@"passcode"];
  3458. // ----------------------------------------------------------------------------------------------------------
  3459. // E2E Image Status Encrypted
  3460. // ----------------------------------------------------------------------------------------------------------
  3461. if (_metadataFolder.e2eEncrypted && !metadata.directory) {
  3462. tableE2eEncryption *tableE2eEncryption = [[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND fileNameIdentifier = %@", appDelegate.activeAccount, metadata.fileName]];
  3463. if (tableE2eEncryption)
  3464. cell.status.image = [UIImage imageNamed:@"encrypted"];
  3465. }
  3466. // ----------------------------------------------------------------------------------------------------------
  3467. // Favorite
  3468. // ----------------------------------------------------------------------------------------------------------
  3469. if (metadata.favorite) {
  3470. cell.favorite.image = [UIImage imageNamed:@"favorite"];
  3471. }
  3472. // ----------------------------------------------------------------------------------------------------------
  3473. // Share
  3474. // ----------------------------------------------------------------------------------------------------------
  3475. NSString *shareLink = [appDelegate.sharesLink objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3476. NSString *shareUserAndGroup = [appDelegate.sharesUserAndGroup objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3477. BOOL isShare = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_shared].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_shared].location == NSNotFound);
  3478. BOOL isMounted = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_mounted].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_mounted].location == NSNotFound);
  3479. // Aggiungiamo il Tap per le shared
  3480. if (isShare || [shareLink length] > 0 || [shareUserAndGroup length] > 0 || isMounted) {
  3481. // Shared with you
  3482. if (isShare) {
  3483. if (metadata.directory) {
  3484. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brandElement];
  3485. cell.accessoryType = UITableViewCellAccessoryNone;
  3486. }
  3487. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brandElement];
  3488. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3489. [tap setNumberOfTapsRequired:1];
  3490. cell.shared.userInteractionEnabled = YES;
  3491. [cell.shared addGestureRecognizer:tap];
  3492. }
  3493. // Mounted with you
  3494. if (isMounted) {
  3495. if (metadata.directory) {
  3496. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_external"] color:[NCBrandColor sharedInstance].brandElement];
  3497. cell.accessoryType = UITableViewCellAccessoryNone;
  3498. }
  3499. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareMounted"] color:[NCBrandColor sharedInstance].brandElement];
  3500. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3501. [tap setNumberOfTapsRequired:1];
  3502. cell.shared.userInteractionEnabled = YES;
  3503. [cell.shared addGestureRecognizer:tap];
  3504. }
  3505. // You share
  3506. if ([shareLink length] > 0 || [shareUserAndGroup length] > 0) {
  3507. if (metadata.directory) {
  3508. if ([shareLink length] > 0)
  3509. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_public"] color:[NCBrandColor sharedInstance].brandElement];
  3510. if ([shareUserAndGroup length] > 0)
  3511. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brandElement];
  3512. cell.shared.userInteractionEnabled = NO;
  3513. } else {
  3514. if ([shareLink length] > 0)
  3515. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareLink"] color:[NCBrandColor sharedInstance].brandElement];
  3516. if ([shareUserAndGroup length] > 0)
  3517. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brandElement];
  3518. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  3519. [tap setNumberOfTapsRequired:1];
  3520. cell.shared.userInteractionEnabled = YES;
  3521. [cell.shared addGestureRecognizer:tap];
  3522. }
  3523. }
  3524. } else {
  3525. cell.shared.userInteractionEnabled = NO;
  3526. }
  3527. // ----------------------------------------------------------------------------------------------------------
  3528. // downloadFile
  3529. // ----------------------------------------------------------------------------------------------------------
  3530. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  3531. cell.status.image = [UIImage imageNamed:@"statusdownload"];
  3532. // sessionTaskIdentifier : RELOAD + STOP
  3533. if (metadata.sessionTaskIdentifier != k_taskIdentifierDone) {
  3534. [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3535. cell.cancelTaskButton.hidden = NO;
  3536. [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3537. cell.reloadTaskButton.hidden = NO;
  3538. }
  3539. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3540. float progress = [[appDelegate.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3541. if (progress > 0) {
  3542. cell.progressView.progressTintColor = [UIColor blackColor];
  3543. cell.progressView.progress = progress;
  3544. cell.progressView.hidden = NO;
  3545. }
  3546. // ----------------------------------------------------------------------------------------------------------
  3547. // downloadFile Error
  3548. // ----------------------------------------------------------------------------------------------------------
  3549. if (metadata.sessionTaskIdentifier == k_taskIdentifierError) {
  3550. cell.status.image = [UIImage imageNamed:@"statuserror"];
  3551. if ([metadata.sessionError length] == 0) {
  3552. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_downloaded_",nil)];
  3553. } else {
  3554. cell.labelInfoFile.text = metadata.sessionError;
  3555. }
  3556. }
  3557. }
  3558. // ----------------------------------------------------------------------------------------------------------
  3559. // uploadFile
  3560. // ----------------------------------------------------------------------------------------------------------
  3561. if ([metadata.session length] > 0 && [metadata.session rangeOfString:@"upload"].location != NSNotFound) {
  3562. cell.status.image = [UIImage imageNamed:@"statusupload"];
  3563. [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"removetask"] forState:UIControlStateNormal];
  3564. cell.cancelTaskButton.hidden = NO;
  3565. if (metadata.sessionTaskIdentifier == k_taskIdentifierStop) {
  3566. [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3567. cell.status.image = [UIImage imageNamed:@"statusstop"];
  3568. cell.reloadTaskButton.hidden = NO;
  3569. cell.stopTaskButton.hidden = YES;
  3570. } else {
  3571. [cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3572. cell.stopTaskButton.hidden = NO;
  3573. cell.reloadTaskButton.hidden = YES;
  3574. }
  3575. // se non c'è una preview in bianconero metti l'immagine di default
  3576. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, metadata.fileID]] == NO)
  3577. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"uploaddisable"] color:[NCBrandColor sharedInstance].brandElement];
  3578. cell.labelTitle.enabled = NO;
  3579. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3580. float progress = [[appDelegate.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3581. if (progress > 0) {
  3582. cell.progressView.progressTintColor = [UIColor blackColor];
  3583. cell.progressView.progress = progress;
  3584. cell.progressView.hidden = NO;
  3585. }
  3586. // ----------------------------------------------------------------------------------------------------------
  3587. // uploadFileError
  3588. // ----------------------------------------------------------------------------------------------------------
  3589. if (metadata.sessionTaskIdentifier == k_taskIdentifierError) {
  3590. cell.labelTitle.enabled = NO;
  3591. cell.status.image = [UIImage imageNamed:@"statuserror"];
  3592. if ([metadata.sessionError length] == 0) {
  3593. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_uploaded_",nil)];
  3594. } else {
  3595. cell.labelInfoFile.text = metadata.sessionError;
  3596. }
  3597. }
  3598. }
  3599. [cell.reloadTaskButton addTarget:self action:@selector(reloadTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3600. [cell.cancelTaskButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3601. [cell.stopTaskButton addTarget:self action:@selector(stopTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3602. // ======== MGSwipe ========
  3603. if (metadata.favorite)
  3604. cell.leftButtons = @[[MGSwipeButton buttonWithTitle:[NSString stringWithFormat:@" %@ ", NSLocalizedString(@"_unfavorite_", nil)] icon:[UIImage imageNamed:@"swipeUnfavorite"] backgroundColor:[UIColor colorWithRed:242.0/255.0 green:220.0/255.0 blue:132.0/255.0 alpha:1.000]]];
  3605. else
  3606. cell.leftButtons = @[[MGSwipeButton buttonWithTitle:[NSString stringWithFormat:@" %@ ", NSLocalizedString(@"_favorite_", nil)] icon:[UIImage imageNamed:@"swipeFavorite"] backgroundColor:[UIColor colorWithRed:242.0/255.0 green:220.0/255.0 blue:132.0/255.0 alpha:1.000]]];
  3607. cell.leftExpansion.buttonIndex = 0;
  3608. cell.leftExpansion.fillOnTrigger = NO;
  3609. //centerIconOverText
  3610. MGSwipeButton *favoriteButton = (MGSwipeButton *)[cell.leftButtons objectAtIndex:0];
  3611. [favoriteButton centerIconOverText];
  3612. //Right
  3613. cell.rightButtons = @[[MGSwipeButton buttonWithTitle:[NSString stringWithFormat:@" %@ ", NSLocalizedString(@"_delete_", nil)] icon:[UIImage imageNamed:@"swipeDelete"] backgroundColor:[UIColor redColor]], [MGSwipeButton buttonWithTitle:[NSString stringWithFormat:@" %@ ", NSLocalizedString(@"_more_", nil)] icon:[UIImage imageNamed:@"swipeMore"] backgroundColor:[UIColor lightGrayColor]]];
  3614. cell.rightSwipeSettings.transition = MGSwipeTransitionBorder;
  3615. //centerIconOverText
  3616. MGSwipeButton *deleteButton = (MGSwipeButton *)[cell.rightButtons objectAtIndex:0];
  3617. MGSwipeButton *moreButton = (MGSwipeButton *)[cell.rightButtons objectAtIndex:1];
  3618. [deleteButton centerIconOverText];
  3619. [moreButton centerIconOverText];
  3620. //restore swipeOffset after relod
  3621. CGFloat swipeOffset = [[_statusSwipeCell objectForKey:indexPath] doubleValue];
  3622. if (swipeOffset < 0) {
  3623. [cell showSwipe:MGSwipeDirectionRightToLeft animated:NO];
  3624. [_statusSwipeCell removeObjectForKey:indexPath];
  3625. } else if (swipeOffset > 0) {
  3626. [cell showSwipe:MGSwipeDirectionLeftToRight animated:NO];
  3627. [_statusSwipeCell removeObjectForKey:indexPath];
  3628. }
  3629. return cell;
  3630. }
  3631. - (void)setTableViewFooter
  3632. {
  3633. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3634. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3635. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3636. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3637. UIFont *appFont = [UIFont systemFontOfSize:12];
  3638. footerLabel.font = appFont;
  3639. footerLabel.textColor = [UIColor grayColor];
  3640. footerLabel.backgroundColor = [UIColor clearColor];
  3641. footerLabel.textAlignment = NSTextAlignmentCenter;
  3642. NSString *folders;
  3643. NSString *files;
  3644. NSString *footerText;
  3645. if (_sectionDataSource.directories > 1) {
  3646. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  3647. } else if (_sectionDataSource.directories == 1){
  3648. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  3649. } else {
  3650. folders = @"";
  3651. }
  3652. if (_sectionDataSource.files > 1) {
  3653. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3654. } else if (_sectionDataSource.files == 1){
  3655. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3656. } else {
  3657. files = @"";
  3658. }
  3659. if ([folders isEqualToString:@""]) {
  3660. footerText = files;
  3661. } else if ([files isEqualToString:@""]) {
  3662. footerText = folders;
  3663. } else {
  3664. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  3665. }
  3666. footerLabel.text = footerText;
  3667. [footerView addSubview:footerLabel];
  3668. [self.tableView setTableFooterView:footerView];
  3669. }
  3670. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  3671. {
  3672. UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
  3673. // settiamo il record file.
  3674. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3675. if (!_metadata)
  3676. return;
  3677. // se non può essere selezionata deseleziona
  3678. if ([cell isEditing] == NO)
  3679. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  3680. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  3681. if (self.tableView.editing) {
  3682. [_selectedFileIDsMetadatas setObject:_metadata forKey:_metadata.fileID];
  3683. [self setTitle];
  3684. return;
  3685. }
  3686. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3687. if (!serverUrl) return;
  3688. // se è in corso una sessione
  3689. if ([_metadata.session length] > 0) return;
  3690. // file
  3691. if (_metadata.directory == NO) {
  3692. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  3693. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, _metadata.fileID]]) {
  3694. [self downloadFileSuccessFailure:_metadata.fileName fileID:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:@"" errorMessage:@"" errorCode:0];
  3695. } else {
  3696. if ([CCUtility isFolderEncrypted:self.serverUrl account:appDelegate.activeAccount] && ![CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  3697. [appDelegate messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  3698. } else {
  3699. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileName fileID:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  3700. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  3701. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  3702. }
  3703. }
  3704. }
  3705. if (_metadata.directory) [self performSegueDirectoryWithControlPasscode:true];
  3706. }
  3707. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  3708. {
  3709. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3710. [_selectedFileIDsMetadatas removeObjectForKey:metadata.fileID];
  3711. [self setTitle];
  3712. }
  3713. - (BOOL)indexPathIsValid:(NSIndexPath *)indexPath
  3714. {
  3715. if (!indexPath)
  3716. return NO;
  3717. NSInteger section = indexPath.section;
  3718. NSInteger row = indexPath.row;
  3719. NSInteger lastSectionIndex = [self numberOfSectionsInTableView:self.tableView] - 1;
  3720. if (section > lastSectionIndex || lastSectionIndex < 0)
  3721. return NO;
  3722. NSInteger rowCount = [self.tableView numberOfRowsInSection:indexPath.section] - 1;
  3723. if (rowCount < 0)
  3724. return NO;
  3725. return row <= rowCount;
  3726. }
  3727. #pragma --------------------------------------------------------------------------------------------
  3728. #pragma mark ===== Navigation ====
  3729. #pragma --------------------------------------------------------------------------------------------
  3730. - (BOOL)shouldPerformSegue
  3731. {
  3732. // if background return
  3733. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return NO;
  3734. if (self.view.window == NO)
  3735. return NO;
  3736. // Collapsed ma siamo già in detail esci
  3737. if (self.splitViewController.isCollapsed)
  3738. if (_detailViewController.isViewLoaded && _detailViewController.view.window) return NO;
  3739. return YES;
  3740. }
  3741. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  3742. {
  3743. id viewController = segue.destinationViewController;
  3744. NSMutableArray *allRecordsDataSourceImagesVideos = [NSMutableArray new];
  3745. tableMetadata *metadata;
  3746. if ([viewController isKindOfClass:[UINavigationController class]]) {
  3747. UINavigationController *nav = viewController;
  3748. _detailViewController = (CCDetail *)nav.topViewController;
  3749. } else {
  3750. _detailViewController = segue.destinationViewController;
  3751. }
  3752. if ([sender isKindOfClass:[tableMetadata class]]) {
  3753. metadata = sender;
  3754. [allRecordsDataSourceImagesVideos addObject:sender];
  3755. } else {
  3756. metadata = _metadata;
  3757. for (NSString *fileID in _sectionDataSource.allEtag) {
  3758. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3759. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video] || [metadata.typeFile isEqualToString: k_metadataTypeFile_audio])
  3760. [allRecordsDataSourceImagesVideos addObject:metadata];
  3761. }
  3762. }
  3763. _detailViewController.metadataDetail = metadata;
  3764. _detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  3765. _detailViewController.dateFilterQuery = nil;
  3766. [_detailViewController setTitle:metadata.fileName];
  3767. }
  3768. // can i go to next viewcontroller
  3769. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode
  3770. {
  3771. NSString *nomeDir;
  3772. if(self.tableView.editing == NO) {
  3773. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3774. if (!serverUrl) return;
  3775. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  3776. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, lockServerUrl]];
  3777. // SE siamo in presenza di una directory bloccata E è attivo il block E la sessione password Lock è senza data ALLORA chiediamo la password per procedere
  3778. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil && controlPasscode) {
  3779. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  3780. viewController.delegate = self;
  3781. viewController.fromType = CCBKPasscodeFromLockDirectory;
  3782. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  3783. viewController.inputViewTitlePassword = YES;
  3784. if ([CCUtility getSimplyBlockCode]) {
  3785. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  3786. viewController.passcodeInputView.maximumLength = 6;
  3787. } else {
  3788. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  3789. viewController.passcodeInputView.maximumLength = 64;
  3790. }
  3791. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  3792. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  3793. viewController.touchIDManager = touchIDManager;
  3794. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  3795. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  3796. viewController.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
  3797. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  3798. [self presentViewController:navController animated:YES completion:nil];
  3799. return;
  3800. }
  3801. nomeDir = _metadata.fileName;
  3802. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:serverUrl addFileName:nomeDir];
  3803. CCMain *viewController = [appDelegate.listMainVC objectForKey:serverUrlPush];
  3804. if (!viewController) {
  3805. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMainVC"];
  3806. viewController.serverUrl = serverUrlPush;
  3807. viewController.titleMain = _metadata.fileName;
  3808. viewController.textBackButton = _titleMain;
  3809. // save self
  3810. [appDelegate.listMainVC setObject:viewController forKey:serverUrlPush];
  3811. [self.navigationController pushViewController:viewController animated:YES];
  3812. } else {
  3813. if (viewController.isViewLoaded) {
  3814. // Fix : Application tried to present modally an active controller
  3815. if ([self.navigationController isBeingPresented]) {
  3816. // being presented
  3817. } else if ([self.navigationController isMovingToParentViewController]) {
  3818. // being pushed
  3819. } else {
  3820. [self.navigationController pushViewController:viewController animated:YES];
  3821. }
  3822. }
  3823. }
  3824. }
  3825. }
  3826. @end