CCMain.m 205 KB

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