CCMain.m 223 KB

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