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