CCMain.m 207 KB

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