CCMain.m 206 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237
  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. }
  63. @end
  64. @implementation CCMain
  65. #pragma --------------------------------------------------------------------------------------------
  66. #pragma mark ===== Init =====
  67. #pragma --------------------------------------------------------------------------------------------
  68. - (id)initWithCoder:(NSCoder *)aDecoder
  69. {
  70. if (self = [super initWithCoder:aDecoder]) {
  71. appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  72. appDelegate.activeMain = self;
  73. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initializeMain:) name:@"initializeMain" object:nil];
  74. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearDateReadDataSource:) name:@"clearDateReadDataSource" object:nil];
  75. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTitle) name:@"setTitleMain" object:nil];
  76. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:@"NotificationProgressTask" object:nil];
  77. }
  78. return self;
  79. }
  80. #pragma --------------------------------------------------------------------------------------------
  81. #pragma mark ===== View =====
  82. #pragma --------------------------------------------------------------------------------------------
  83. - (void)viewDidLoad
  84. {
  85. [super viewDidLoad];
  86. // init object
  87. self.metadata = [tableMetadata new];
  88. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  89. _selectedocIdsMetadatas = [NSMutableDictionary new];
  90. _isViewDidLoad = YES;
  91. _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
  92. _searchResultMetadatas = [NSMutableArray new];
  93. _searchFileName = @"";
  94. _noFilesSearchTitle = @"";
  95. _noFilesSearchDescription = @"";
  96. _cellFavouriteImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] width:50 height:50 color:[UIColor whiteColor]];
  97. _cellTrashImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"trash"] width:50 height:50 color:[UIColor whiteColor]];
  98. // delegate
  99. self.tableView.delegate = self;
  100. self.tableView.tableFooterView = [UIView new];
  101. self.tableView.emptyDataSetDelegate = self;
  102. self.tableView.emptyDataSetSource = self;
  103. self.searchController.delegate = self;
  104. self.searchController.searchBar.delegate = self;
  105. // Register cell
  106. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMain" bundle:nil] forCellReuseIdentifier:@"CellMain"];
  107. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMainTransfer" bundle:nil] forCellReuseIdentifier:@"CellMainTransfer"];
  108. // long press recognizer TableView
  109. UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPressTableView:)];
  110. [self.tableView addGestureRecognizer:longPressRecognizer];
  111. // Load Rich Workspace
  112. self.viewRichWorkspace = [[[NSBundle mainBundle] loadNibNamed:@"NCRichWorkspace" owner:self options:nil] firstObject];
  113. UITapGestureRecognizer *viewRichWorkspaceTapped = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(viewRichWorkspaceTapAction:)];
  114. viewRichWorkspaceTapped.numberOfTapsRequired = 1;
  115. viewRichWorkspaceTapped.delegate = self;
  116. [self.viewRichWorkspace addGestureRecognizer:viewRichWorkspaceTapped];
  117. // Pull-to-Refresh
  118. [self createRefreshControl];
  119. // Register for 3D Touch Previewing if available
  120. if ([self.traitCollection respondsToSelector:@selector(forceTouchCapability)] && (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable)) {
  121. [self registerForPreviewingWithDelegate:self sourceView:self.view];
  122. }
  123. // reMenu Background
  124. _reMenuBackgroundView = [UIView new];
  125. _reMenuBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
  126. // if this is not Main (the Main uses inizializeMain)
  127. if (_isRoot == NO && appDelegate.activeAccount.length > 0) {
  128. // Read (File) Folder
  129. [self readFileReloadFolder];
  130. }
  131. // Title
  132. [self setTitle];
  133. // changeTheming
  134. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheming) name:@"changeTheming" object:nil];
  135. [self changeTheming];
  136. }
  137. - (void)viewWillAppear:(BOOL)animated
  138. {
  139. [super viewWillAppear:animated];
  140. // test
  141. if (appDelegate.activeAccount.length == 0)
  142. return;
  143. if (_isSelectedMode)
  144. [self setUINavigationBarSelected];
  145. else
  146. [self setUINavigationBarDefault];
  147. // If not editing mode remove _selectedocIds
  148. if (!self.tableView.editing)
  149. [_selectedocIdsMetadatas removeAllObjects];
  150. // Search Bar
  151. if ([CCUtility isFolderEncrypted:self.serverUrl account:appDelegate.activeAccount]) {
  152. [self searchEnabled:NO];
  153. } else {
  154. [self searchEnabled:YES];
  155. }
  156. // Get Shares
  157. appDelegate.shares = [[NCManageDatabase sharedInstance] getTableSharesWithAccount:appDelegate.activeAccount serverUrl:self.serverUrl];
  158. // Get RichWorkspace
  159. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, self.serverUrl]];
  160. self.richWorkspace = directory.richWorkspace;
  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) viewDidLayoutSubviews
  195. {
  196. [super viewDidLayoutSubviews];
  197. [self setTableViewHeader];
  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 = [tableMetadata new];
  837. (void)[[NCNetworking sharedInstance] convertFiles:files urlString:appDelegate.activeUrl serverUrl:self.serverUrl user:appDelegate.activeUser metadataFolder:&metadataFolder];
  838. // Rich Workspace
  839. [[NCManageDatabase sharedInstance] setDirectoryWithOcId:metadataFolder.ocId serverUrl:self.serverUrl richWorkspace:metadataFolder.richWorkspace account:account];
  840. self.richWorkspace = metadataFolder.richWorkspace;
  841. [self setTableViewHeader];
  842. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", account, metadataFolder.serverUrl]];
  843. // Read folder: No record, Change etag or BLINK
  844. if ([sectionDataSource.allRecordsDataSource count] == 0 || [metadataFolder.etag isEqualToString:directory.etag] == NO || self.blinkFileNamePath != nil) {
  845. [self readFolder:self.serverUrl];
  846. }
  847. } else if (errorCode != 0) {
  848. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorMessage delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  849. } else {
  850. NSLog(@"[LOG] It has been changed user during networking process, error.");
  851. }
  852. }];
  853. }
  854. #pragma --------------------------------------------------------------------------------------------
  855. #pragma mark ==== Read Folder ====
  856. #pragma --------------------------------------------------------------------------------------------
  857. - (void)insertMetadatasWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl metadataFolder:(tableMetadata *)metadataFolder metadatas:(NSArray *)metadatas
  858. {
  859. // stoprefresh
  860. [refreshControl endRefreshing];
  861. // save metadataFolder
  862. _metadataFolder = metadataFolder;
  863. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  864. if (tableAccount == nil) {
  865. return;
  866. }
  867. if (self.searchController.isActive == NO) {
  868. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:serverUrl serverUrlTo:nil etag:metadataFolder.etag ocId:metadataFolder.ocId encrypted:metadataFolder.e2eEncrypted richWorkspace:nil account:account];
  869. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND (status == %d OR status == %d)", account, serverUrl, k_metadataStatusNormal, k_metadataStatusHide]];
  870. [[NCManageDatabase sharedInstance] setDateReadDirectoryWithServerUrl:serverUrl account:account];
  871. }
  872. 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];
  873. // insert in Database
  874. NSMutableArray *metadatasToInsertInDB = (NSMutableArray *)[[NCManageDatabase sharedInstance] addMetadatas:metadatas];
  875. // insert in Database the /
  876. if (metadataFolder != nil) {
  877. _metadataFolder = [[NCManageDatabase sharedInstance] addMetadata:metadataFolder];
  878. }
  879. // reinsert metadatas in Download
  880. if (metadatasInDownload) {
  881. (void)[[NCManageDatabase sharedInstance] addMetadatas:metadatasInDownload];
  882. }
  883. // File is changed ??
  884. if (!self.searchController.isActive && metadatasToInsertInDB) {
  885. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  886. [[CCSynchronize sharedSynchronize] verifyChangeMedatas:metadatasToInsertInDB serverUrl:serverUrl account:account withDownload:NO];
  887. });
  888. }
  889. // Search Mode
  890. if (self.searchController.isActive) {
  891. // Fix managed -> Unmanaged _searchResultMetadatas
  892. if (metadatasToInsertInDB)
  893. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatasToInsertInDB];
  894. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:serverUrl ocId:nil action:k_action_NULL];
  895. }
  896. // this is the same directory
  897. if ([serverUrl isEqualToString:_serverUrl] && !self.searchController.isActive) {
  898. // reload
  899. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:serverUrl ocId:nil action:k_action_NULL];
  900. [self tableViewReloadData];
  901. }
  902. // E2EE Is encrypted folder get metadata
  903. if (_metadataFolder.e2eEncrypted) {
  904. NSString *metadataFolderocId = metadataFolder.ocId;
  905. // Read Metadata
  906. if ([CCUtility isEndToEndEnabled:account]) {
  907. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  908. NSString *metadata;
  909. NSError *error = [[NCNetworkingEndToEnd sharedManager] getEndToEndMetadata:&metadata ocId:metadataFolderocId user:tableAccount.user userID:tableAccount.userID password:[CCUtility getPassword:tableAccount.account] url:tableAccount.url];
  910. dispatch_async(dispatch_get_main_queue(), ^{
  911. if (error) {
  912. if (error.code != kOCErrorServerPathNotFound)
  913. [[NCContentPresenter shared] messageNotification:@"_e2e_error_get_metadata_" description:error.localizedDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  914. } else {
  915. if ([[NCEndToEndMetadata sharedInstance] decoderMetadata:metadata privateKey:[CCUtility getEndToEndPrivateKey:account] serverUrl:self.serverUrl account:account url:tableAccount.url] == false)
  916. [[NCContentPresenter shared] messageNotification:@"_error_e2ee_" description:@"_e2e_error_decode_metadata_" delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  917. else
  918. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:serverUrl ocId:nil action:k_action_NULL];
  919. }
  920. });
  921. });
  922. } else {
  923. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  924. }
  925. }
  926. // rewrite title
  927. [self setTitle];
  928. }
  929. - (void)readFolder:(NSString *)serverUrl
  930. {
  931. // init control
  932. if (!serverUrl || !appDelegate.activeAccount || appDelegate.maintenanceMode) {
  933. [refreshControl endRefreshing];
  934. return;
  935. }
  936. // Search Mode
  937. if (self.searchController.isActive) {
  938. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrl account:appDelegate.activeAccount];
  939. _searchFileName = @""; // forced reload searchg
  940. [self updateSearchResultsForSearchController:self.searchController];
  941. return;
  942. }
  943. _loadingFolder = YES;
  944. [self tableViewReloadData];
  945. [[OCNetworking sharedManager] readFolderWithAccount:appDelegate.activeAccount serverUrl:serverUrl depth:@"1" completion:^(NSString *account, NSArray *metadatas, tableMetadata *metadataFolder, NSString *message, NSInteger errorCode) {
  946. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount]) {
  947. [self insertMetadatasWithAccount:account serverUrl:serverUrl metadataFolder:metadataFolder metadatas:metadatas];
  948. } else if (errorCode != 0) {
  949. [[NCContentPresenter shared] messageNotification:@"_error_" description:message delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  950. } else {
  951. NSLog(@"[LOG] It has been changed user during networking process, error.");
  952. }
  953. _loadingFolder = NO;
  954. }];
  955. }
  956. #pragma mark -
  957. #pragma --------------------------------------------------------------------------------------------
  958. #pragma mark ===== Search =====
  959. #pragma --------------------------------------------------------------------------------------------
  960. - (void)searchEnabled:(BOOL)enabled
  961. {
  962. if (enabled) {
  963. if (self.tableView.tableHeaderView != nil)
  964. return;
  965. self.definesPresentationContext = YES;
  966. self.searchController.searchResultsUpdater = self;
  967. self.searchController.dimsBackgroundDuringPresentation = NO;
  968. self.searchController.searchBar.translucent = NO;
  969. [self.searchController.searchBar sizeToFit];
  970. self.searchController.searchBar.delegate = self;
  971. self.searchController.searchBar.barTintColor = NCBrandColor.sharedInstance.brand;
  972. self.searchController.searchBar.backgroundColor = NCBrandColor.sharedInstance.brand;
  973. self.searchController.searchBar.backgroundImage = [UIImage new];
  974. // color searchbbar button text (cancel)
  975. UIButton *searchButton = self.searchController.searchBar.subviews.firstObject.subviews.lastObject;
  976. if (searchButton && [searchButton isKindOfClass:[UIButton class]]) {
  977. [searchButton setTitleColor:NCBrandColor.sharedInstance.brandText forState:UIControlStateNormal];
  978. }
  979. // color textview searchbbar
  980. UITextField *searchTextView = [self.searchController.searchBar valueForKey:@"searchField"];
  981. if (searchTextView && [searchTextView isKindOfClass:[UITextField class]]) {
  982. searchTextView.backgroundColor = NCBrandColor.sharedInstance.backgroundForm;
  983. searchTextView.textColor = NCBrandColor.sharedInstance.textView;
  984. }
  985. self.tableView.tableHeaderView = self.searchController.searchBar;
  986. [self.tableView setContentOffset:CGPointMake(0, self.searchController.searchBar.frame.size.height - self.tableView.contentOffset.y)];
  987. } else {
  988. self.tableView.tableHeaderView = nil;
  989. }
  990. }
  991. - (void)searchStartTimer
  992. {
  993. if (self.searchController.isActive == false) {
  994. return;
  995. }
  996. NSString *startDirectory = [CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl];
  997. [[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) {
  998. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount]) {
  999. #if TARGET_OS_SIMULATOR
  1000. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilitesWithAccount:account];
  1001. if (capabilities.isFulltextsearchEnabled) {
  1002. [[OCNetworking sharedManager] fullTextSearchWithAccount:appDelegate.activeAccount text:_searchFileName page:1 completion:^(NSString *account, NSArray *items, NSString *message, NSInteger errorCode) {
  1003. NSLog(@"x");
  1004. }];
  1005. }
  1006. #endif
  1007. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatas];
  1008. [self insertMetadatasWithAccount:appDelegate.activeAccount serverUrl:_serverUrl metadataFolder:nil metadatas:_searchResultMetadatas];
  1009. } else {
  1010. if (errorCode != 0) {
  1011. [[NCContentPresenter shared] messageNotification:@"_error_" description:message delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  1012. } else {
  1013. NSLog(@"[LOG] It has been changed user during networking process, error.");
  1014. }
  1015. _searchFileName = @"";
  1016. }
  1017. }];
  1018. _noFilesSearchTitle = @"";
  1019. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  1020. [self.tableView reloadEmptyDataSet];
  1021. }
  1022. - (void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1023. {
  1024. // Color text "Cancel"
  1025. [[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTintColor:NCBrandColor.sharedInstance.brandText];
  1026. if (searchController.isActive) {
  1027. [self deleteRefreshControl];
  1028. NSString *fileName = [CCUtility removeForbiddenCharactersServer:searchController.searchBar.text];
  1029. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1030. _searchFileName = fileName;
  1031. // First : filter
  1032. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileNameView CONTAINS[cd] %@", appDelegate.activeAccount, _serverUrl, fileName] sorted:nil ascending:NO];
  1033. [_searchResultMetadatas removeAllObjects];
  1034. for (tableMetadata *record in records)
  1035. [_searchResultMetadatas addObject:record];
  1036. [self insertMetadatasWithAccount:appDelegate.activeAccount serverUrl:_serverUrl metadataFolder:nil metadatas:_searchResultMetadatas];
  1037. // Version >= 12
  1038. if ([[NCManageDatabase sharedInstance] getServerVersionWithAccount:appDelegate.activeAccount] >= 12) {
  1039. [_timerWaitInput invalidate];
  1040. _timerWaitInput = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(searchStartTimer) userInfo:nil repeats:NO];
  1041. }
  1042. }
  1043. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1044. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1045. }
  1046. } else {
  1047. [self createRefreshControl];
  1048. [self reloadDatasource:self.serverUrl ocId:nil action:k_action_NULL];
  1049. }
  1050. }
  1051. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1052. {
  1053. [self cancelSearchBar];
  1054. }
  1055. - (void)cancelSearchBar
  1056. {
  1057. if (self.searchController.active) {
  1058. [self.searchController setActive:NO];
  1059. _searchFileName = @"";
  1060. _dateReadDataSource = nil;
  1061. _searchResultMetadatas = [NSMutableArray new];
  1062. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1063. }
  1064. //[self setNeedsStatusBarAppearanceUpdate];
  1065. }
  1066. #pragma mark -
  1067. #pragma --------------------------------------------------------------------------------------------
  1068. #pragma mark ===== Delete File or Folder =====
  1069. #pragma --------------------------------------------------------------------------------------------
  1070. - (void)deleteFile
  1071. {
  1072. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  1073. return;
  1074. NSArray *metadatas;
  1075. if ([_selectedocIdsMetadatas count] > 0) {
  1076. metadatas = [_selectedocIdsMetadatas allValues];
  1077. } else {
  1078. metadatas = [[NSArray alloc] initWithObjects:self.metadata, nil];
  1079. }
  1080. // remove optimization
  1081. _dateReadDataSource = nil;
  1082. [[NCMainCommon sharedInstance ] deleteFileWithMetadatas:metadatas e2ee:_metadataFolder.e2eEncrypted serverUrl:self.serverUrl folderocId:_metadataFolder.ocId completion:^(NSInteger errorCode, NSString *message) {
  1083. // Reload
  1084. if (self.searchController.isActive)
  1085. [self readFolder:self.serverUrl];
  1086. else
  1087. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1088. }];
  1089. // End Select Table View
  1090. [self tableViewSelect:NO];
  1091. }
  1092. #pragma --------------------------------------------------------------------------------------------
  1093. #pragma mark ===== Rename =====
  1094. #pragma --------------------------------------------------------------------------------------------
  1095. - (void)renameFile:(NSArray *)arguments
  1096. {
  1097. tableMetadata *metadata = [arguments objectAtIndex:0];
  1098. NSString *fileName = [arguments objectAtIndex:1];
  1099. // E2EE
  1100. if (_metadataFolder.e2eEncrypted) {
  1101. // verify if exists the new fileName
  1102. if ([[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileName == %@", appDelegate.activeAccount, self.serverUrl, fileName]]) {
  1103. [[NCContentPresenter shared] messageNotification:@"_error_e2ee_" description:@"_file_already_exists_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  1104. return;
  1105. }
  1106. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  1107. 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];
  1108. if (error) {
  1109. [[NCContentPresenter shared] messageNotification:@"_error_e2ee_" description:@"_e2e_error_send_metadata_" delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  1110. } else {
  1111. [[NCManageDatabase sharedInstance] setMetadataFileNameViewWithServerUrl:metadata.serverUrl fileName:metadata.fileName newFileNameView:fileName account:appDelegate.activeAccount];
  1112. // Move file system
  1113. NSString *atPath = [NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorageOcId:metadata.ocId], metadata.fileNameView];
  1114. NSString *toPath = [NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorageOcId:metadata.ocId], fileName];
  1115. [[NSFileManager defaultManager] moveItemAtPath:atPath toPath:toPath error:nil];
  1116. [[NSFileManager defaultManager] moveItemAtPath:[CCUtility getDirectoryProviderStorageIconOcId:metadata.ocId fileNameView:metadata.fileNameView] toPath:[CCUtility getDirectoryProviderStorageIconOcId:metadata.ocId fileNameView:fileName] error:nil];
  1117. }
  1118. // Unlock
  1119. tableE2eEncryptionLock *tableLock = [[NCManageDatabase sharedInstance] getE2ETokenLockWithServerUrl:self.serverUrl];
  1120. if (tableLock != nil) {
  1121. 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];
  1122. if (error) {
  1123. [[NCContentPresenter shared] messageNotification:@"_e2e_error_unlock_" description:error.localizedDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  1124. }
  1125. }
  1126. dispatch_async(dispatch_get_main_queue(), ^{
  1127. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1128. });
  1129. });
  1130. } else {
  1131. // verify permission
  1132. BOOL permission = [[NCUtility sharedInstance] permissionsContainsString:metadata.permissions permissions:k_permission_can_rename];
  1133. if (![metadata.permissions isEqualToString:@""] && permission == false) {
  1134. [[NCContentPresenter shared] messageNotification:@"_error_" description:@"_no_permission_modify_file_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  1135. return;
  1136. }
  1137. // Plain
  1138. NSString *fileNameNew = [CCUtility removeForbiddenCharactersServer:fileName];
  1139. if ([fileName length] == 0 || [fileName isEqualToString:metadata.fileNameView]) {
  1140. return;
  1141. }
  1142. // Verify if exists the fileName TO
  1143. [[OCNetworking sharedManager] readFileWithAccount:appDelegate.activeAccount serverUrl:metadata.serverUrl fileName:fileNameNew completion:^(NSString *account, tableMetadata *metadataReadFile, NSString *message, NSInteger errorCode) {
  1144. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount]) {
  1145. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1146. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) { }];
  1147. [alert addAction:ok];
  1148. [self presentViewController:alert animated:YES completion:nil];
  1149. } else if (errorCode != 0) {
  1150. if (errorCode == kOCErrorServerPathNotFound) {
  1151. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@", metadata.serverUrl, metadata.fileName];
  1152. NSString *fileNameToPath = [NSString stringWithFormat:@"%@/%@", metadata.serverUrl, fileNameNew];
  1153. [[OCNetworking sharedManager] moveFileOrFolderWithAccount:appDelegate.activeAccount fileName:fileNamePath fileNameTo:fileNameToPath completion:^(NSString *account, NSString *message, NSInteger errorCode) {
  1154. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount]) {
  1155. // Rename metadata
  1156. (void) [[NCManageDatabase sharedInstance] renameMetadataWithFileNameTo:fileNameNew ocId:metadata.ocId];
  1157. if (metadata.directory) {
  1158. NSString *serverUrl = [CCUtility stringAppendServerUrl:metadata.serverUrl addFileName:metadata.fileName];
  1159. NSString *serverUrlTo = [CCUtility stringAppendServerUrl:metadata.serverUrl addFileName:fileNameNew];
  1160. tableDirectory *directoryTable = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", account, metadata.serverUrl]];
  1161. if (directoryTable == nil) {
  1162. [[NCContentPresenter shared] messageNotification:@"_rename_" description:@"Internal error, ServerUrl not found" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  1163. return;
  1164. }
  1165. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:serverUrl serverUrlTo:serverUrlTo etag:@"" ocId:nil encrypted:directoryTable.e2eEncrypted richWorkspace:nil account:appDelegate.activeAccount];
  1166. } else {
  1167. [[NCManageDatabase sharedInstance] setLocalFileWithOcId:metadata.ocId date:nil exifDate:nil exifLatitude:nil exifLongitude:nil fileName:fileNameNew etag:nil];
  1168. // Move file system
  1169. NSString *atPath = [NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorageOcId:metadata.ocId], metadata.fileName];
  1170. NSString *toPath = [NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorageOcId:metadata.ocId], fileNameNew];
  1171. [[NSFileManager defaultManager] moveItemAtPath:atPath toPath:toPath error:nil];
  1172. NSString *atPathIcon = [CCUtility getDirectoryProviderStorageIconOcId:metadata.ocId fileNameView:metadata.fileName];
  1173. NSString *toPathIcon = [CCUtility getDirectoryProviderStorageIconOcId:metadata.ocId fileNameView:fileNameNew];
  1174. [[NSFileManager defaultManager] moveItemAtPath:atPathIcon toPath:toPathIcon error:nil];
  1175. }
  1176. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:metadata.serverUrl ocId:metadata.ocId action:k_action_MOD];
  1177. } else if (errorCode != 0) {
  1178. [[NCContentPresenter shared] messageNotification:@"_rename_" description:message delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  1179. } else {
  1180. NSLog(@"[LOG] It has been changed user during networking process, error.");
  1181. }
  1182. }];
  1183. } else {
  1184. [[NCContentPresenter shared] messageNotification:@"_error_" description:message delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  1185. }
  1186. } else {
  1187. NSLog(@"[LOG] It has been changed user during networking process, error.");
  1188. }
  1189. }];
  1190. }
  1191. }
  1192. #pragma --------------------------------------------------------------------------------------------
  1193. #pragma mark ===== Move =====
  1194. #pragma --------------------------------------------------------------------------------------------
  1195. - (void)moveFileOrFolderMetadata:(tableMetadata *)metadata serverUrlTo:(NSString *)serverUrlTo numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  1196. {
  1197. // verify permission
  1198. BOOL permission = [[NCUtility sharedInstance] permissionsContainsString:metadata.permissions permissions:k_permission_can_move];
  1199. if (![metadata.permissions isEqualToString:@""] && permission == false) {
  1200. [[NCContentPresenter shared] messageNotification:@"_error_" description:@"_no_permission_modify_file_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  1201. return;
  1202. }
  1203. [[OCNetworking sharedManager] readFileWithAccount:appDelegate.activeAccount serverUrl:serverUrlTo fileName:metadata.fileName completion:^(NSString *account, tableMetadata *metadataReadFile, NSString *message, NSInteger errorCode) {
  1204. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount]) {
  1205. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1206. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1207. }];
  1208. [alert addAction:ok];
  1209. [self presentViewController:alert animated:YES completion:nil];
  1210. // End Select Table View
  1211. [self tableViewSelect:NO];
  1212. // reload Datasource
  1213. [self readFileReloadFolder];
  1214. } else if (errorCode != 0) {
  1215. if (errorCode == kOCErrorServerPathNotFound) {
  1216. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@", metadata.serverUrl, metadata.fileName];
  1217. NSString *fileNameToPath = [NSString stringWithFormat:@"%@/%@", serverUrlTo, metadata.fileName];
  1218. [[OCNetworking sharedManager] moveFileOrFolderWithAccount:appDelegate.activeAccount fileName:fileNamePath fileNameTo:fileNameToPath completion:^(NSString *account, NSString *message, NSInteger errorCode) {
  1219. [_hud hideHud];
  1220. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount]) {
  1221. if (metadata.directory) {
  1222. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:[CCUtility stringAppendServerUrl:metadata.serverUrl addFileName:metadata.fileName] account:account];
  1223. }
  1224. [[NCManageDatabase sharedInstance] moveMetadataWithOcId:metadata.ocId serverUrlTo:serverUrlTo];
  1225. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:metadata.serverUrl account:account];
  1226. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrlTo account:account];
  1227. // next
  1228. [_selectedocIdsMetadatas removeObjectForKey:metadata.ocId];
  1229. if ([_selectedocIdsMetadatas count] > 0) {
  1230. NSArray *metadatas = [_selectedocIdsMetadatas allValues];
  1231. [self moveFileOrFolderMetadata:[metadatas objectAtIndex:0] serverUrlTo:serverUrlTo numFile:[_selectedocIdsMetadatas count] ofFile:_numSelectedocIdsMetadatas];
  1232. } else {
  1233. // End Select Table View
  1234. [self tableViewSelect:NO];
  1235. // reload Datasource
  1236. if (self.searchController.isActive)
  1237. [self readFolder:metadata.serverUrl];
  1238. else
  1239. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1240. }
  1241. } else if (errorCode != 0) {
  1242. [[NCContentPresenter shared] messageNotification:@"_move_" description:message delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  1243. // End Select Table View
  1244. [self tableViewSelect:NO];
  1245. // reload Datasource
  1246. if (self.searchController.isActive)
  1247. [self readFolder:metadata.serverUrl];
  1248. else
  1249. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:metadata.serverUrl ocId:nil action:k_action_NULL];
  1250. } else {
  1251. NSLog(@"[LOG] It has been changed user during networking process, error.");
  1252. }
  1253. }];
  1254. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_move_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1255. } else {
  1256. [[NCContentPresenter shared] messageNotification:@"_error_" description:message delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  1257. }
  1258. } else {
  1259. NSLog(@"[LOG] It has been changed user during networking process, error.");
  1260. }
  1261. }];
  1262. }
  1263. // DELEGATE : Select
  1264. - (void)dismissSelectWithServerUrl:(NSString *)serverUrl metadata:(tableMetadata *)metadata type:(NSString *)type
  1265. {
  1266. if (serverUrl == nil) {
  1267. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1268. } else {
  1269. // E2EE DENIED
  1270. if ([CCUtility isFolderEncrypted:serverUrl account:appDelegate.activeAccount]) {
  1271. [[NCContentPresenter shared] messageNotification:@"_move_" description:@"Not possible move files to encrypted directory" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  1272. return;
  1273. }
  1274. if ([_selectedocIdsMetadatas count] > 0) {
  1275. _numSelectedocIdsMetadatas = [_selectedocIdsMetadatas count];
  1276. NSArray *metadatas = [_selectedocIdsMetadatas allValues];
  1277. [self moveFileOrFolderMetadata:[metadatas objectAtIndex:0] serverUrlTo:serverUrl numFile:[_selectedocIdsMetadatas count] ofFile:_numSelectedocIdsMetadatas];
  1278. } else {
  1279. _numSelectedocIdsMetadatas = 1;
  1280. [self moveFileOrFolderMetadata:self.metadata serverUrlTo:serverUrl numFile:1 ofFile:_numSelectedocIdsMetadatas];
  1281. }
  1282. }
  1283. }
  1284. - (void)moveOpenWindow:(NSArray *)indexPaths
  1285. {
  1286. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  1287. return;
  1288. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"NCSelect" bundle:nil] instantiateInitialViewController];
  1289. NCSelect *viewController = (NCSelect *)navigationController.topViewController;
  1290. viewController.delegate = self;
  1291. viewController.hideButtonCreateFolder = false;
  1292. viewController.selectFile = false;
  1293. viewController.includeDirectoryE2EEncryption = false;
  1294. viewController.includeImages = false;
  1295. viewController.type = @"";
  1296. viewController.titleButtonDone = NSLocalizedString(@"_move_", nil);
  1297. viewController.layoutViewSelect = k_layout_view_move;
  1298. [navigationController setModalPresentationStyle:UIModalPresentationFullScreen];
  1299. [self presentViewController:navigationController animated:YES completion:nil];
  1300. }
  1301. #pragma --------------------------------------------------------------------------------------------
  1302. #pragma mark ===== Create folder =====
  1303. #pragma --------------------------------------------------------------------------------------------
  1304. - (void)createFolder
  1305. {
  1306. NSString *serverUrl = [appDelegate getTabBarControllerActiveServerUrl];
  1307. NSString *message;
  1308. UIAlertController *alertController;
  1309. if ([serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]]) {
  1310. message = @"/";
  1311. } else {
  1312. message = [serverUrl lastPathComponent];
  1313. }
  1314. alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_create_folder_on_",nil) message:message preferredStyle:UIAlertControllerStyleAlert];
  1315. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  1316. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  1317. textField.autocapitalizationType = UITextAutocapitalizationTypeSentences;
  1318. }];
  1319. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  1320. NSLog(@"[LOG] Cancel action");
  1321. }];
  1322. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  1323. UITextField *fileName = alertController.textFields.firstObject;
  1324. [self createFolder:fileName.text serverUrl:serverUrl];
  1325. }];
  1326. okAction.enabled = NO;
  1327. [alertController addAction:cancelAction];
  1328. [alertController addAction:okAction];
  1329. [self presentViewController:alertController animated:YES completion:nil];
  1330. }
  1331. - (void)createFolder:(NSString *)fileNameFolder serverUrl:(NSString *)serverUrl
  1332. {
  1333. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1334. fileNameFolder = [[NCUtility sharedInstance] createFileName:fileNameFolder serverUrl:self.serverUrl account:appDelegate.activeAccount];
  1335. if (![fileNameFolder length]) return;
  1336. NSString *ocIdTemp = [[NSUUID UUID] UUIDString];
  1337. // Create Directory (temp) on metadata
  1338. 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:@""];
  1339. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1340. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrl account:appDelegate.activeAccount];
  1341. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1342. // Creeate folder Networking
  1343. [[OCNetworking sharedManager] createFolderWithAccount:appDelegate.activeAccount serverUrl:serverUrl fileName:fileNameFolder completion:^(NSString *account, NSString *ocId, NSDate *date, NSString *message, NSInteger errorCode) {
  1344. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount]) {
  1345. // Delete Temp Dir
  1346. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocIdTemp]];
  1347. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrl, fileNameFolder];
  1348. if (_metadataFolder.e2eEncrypted) {
  1349. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1350. NSError *error = [[NCNetworkingEndToEnd sharedManager] markEndToEndFolderEncryptedOnServerUrl:newDirectory ocId:ocId user:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl];
  1351. dispatch_async(dispatch_get_main_queue(), ^{
  1352. if (error) {
  1353. [[NCContentPresenter shared] messageNotification:@"_e2e_error_mark_folder_" description:error.localizedDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  1354. }
  1355. [self readFolder:self.serverUrl];
  1356. });
  1357. });
  1358. } else {
  1359. [self readFolder:self.serverUrl];
  1360. }
  1361. } else {
  1362. // Delete Temp Dir
  1363. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocIdTemp]];
  1364. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1365. if (errorCode != 0) {
  1366. [[NCContentPresenter shared] messageNotification:@"_create_folder_" description:message delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  1367. } else {
  1368. NSLog(@"[LOG] It has been changed user during networking process, error.");
  1369. }
  1370. }
  1371. }];
  1372. }
  1373. #pragma --------------------------------------------------------------------------------------------
  1374. #pragma mark ===== Progress & Task Button =====
  1375. #pragma --------------------------------------------------------------------------------------------
  1376. - (void)triggerProgressTask:(NSNotification *)notification
  1377. {
  1378. if (sectionDataSource.ocIdIndexPath != nil) {
  1379. [[NCMainCommon sharedInstance] triggerProgressTask:notification sectionDataSourceocIdIndexPath:sectionDataSource.ocIdIndexPath tableView:self.tableView viewController:self serverUrlViewController:self.serverUrl];
  1380. }
  1381. }
  1382. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  1383. {
  1384. UITouch *touch = [[event allTouches] anyObject];
  1385. CGPoint location = [touch locationInView:self.tableView];
  1386. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1387. if ([self indexPathIsValid:indexPath]) {
  1388. tableMetadata *metadataSection = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1389. if (metadataSection) {
  1390. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadataSection.ocId]];
  1391. if (metadata)
  1392. [[NCMainCommon sharedInstance] cancelTransferMetadata:metadata reloadDatasource:true uploadStatusForcedStart:false];
  1393. }
  1394. }
  1395. }
  1396. - (void)cancelAllTask:(id)sender
  1397. {
  1398. CGPoint location = [sender locationInView:self.tableView];
  1399. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1400. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  1401. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_all_task_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  1402. [NCUtility.sharedInstance startActivityIndicatorWithView:self.view bottom:0];
  1403. [[NCMainCommon sharedInstance] cancelAllTransfer];
  1404. [NCUtility.sharedInstance stopActivityIndicator];
  1405. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:nil ocId:nil action:k_action_NULL];
  1406. }]];
  1407. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { }]];
  1408. alertController.popoverPresentationController.sourceView = self.tableView;
  1409. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  1410. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  1411. [alertController.view layoutIfNeeded];
  1412. [self presentViewController:alertController animated:YES completion:nil];
  1413. }
  1414. #pragma --------------------------------------------------------------------------------------------
  1415. #pragma mark ===== Tap =====
  1416. #pragma --------------------------------------------------------------------------------------------
  1417. - (void)tapActionComment:(UITapGestureRecognizer *)tapGesture
  1418. {
  1419. CGPoint location = [tapGesture locationInView:self.tableView];
  1420. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1421. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1422. if (metadata) {
  1423. [[NCMainCommon sharedInstance] openShareWithViewController:self metadata:metadata indexPage:1];
  1424. }
  1425. }
  1426. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  1427. {
  1428. CGPoint location = [tapGesture locationInView:self.tableView];
  1429. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1430. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1431. if (metadata) {
  1432. [[NCMainCommon sharedInstance] openShareWithViewController:self metadata:metadata indexPage:2];
  1433. }
  1434. }
  1435. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  1436. {
  1437. CGPoint location = [tapGesture locationInView:self.tableView];
  1438. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1439. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1440. if (metadata) {
  1441. }
  1442. }
  1443. #pragma --------------------------------------------------------------------------------------------
  1444. #pragma mark ===== Rich Workspace =====
  1445. #pragma --------------------------------------------------------------------------------------------
  1446. - (void)viewRichWorkspaceTapAction:(UITapGestureRecognizer *)tapGesture
  1447. {
  1448. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"NCViewerRichWorkspace" bundle:nil] instantiateInitialViewController];
  1449. NCViewerRichWorkspace *viewerRichWorkspace = (NCViewerRichWorkspace *)[navigationController topViewController];
  1450. viewerRichWorkspace.richWorkspace = self.richWorkspace;
  1451. viewerRichWorkspace.serverUrl = self.serverUrl;
  1452. navigationController.modalPresentationStyle = UIModalPresentationFullScreen;
  1453. [self presentViewController:navigationController animated:NO completion:NULL];
  1454. }
  1455. - (void)createRichWorkspace
  1456. {
  1457. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileNameView LIKE[c] %@", appDelegate.activeAccount, self.serverUrl, k_fileNameRichWorkspace.lowercaseString]];
  1458. if (metadata && [[NCUtility sharedInstance] isDirectEditing:metadata]) {
  1459. if (appDelegate.reachability.isReachable) {
  1460. [self shouldPerformSegue:metadata selector:@""];
  1461. } else {
  1462. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_go_online_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  1463. }
  1464. } else if (metadata == nil) {
  1465. NSString *fileNamePath = [CCUtility returnFileNamePathFromFileName:k_fileNameRichWorkspace serverUrl:self.serverUrl activeUrl:appDelegate.activeUrl];
  1466. [[NCCommunication sharedInstance] NCTextCreateFileWithUrlString:appDelegate.activeUrl fileNamePath:fileNamePath editor:@"text" templateId:@"" account:appDelegate.activeAccount completionHandler:^(NSString *account, NSString *url, NSInteger errorCode, NSString *errorMessage) {
  1467. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount]) {
  1468. tableMetadata *metadata = [CCUtility createMetadataWithAccount:appDelegate.activeAccount date:[NSDate date] directory:false ocId:[CCUtility createRandomString:12] serverUrl:self.serverUrl fileName:k_fileNameRichWorkspace etag:@"" size:0 status:k_metadataStatusNormal url:url contentType:@"text/markdown"];
  1469. [self shouldPerformSegue:metadata selector:@""];
  1470. } else if (errorCode != 0) {
  1471. [NCContentPresenter.shared messageNotification:@"_error_" description:errorMessage delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  1472. } else {
  1473. NSLog(@"[LOG] It has been changed user during networking process, error.");
  1474. }
  1475. }];
  1476. }
  1477. }
  1478. #pragma --------------------------------------------------------------------------------------------
  1479. #pragma mark ===== Favorite =====
  1480. #pragma --------------------------------------------------------------------------------------------
  1481. - (void)settingFavorite:(tableMetadata *)metadata favorite:(BOOL)favorite
  1482. {
  1483. NSString *fileNameServerUrl = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:self.serverUrl activeUrl:appDelegate.activeUrl];
  1484. [[NCCommunication sharedInstance] setFavoriteWithUrlString:appDelegate.activeUrl fileName:fileNameServerUrl favorite:favorite account:appDelegate.activeAccount completionHandler:^(NSString *account, NSInteger errorCode, NSString *errorDecription) {
  1485. if (errorCode == 0 && [appDelegate.activeAccount isEqualToString:account]) {
  1486. [[NCManageDatabase sharedInstance] setMetadataFavoriteWithOcId:metadata.ocId favorite:favorite];
  1487. _dateReadDataSource = nil;
  1488. if (self.searchController.isActive)
  1489. [self readFolder:self.serverUrl];
  1490. else
  1491. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:metadata.ocId action:k_action_MOD];
  1492. if (metadata.directory && favorite) {
  1493. NSString *selector;
  1494. if ([CCUtility getFavoriteOffline])
  1495. selector = selectorReadFolderWithDownload;
  1496. else
  1497. selector = selectorReadFolder;
  1498. [[CCSynchronize sharedSynchronize] readFolder:[CCUtility stringAppendServerUrl:self.serverUrl addFileName:metadata.fileName] selector:selector account:appDelegate.activeAccount];
  1499. }
  1500. if (!metadata.directory && favorite && [CCUtility getFavoriteOffline]) {
  1501. metadata.favorite = favorite;
  1502. metadata.session = k_download_session;
  1503. metadata.sessionError = @"";
  1504. metadata.sessionSelector = selectorDownloadSynchronize;
  1505. metadata.status = k_metadataStatusWaitDownload;
  1506. // Add Metadata for Download
  1507. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1508. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:metadata.ocId action:k_action_MOD];
  1509. [appDelegate startLoadAutoDownloadUpload];
  1510. }
  1511. } else if (errorCode != 0) {
  1512. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDecription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  1513. } else {
  1514. NSLog(@"[LOG] It has been changed user during networking process, error.");
  1515. }
  1516. }];
  1517. }
  1518. #pragma --------------------------------------------------------------------------------------------
  1519. #pragma mark ==== Menu LOGO ====
  1520. #pragma --------------------------------------------------------------------------------------------
  1521. - (void)menuLogo:(UIGestureRecognizer *)theGestureRecognizer
  1522. {
  1523. if (appDelegate.reSelectMenu.isOpen || appDelegate.reMainMenu.isOpen)
  1524. return;
  1525. // Brand
  1526. if ([NCBrandOptions sharedInstance].disable_multiaccount)
  1527. return;
  1528. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  1529. NSMutableArray *menuArray = [NSMutableArray new];
  1530. for (NSString *account in listAccount) {
  1531. CCMenuItem *item = [[CCMenuItem alloc] init];
  1532. item.title = [account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  1533. item.argument = account;
  1534. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ ", account]];
  1535. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@-%@.png", [CCUtility getDirectoryUserData], [CCUtility getStringUser:tableAccount.user activeUrl:tableAccount.url], tableAccount.user];
  1536. UIImage *avatar = [UIImage imageWithContentsOfFile:fileNamePath];
  1537. if (avatar) {
  1538. avatar = [CCGraphics scaleImage:avatar toSize:CGSizeMake(25, 25) isAspectRation:YES];
  1539. CCAvatar *avatarImageView = [[CCAvatar alloc] initWithImage:avatar borderColor:[UIColor lightGrayColor] borderWidth:0.5];
  1540. CGSize imageSize = avatarImageView.bounds.size;
  1541. UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
  1542. CGContextRef context = UIGraphicsGetCurrentContext();
  1543. [avatarImageView.layer renderInContext:context];
  1544. avatar = UIGraphicsGetImageFromCurrentImageContext();
  1545. UIGraphicsEndImageContext();
  1546. } else {
  1547. avatar = [UIImage imageNamed:@"menuLogoUser"];
  1548. }
  1549. item.image = avatar;
  1550. item.target = self;
  1551. if ([account isEqualToString:appDelegate.activeAccount]) {
  1552. item.action = nil;
  1553. [menuArray insertObject:item atIndex:0];
  1554. } else {
  1555. item.action = @selector(changeDefaultAccount:);
  1556. [menuArray addObject:item];
  1557. }
  1558. }
  1559. // Add + new account
  1560. CCMenuItem *item = [[CCMenuItem alloc] init];
  1561. item.title = NSLocalizedString(@"_add_account_", nil);
  1562. item.argument = @"";
  1563. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"add"] width:50 height:50 color:NCBrandColor.sharedInstance.textView];
  1564. item.target = self;
  1565. item.action = @selector(addNewAccount:);
  1566. [menuArray addObject:item];
  1567. OptionalConfiguration options;
  1568. Color backgroundColor;
  1569. const CGFloat *componentsBackgroundColor = CGColorGetComponents(NCBrandColor.sharedInstance.backgroundForm.CGColor);
  1570. backgroundColor.R = componentsBackgroundColor[0];
  1571. backgroundColor.G = componentsBackgroundColor[1];
  1572. backgroundColor.B = componentsBackgroundColor[2];
  1573. options.arrowSize = 9;
  1574. options.marginXSpacing = 7;
  1575. options.marginYSpacing = 10;
  1576. options.intervalSpacing = 20;
  1577. options.menuCornerRadius = 6.5;
  1578. options.maskToBackground = NO;
  1579. options.shadowOfMenu = YES;
  1580. options.hasSeperatorLine = YES;
  1581. options.seperatorLineHasInsets = YES;
  1582. options.textColor = NCBrandColor.sharedInstance.textView;
  1583. options.menuBackgroundColor = backgroundColor;
  1584. options.separatorColor = NCBrandColor.sharedInstance.separator;
  1585. CGRect rect = self.view.frame;
  1586. CGFloat locationY = [theGestureRecognizer locationInView: self.navigationController.navigationBar].y;
  1587. CGFloat safeAreaTop = 0;
  1588. CGFloat offsetY = 35;
  1589. if (@available(iOS 11, *)) {
  1590. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top / 2;
  1591. }
  1592. rect.origin.y = locationY + safeAreaTop + offsetY;
  1593. rect.size.height = rect.size.height - locationY - safeAreaTop - offsetY;
  1594. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  1595. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  1596. }
  1597. - (void)changeDefaultAccount:(CCMenuItem *)sender
  1598. {
  1599. // LOGOUT
  1600. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:[sender argument]];
  1601. if (tableAccount) {
  1602. // LOGIN
  1603. [appDelegate settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activeUserID:tableAccount.userID activePassword:[CCUtility getPassword:tableAccount.account]];
  1604. // go to home sweet home
  1605. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initializeMain" object:nil userInfo:nil];
  1606. }
  1607. }
  1608. - (void)addNewAccount:(CCMenuItem *)sender
  1609. {
  1610. [appDelegate openLoginView:self selector:k_intro_login openLoginWeb:false];
  1611. }
  1612. #pragma --------------------------------------------------------------------------------------------
  1613. #pragma mark ==== ReMenu ====
  1614. #pragma --------------------------------------------------------------------------------------------
  1615. - (void)createReMenuBackgroundView:(REMenu *)menu
  1616. {
  1617. CGFloat safeAreaBottom = 0;
  1618. CGFloat safeAreaTop = 0;
  1619. CGFloat statusBar = 0;
  1620. if (@available(iOS 11, *)) {
  1621. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top;
  1622. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  1623. }
  1624. if ([UIApplication sharedApplication].isStatusBarHidden) {
  1625. statusBar = 13;
  1626. }
  1627. CGFloat computeNavigationBarOffset = [menu computeNavigationBarOffset];
  1628. UIViewController *rootController = [[[[UIApplication sharedApplication]delegate] window] rootViewController];
  1629. CGRect globalPositionMenu = [menu.menuView convertRect:menu.menuView.bounds toView:rootController.view];
  1630. _reMenuBackgroundView.frame = CGRectMake(0, computeNavigationBarOffset, globalPositionMenu.size.width, rootController.view.frame.size.height);
  1631. [UIView animateWithDuration:0.2 animations:^{
  1632. CGFloat minimum = safeAreaBottom + self.tabBarController.tabBar.frame.size.height;
  1633. CGFloat y = rootController.view.frame.size.height - menu.menuView.frame.size.height - globalPositionMenu.origin.y + statusBar;
  1634. if (y>minimum) {
  1635. _reMenuBackgroundView.frame = CGRectMake(0, rootController.view.frame.size.height, globalPositionMenu.size.width, - y);
  1636. [self.tabBarController.view addSubview:_reMenuBackgroundView];
  1637. }
  1638. }];
  1639. }
  1640. - (void)createReMainMenu
  1641. {
  1642. NSString *title;
  1643. //NSString *groupBy = [CCUtility getGroupBySettings];
  1644. NSString *sorted = [CCUtility getOrderSettings];
  1645. BOOL ascending = [CCUtility getAscendingSettings];
  1646. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilitesWithAccount:appDelegate.activeAccount];
  1647. // ITEM SELECT ----------------------------------------------------------------------------------------------------
  1648. 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) {
  1649. if ([sectionDataSource.allRecordsDataSource count] > 0) [self tableViewSelect:YES];
  1650. }];
  1651. // ITEM ORDER ----------------------------------------------------------------------------------------------------
  1652. if ([sorted isEqualToString:@"fileName"] && ascending) { title = [NSString stringWithFormat:@"✓ %@", NSLocalizedString(@"_order_by_name_a_z_", nil)]; }
  1653. else title = NSLocalizedString(@"_order_by_name_a_z_", nil);
  1654. appDelegate.sortFileNameAZItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"sortFileNameAZ"] multiplier:2 color:NCBrandColor.sharedInstance.icon] highlightedImage:nil action:^(REMenuItem *item) {
  1655. [CCUtility setOrderSettings:@"fileName"];
  1656. [CCUtility setAscendingSettings:true];
  1657. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1658. }];
  1659. if ([sorted isEqualToString:@"fileName"] && !ascending) { title = [NSString stringWithFormat:@"✓ %@", NSLocalizedString(@"_order_by_name_z_a_", nil)]; }
  1660. else title = NSLocalizedString(@"_order_by_name_z_a_", nil);
  1661. appDelegate.sortFileNameZAItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"sortFileNameZA"] multiplier:2 color:NCBrandColor.sharedInstance.icon] highlightedImage:nil action:^(REMenuItem *item) {
  1662. [CCUtility setOrderSettings:@"fileName"];
  1663. [CCUtility setAscendingSettings:false];
  1664. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1665. }];
  1666. if ([sorted isEqualToString:@"date"] && !ascending) { title = [NSString stringWithFormat:@"✓ %@", NSLocalizedString(@"_order_by_date_more_recent_", nil)]; }
  1667. else title = NSLocalizedString(@"_order_by_date_more_recent_", nil);
  1668. appDelegate.sortDateMoreRecentItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"sortDateMoreRecent"] multiplier:2 color:NCBrandColor.sharedInstance.icon] highlightedImage:nil action:^(REMenuItem *item) {
  1669. [CCUtility setOrderSettings:@"date"];
  1670. [CCUtility setAscendingSettings:false];
  1671. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1672. }];
  1673. if ([sorted isEqualToString:@"date"] && ascending) { title = [NSString stringWithFormat:@"✓ %@", NSLocalizedString(@"_order_by_date_less_recent_", nil)]; }
  1674. else title = NSLocalizedString(@"_order_by_date_less_recent_", nil);
  1675. appDelegate.sortDateLessRecentItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"sortDateLessRecent"] multiplier:2 color:NCBrandColor.sharedInstance.icon] highlightedImage:nil action:^(REMenuItem *item) {
  1676. [CCUtility setOrderSettings:@"date"];
  1677. [CCUtility setAscendingSettings:true];
  1678. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1679. }];
  1680. if ([sorted isEqualToString:@"size"] && ascending) { title = [NSString stringWithFormat:@"✓ %@", NSLocalizedString(@"_order_by_size_smallest_", nil)]; }
  1681. else title = NSLocalizedString(@"_order_by_size_smallest_", nil);
  1682. appDelegate.sortSmallestItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"sortSmallest"] multiplier:2 color:NCBrandColor.sharedInstance.icon] highlightedImage:nil action:^(REMenuItem *item) {
  1683. [CCUtility setOrderSettings:@"size"];
  1684. [CCUtility setAscendingSettings:true];
  1685. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1686. }];
  1687. if ([sorted isEqualToString:@"size"] && !ascending) { title = [NSString stringWithFormat:@"✓ %@", NSLocalizedString(@"_order_by_size_largest_", nil)]; }
  1688. else title = NSLocalizedString(@"_order_by_size_largest_", nil);
  1689. appDelegate.sortLargestItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"sortLargest"] multiplier:2 color:NCBrandColor.sharedInstance.icon] highlightedImage:nil action:^(REMenuItem *item) {
  1690. [CCUtility setOrderSettings:@"size"];
  1691. [CCUtility setAscendingSettings:false];
  1692. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1693. }];
  1694. /*
  1695. // ITEM GROUP ALPHABETIC -----------------------------------------------------------------------------------------------------
  1696. if ([groupBy isEqualToString:@"alphabetic"]) { title = NSLocalizedString(@"_group_alphabetic_yes_", nil); }
  1697. else { title = NSLocalizedString(@"_group_alphabetic_no_", nil); }
  1698. appDelegate.alphabeticItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByAlphabetic"] multiplier:2 color:NCBrandColor.sharedInstance.icon] highlightedImage:nil action:^(REMenuItem *item) {
  1699. if ([groupBy isEqualToString:@"alphabetic"]) [CCUtility setGroupBySettings:@"none"];
  1700. else [CCUtility setGroupBySettings:@"alphabetic"];
  1701. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1702. }];
  1703. // ITEM GROUP TYPEFILE -------------------------------------------------------------------------------------------------------
  1704. if ([groupBy isEqualToString:@"typefile"]) { title = NSLocalizedString(@"_group_typefile_yes_", nil); }
  1705. else { title = NSLocalizedString(@"_group_typefile_no_", nil); }
  1706. appDelegate.typefileItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByFile"] multiplier:2 color:NCBrandColor.sharedInstance.icon] highlightedImage:nil action:^(REMenuItem *item) {
  1707. if ([groupBy isEqualToString:@"typefile"]) [CCUtility setGroupBySettings:@"none"];
  1708. else [CCUtility setGroupBySettings:@"typefile"];
  1709. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1710. }];
  1711. // ITEM GROUP DATE -------------------------------------------------------------------------------------------------------
  1712. if ([groupBy isEqualToString:@"date"]) { title = NSLocalizedString(@"_group_date_yes_", nil); }
  1713. else { title = NSLocalizedString(@"_group_date_no_", nil); }
  1714. appDelegate.dateItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByDate"] multiplier:2 color:NCBrandColor.sharedInstance.icon] highlightedImage:nil action:^(REMenuItem *item) {
  1715. if ([groupBy isEqualToString:@"date"]) [CCUtility setGroupBySettings:@"none"];
  1716. else [CCUtility setGroupBySettings:@"date"];
  1717. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1718. }];
  1719. */
  1720. // ITEM DIRECTORY ON TOP ------------------------------------------------------------------------------------------------
  1721. if ([CCUtility getDirectoryOnTop]) { title = NSLocalizedString(@"_directory_on_top_yes_", nil); }
  1722. else { title = NSLocalizedString(@"_directory_on_top_no_", nil); }
  1723. appDelegate.directoryOnTopItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"foldersOnTop"] multiplier:2 color:NCBrandColor.sharedInstance.icon] highlightedImage:nil action:^(REMenuItem *item) {
  1724. if ([CCUtility getDirectoryOnTop]) [CCUtility setDirectoryOnTop:NO];
  1725. else [CCUtility setDirectoryOnTop:YES];
  1726. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1727. }];
  1728. // ITEM ADD FOLDER INFO -----------------------------------------------------------------------------------------------
  1729. appDelegate.addFolderInfo = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_add_folder_info_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"addFolderInfo"] width:50 height:50 color:NCBrandColor.sharedInstance.icon] highlightedImage:nil action:^(REMenuItem *item) {
  1730. [self createRichWorkspace];
  1731. }];
  1732. // REMENU --------------------------------------------------------------------------------------------------------------
  1733. if (capabilities.versionMajor >= k_nextcloud_version_18_0 && self.richWorkspace.length == 0) {
  1734. appDelegate.reMainMenu = [[REMenu alloc] initWithItems:@[appDelegate.selezionaItem, appDelegate.sortFileNameAZItem, appDelegate.sortFileNameZAItem, appDelegate.sortDateMoreRecentItem, appDelegate.sortDateLessRecentItem, appDelegate.sortSmallestItem, appDelegate.sortLargestItem, appDelegate.directoryOnTopItem, appDelegate.addFolderInfo]];
  1735. } else {
  1736. appDelegate.reMainMenu = [[REMenu alloc] initWithItems:@[appDelegate.selezionaItem, appDelegate.sortFileNameAZItem, appDelegate.sortFileNameZAItem, appDelegate.sortDateMoreRecentItem, appDelegate.sortDateLessRecentItem, appDelegate.sortSmallestItem, appDelegate.sortLargestItem, appDelegate.directoryOnTopItem]];
  1737. }
  1738. appDelegate.reMainMenu.itemHeight = 40;
  1739. appDelegate.reMainMenu.imageOffset = CGSizeMake(5, -1);
  1740. appDelegate.reMainMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  1741. appDelegate.reMainMenu.imageOffset = CGSizeMake(0, 0);
  1742. appDelegate.reMainMenu.waitUntilAnimationIsComplete = NO;
  1743. appDelegate.reMainMenu.separatorHeight = 0.5;
  1744. appDelegate.reMainMenu.separatorColor = NCBrandColor.sharedInstance.separator;
  1745. appDelegate.reMainMenu.backgroundColor = NCBrandColor.sharedInstance.backgroundForm;
  1746. appDelegate.reMainMenu.textColor = NCBrandColor.sharedInstance.textView;
  1747. appDelegate.reMainMenu.textAlignment = NSTextAlignmentLeft;
  1748. appDelegate.reMainMenu.textShadowColor = nil;
  1749. appDelegate.reMainMenu.textOffset = CGSizeMake(50, 0.0);
  1750. appDelegate.reMainMenu.font = [UIFont systemFontOfSize:14.0];
  1751. appDelegate.reMainMenu.highlightedBackgroundColor = NCBrandColor.sharedInstance.select;
  1752. appDelegate.reMainMenu.highlightedSeparatorColor = nil;
  1753. appDelegate.reMainMenu.highlightedTextColor = [UIColor blackColor];
  1754. appDelegate.reMainMenu.highlightedTextShadowColor = nil;
  1755. appDelegate.reMainMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  1756. appDelegate.reMainMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  1757. appDelegate.reMainMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  1758. appDelegate.reMainMenu.subtitleTextShadowColor = nil;
  1759. appDelegate.reMainMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  1760. appDelegate.reMainMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  1761. appDelegate.reMainMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  1762. appDelegate.reMainMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  1763. appDelegate.reMainMenu.subtitleHighlightedTextShadowColor = nil;
  1764. appDelegate.reMainMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  1765. appDelegate.reMainMenu.borderWidth = 0;
  1766. appDelegate.reMainMenu.borderColor = NCBrandColor.sharedInstance.backgroundForm;
  1767. appDelegate.reMainMenu.animationDuration = 0.2;
  1768. appDelegate.reMainMenu.closeAnimationDuration = 0.2;
  1769. appDelegate.reMainMenu.bounce = NO;
  1770. __weak typeof(self) weakSelf = self;
  1771. [appDelegate.reMainMenu setClosePreparationBlock:^{
  1772. // Backgroun reMenu (Gesture)
  1773. [weakSelf.reMenuBackgroundView removeFromSuperview];
  1774. [weakSelf.reMenuBackgroundView removeGestureRecognizer:weakSelf.singleFingerTap];
  1775. }];
  1776. }
  1777. - (void)toggleReMainMenu
  1778. {
  1779. if (appDelegate.reMainMenu.isOpen) {
  1780. [appDelegate.reMainMenu close];
  1781. } else {
  1782. [self createReMainMenu];
  1783. [appDelegate.reMainMenu showFromNavigationController:self.navigationController];
  1784. // Backgroun reMenu & (Gesture)
  1785. [self createReMenuBackgroundView:appDelegate.reMainMenu];
  1786. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReMainMenu)];
  1787. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  1788. }
  1789. }
  1790. - (void)createReSelectMenu
  1791. {
  1792. // ITEM SELECT ALL --------------------------------------------------------------------------------------------------
  1793. 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) {
  1794. [self didSelectAll];
  1795. }];
  1796. // ITEM MOVE --------------------------------------------------------------------------------------------------------
  1797. 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) {
  1798. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  1799. }];
  1800. // ITEM DOWNLOAD ----------------------------------------------------------------------------------------------------
  1801. 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) {
  1802. [self downloadSelectedFilesFolders];
  1803. }];
  1804. // ITEM SAVE IMAGE & VIDEO -------------------------------------------------------------------------------------------
  1805. 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) {
  1806. [self saveSelectedFiles];
  1807. }];
  1808. // ITEM DELETE ------------------------------------------------------------------------------------------------------
  1809. 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) {
  1810. [self deleteFile];
  1811. }];
  1812. // E2EE
  1813. if (_metadataFolder.e2eEncrypted) {
  1814. if ([NCBrandOptions sharedInstance].disable_openin_file) {
  1815. appDelegate.reSelectMenu = [[REMenu alloc] initWithItems:@[appDelegate.selectAllItem, appDelegate.downloadItem, appDelegate.deleteItem]];
  1816. } else {
  1817. appDelegate.reSelectMenu = [[REMenu alloc] initWithItems:@[appDelegate.selectAllItem, appDelegate.downloadItem, appDelegate.saveItem, appDelegate.deleteItem]];
  1818. }
  1819. } else {
  1820. if ([NCBrandOptions sharedInstance].disable_openin_file) {
  1821. appDelegate.reSelectMenu = [[REMenu alloc] initWithItems:@[appDelegate.selectAllItem, appDelegate.moveItem, appDelegate.downloadItem, appDelegate.deleteItem]];
  1822. } else {
  1823. appDelegate.reSelectMenu = [[REMenu alloc] initWithItems:@[appDelegate.selectAllItem, appDelegate.moveItem, appDelegate.downloadItem, appDelegate.saveItem, appDelegate.deleteItem]];
  1824. }
  1825. }
  1826. appDelegate.reSelectMenu.itemHeight = 50;
  1827. appDelegate.reSelectMenu.imageOffset = CGSizeMake(5, -1);
  1828. appDelegate.reSelectMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  1829. appDelegate.reSelectMenu.imageOffset = CGSizeMake(0, 0);
  1830. appDelegate.reSelectMenu.waitUntilAnimationIsComplete = NO;
  1831. appDelegate.reSelectMenu.separatorHeight = 0.5;
  1832. appDelegate.reSelectMenu.separatorColor = NCBrandColor.sharedInstance.separator;
  1833. appDelegate.reSelectMenu.backgroundColor = NCBrandColor.sharedInstance.backgroundForm;
  1834. appDelegate.reSelectMenu.textColor = NCBrandColor.sharedInstance.textView;
  1835. appDelegate.reSelectMenu.textAlignment = NSTextAlignmentLeft;
  1836. appDelegate.reSelectMenu.textShadowColor = nil;
  1837. appDelegate.reSelectMenu.textOffset = CGSizeMake(50, 0.0);
  1838. appDelegate.reSelectMenu.font = [UIFont systemFontOfSize:14.0];
  1839. appDelegate.reSelectMenu.highlightedBackgroundColor = NCBrandColor.sharedInstance.select;
  1840. appDelegate.reSelectMenu.highlightedSeparatorColor = nil;
  1841. appDelegate.reSelectMenu.highlightedTextColor = [UIColor blackColor];
  1842. appDelegate.reSelectMenu.highlightedTextShadowColor = nil;
  1843. appDelegate.reSelectMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  1844. appDelegate.reSelectMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1.000];
  1845. appDelegate.reSelectMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  1846. appDelegate.reSelectMenu.subtitleTextShadowColor = nil;
  1847. appDelegate.reSelectMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  1848. appDelegate.reSelectMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  1849. appDelegate.reSelectMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  1850. appDelegate.reSelectMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  1851. appDelegate.reSelectMenu.subtitleHighlightedTextShadowColor = nil;
  1852. appDelegate.reSelectMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  1853. appDelegate.reMainMenu.borderWidth = 0;
  1854. appDelegate.reMainMenu.borderColor = NCBrandColor.sharedInstance.backgroundForm;
  1855. appDelegate.reSelectMenu.closeAnimationDuration = 0.2;
  1856. appDelegate.reSelectMenu.animationDuration = 0.2;
  1857. appDelegate.reSelectMenu.bounce = NO;
  1858. __weak typeof(self) weakSelf = self;
  1859. [appDelegate.reSelectMenu setClosePreparationBlock:^{
  1860. // Backgroun reMenu (Gesture)
  1861. [weakSelf.reMenuBackgroundView removeFromSuperview];
  1862. [weakSelf.reMenuBackgroundView removeGestureRecognizer:weakSelf.singleFingerTap];
  1863. }];
  1864. }
  1865. - (void)toggleReSelectMenu
  1866. {
  1867. if (appDelegate.reSelectMenu.isOpen) {
  1868. [appDelegate.reSelectMenu close];
  1869. } else {
  1870. [self createReSelectMenu];
  1871. [appDelegate.reSelectMenu showFromNavigationController:self.navigationController];
  1872. // Backgroun reMenu & (Gesture)
  1873. [self createReMenuBackgroundView:appDelegate.reSelectMenu];
  1874. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReSelectMenu)];
  1875. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  1876. }
  1877. }
  1878. #pragma --------------------------------------------------------------------------------------------
  1879. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  1880. #pragma --------------------------------------------------------------------------------------------
  1881. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  1882. {
  1883. if (recognizer.state == UIGestureRecognizerStateBegan) {
  1884. CGPoint touchPoint = [recognizer locationInView:self.tableView];
  1885. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touchPoint];
  1886. NSMutableArray *items = [NSMutableArray new];
  1887. if ([self indexPathIsValid:indexPath])
  1888. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1889. else
  1890. self.metadata = nil;
  1891. [self becomeFirstResponder];
  1892. UIMenuController *menuController = [UIMenuController sharedMenuController];
  1893. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)]];
  1894. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)]];
  1895. if ([NCBrandOptions sharedInstance].disable_openin_file == false) {
  1896. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)]];
  1897. }
  1898. if ([self.metadata.typeFile isEqualToString: k_metadataTypeFile_document]) {
  1899. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_internal_view_", nil) action:@selector(openInternalViewer:)]];
  1900. }
  1901. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)]];
  1902. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)]];
  1903. [menuController setMenuItems:items];
  1904. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:self.tableView];
  1905. [menuController setMenuVisible:YES animated:YES];
  1906. }
  1907. }
  1908. - (BOOL)canBecomeFirstResponder
  1909. {
  1910. return YES;
  1911. }
  1912. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  1913. {
  1914. // For copy file, copy files, Open in ... :
  1915. //
  1916. // NO Directory
  1917. // NO Error Passcode
  1918. // NO In Session mode (download/upload)
  1919. // NO Template
  1920. if (@selector(copyFile:) == action || @selector(openinFile:) == action || @selector(openInternalViewer:) == action) {
  1921. if (_isSelectedMode == NO && self.metadata && !self.metadata.directory && self.metadata.status == k_metadataStatusNormal) return YES;
  1922. else return NO;
  1923. }
  1924. if (@selector(copyFiles:) == action) {
  1925. if (_isSelectedMode) {
  1926. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1927. for (tableMetadata *metadata in selectedMetadatas) {
  1928. if (!metadata.directory && metadata.status == k_metadataStatusNormal)
  1929. return YES;
  1930. }
  1931. }
  1932. return NO;
  1933. }
  1934. if (@selector(pasteFile:) == action) {
  1935. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1936. NSArray *items = [pasteboard items];
  1937. if ([items count] == 1) {
  1938. // Value : (NSData) ocId
  1939. NSDictionary *dic = [items objectAtIndex:0];
  1940. NSData *dataocId = [dic objectForKey: k_metadataKeyedUnarchiver];
  1941. NSString *ocId = [NSKeyedUnarchiver unarchiveObjectWithData:dataocId];
  1942. if (ocId) {
  1943. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  1944. if (metadata) {
  1945. return [CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView];
  1946. } else {
  1947. return NO;
  1948. }
  1949. }
  1950. }
  1951. return NO;
  1952. }
  1953. if (@selector(pasteFiles:) == action) {
  1954. BOOL isValid = NO;
  1955. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1956. NSArray *items = [pasteboard items];
  1957. if ([items count] <= 1) return NO;
  1958. for (NSDictionary *dic in items) {
  1959. // Value : (NSData) ocId
  1960. NSData *dataocId = [dic objectForKey: k_metadataKeyedUnarchiver];
  1961. NSString *ocId = [NSKeyedUnarchiver unarchiveObjectWithData:dataocId];
  1962. if (ocId) {
  1963. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  1964. if (metadata) {
  1965. if ([CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView]) {
  1966. isValid = YES;
  1967. } else {
  1968. isValid = NO;
  1969. break;
  1970. }
  1971. } else {
  1972. isValid = NO;
  1973. break;
  1974. }
  1975. } else {
  1976. isValid = NO;
  1977. break;
  1978. }
  1979. }
  1980. return isValid;
  1981. }
  1982. return NO;
  1983. }
  1984. /************************************ COPY ************************************/
  1985. - (void)copyFile:(id)sender
  1986. {
  1987. // Remove all item
  1988. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1989. pasteboard.items = [[NSArray alloc] init];
  1990. if ([CCUtility fileProviderStorageExists:self.metadata.ocId fileNameView:self.metadata.fileNameView]) {
  1991. [self copyFileToPasteboard:self.metadata];
  1992. } else {
  1993. self.metadata.session = k_download_session;
  1994. self.metadata.sessionError = @"";
  1995. self.metadata.sessionSelector = selectorLoadCopy;
  1996. self.metadata.status = k_metadataStatusWaitDownload;
  1997. // Add Metadata for Download
  1998. (void)[[NCManageDatabase sharedInstance] addMetadata:self.metadata];
  1999. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:self.metadata.ocId action:k_action_MOD];
  2000. [appDelegate startLoadAutoDownloadUpload];
  2001. }
  2002. }
  2003. - (void)copyFiles:(id)sender
  2004. {
  2005. // Remove all item
  2006. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2007. pasteboard.items = [[NSArray alloc] init];
  2008. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2009. for (tableMetadata *metadata in selectedMetadatas) {
  2010. if ([CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView]) {
  2011. [self copyFileToPasteboard:metadata];
  2012. } else {
  2013. metadata.session = k_download_session;
  2014. metadata.sessionError = @"";
  2015. metadata.sessionSelector = selectorLoadCopy;
  2016. metadata.status = k_metadataStatusWaitDownload;
  2017. // Add Metadata for Download
  2018. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  2019. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:metadata.ocId action:k_action_MOD];
  2020. [appDelegate startLoadAutoDownloadUpload];
  2021. }
  2022. }
  2023. [self tableViewSelect:NO];
  2024. }
  2025. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  2026. {
  2027. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2028. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  2029. // Value : (NSData) ocId
  2030. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata.ocId], k_metadataKeyedUnarchiver,nil];
  2031. [items addObject:item];
  2032. [pasteboard setItems:items];
  2033. }
  2034. /************************************ OPEN IN ... ******************************/
  2035. - (void)openinFile:(id)sender
  2036. {
  2037. [[NCMainCommon sharedInstance] downloadOpenWithMetadata:self.metadata selector:selectorOpenIn];
  2038. }
  2039. /************************************ OPEN INTERNAL VIEWER ... ******************************/
  2040. - (void)openInternalViewer:(id)sender
  2041. {
  2042. [[NCMainCommon sharedInstance] downloadOpenWithMetadata:self.metadata selector:selectorLoadFileInternalView];
  2043. }
  2044. /************************************ PASTE ************************************/
  2045. - (void)pasteFile:(id)sender
  2046. {
  2047. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2048. [self uploadFilePasteArray:[pasteboard items]];
  2049. }
  2050. - (void)pasteFiles:(id)sender
  2051. {
  2052. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2053. [self uploadFilePasteArray:[pasteboard items]];
  2054. }
  2055. - (void)uploadFilePasteArray:(NSArray *)items
  2056. {
  2057. for (NSDictionary *dic in items) {
  2058. // Value : (NSData) ocId
  2059. NSData *dataocId = [dic objectForKey: k_metadataKeyedUnarchiver];
  2060. NSString *ocId = [NSKeyedUnarchiver unarchiveObjectWithData:dataocId];
  2061. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  2062. if (metadata) {
  2063. if ([CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView]) {
  2064. NSString *fileName = [[NCUtility sharedInstance] createFileName:metadata.fileNameView serverUrl:self.serverUrl account:appDelegate.activeAccount];
  2065. NSString *ocId = [CCUtility createMetadataIDFromAccount:appDelegate.activeAccount serverUrl:self.serverUrl fileNameView:fileName directory:false];
  2066. [CCUtility copyFileAtPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileNameView] toPath:[CCUtility getDirectoryProviderStorageOcId:ocId fileNameView:fileName]];
  2067. tableMetadata *metadataForUpload = [tableMetadata new];
  2068. metadataForUpload.account = appDelegate.activeAccount;
  2069. metadataForUpload.date = [NSDate new];
  2070. metadataForUpload.ocId = ocId;
  2071. metadataForUpload.fileName = fileName;
  2072. metadataForUpload.fileNameView = fileName;
  2073. metadataForUpload.serverUrl = self.serverUrl;
  2074. metadataForUpload.session = k_upload_session;
  2075. metadataForUpload.sessionSelector = selectorUploadFile;
  2076. metadataForUpload.size = metadata.size;
  2077. metadataForUpload.status = k_metadataStatusWaitUpload;
  2078. // Add Medtadata for upload
  2079. (void)[[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  2080. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  2081. }
  2082. }
  2083. }
  2084. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  2085. [appDelegate startLoadAutoDownloadUpload];
  2086. }
  2087. #pragma --------------------------------------------------------------------------------------------
  2088. #pragma mark ===== Lock Passcode =====
  2089. #pragma --------------------------------------------------------------------------------------------
  2090. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  2091. {
  2092. return _failedAttempts;
  2093. }
  2094. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  2095. {
  2096. return _lockUntilDate;
  2097. }
  2098. - (void)passcodeViewCloseButtonPressed:(id)sender
  2099. {
  2100. [self dismissViewControllerAnimated:YES completion:nil];
  2101. }
  2102. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  2103. {
  2104. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  2105. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  2106. _lockUntilDate = nil;
  2107. _failedAttempts = 0;
  2108. aResultHandler(YES);
  2109. } else aResultHandler(NO);
  2110. } else aResultHandler(YES);
  2111. }
  2112. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  2113. {
  2114. [aViewController dismissViewControllerAnimated:YES completion:nil];
  2115. switch (aViewController.type) {
  2116. case BKPasscodeViewControllerCheckPasscodeType: {
  2117. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  2118. // possiamo procedere alla prossima directory
  2119. [self performSegueDirectoryWithControlPasscode:false metadata:self.metadata blinkFileNamePath:self.blinkFileNamePath];
  2120. // avviamo la sessione Passcode Lock con now
  2121. appDelegate.sessionePasscodeLock = [NSDate date];
  2122. }
  2123. // disattivazione lock cartella
  2124. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  2125. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:self.metadata.serverUrl addFileName:self.metadata.fileName];
  2126. if (![[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:NO account:appDelegate.activeAccount]) {
  2127. [[NCContentPresenter shared] messageNotification:@"_error_" description:@"_error_operation_canc_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  2128. }
  2129. [self tableViewReloadData];
  2130. }
  2131. }
  2132. break;
  2133. default:
  2134. break;
  2135. }
  2136. }
  2137. - (void)comandoLockPassword
  2138. {
  2139. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:self.metadata.serverUrl addFileName:self.metadata.fileName];
  2140. // se non è abilitato il Lock Passcode esci
  2141. if ([[CCUtility getBlockCode] length] == 0) {
  2142. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) preferredStyle:UIAlertControllerStyleAlert];
  2143. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  2144. [alertController addAction:okAction];
  2145. [self presentViewController:alertController animated:YES completion:nil];
  2146. return;
  2147. }
  2148. // se è richiesta la disattivazione si chiede la password
  2149. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  2150. if (directory.lock) {
  2151. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2152. viewController.delegate = self;
  2153. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  2154. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2155. viewController.inputViewTitlePassword = YES;
  2156. if ([CCUtility getSimplyBlockCode]) {
  2157. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2158. viewController.passcodeInputView.maximumLength = 6;
  2159. } else {
  2160. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2161. viewController.passcodeInputView.maximumLength = 64;
  2162. }
  2163. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  2164. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2165. viewController.touchIDManager = touchIDManager;
  2166. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  2167. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2168. viewController.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
  2169. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2170. navigationController.modalPresentationStyle = UIModalPresentationFullScreen;
  2171. [self presentViewController:navigationController animated:YES completion:nil];
  2172. return;
  2173. }
  2174. // ---------------- ACTIVATE PASSWORD
  2175. if ([[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:YES account:appDelegate.activeAccount]) {
  2176. NSIndexPath *indexPath = [sectionDataSource.ocIdIndexPath objectForKey:self.metadata.ocId];
  2177. if ([self indexPathIsValid:indexPath])
  2178. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2179. } else {
  2180. [[NCContentPresenter shared] messageNotification:@"_error_" description:@"_error_operation_canc_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  2181. }
  2182. }
  2183. #pragma mark -
  2184. #pragma --------------------------------------------------------------------------------------------
  2185. #pragma mark ===== menu action : Favorite, More, Delete [swipe] =====
  2186. #pragma --------------------------------------------------------------------------------------------
  2187. - (BOOL)canOpenMenuAction:(tableMetadata *)metadata
  2188. {
  2189. if (metadata == nil || _metadataFolder == nil || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata] || metadata.status != k_metadataStatusNormal || [[NCManageDatabase sharedInstance] isTableInvalidated:_metadataFolder])
  2190. return NO;
  2191. // E2EE
  2192. if (_metadataFolder.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount] == NO)
  2193. return NO;
  2194. return YES;
  2195. }
  2196. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell canSwipe:(MGSwipeDirection)direction
  2197. {
  2198. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2199. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2200. return [self canOpenMenuAction:metadata];
  2201. }
  2202. -(void)swipeTableCell:(nonnull MGSwipeTableCell *)cell didChangeSwipeState:(MGSwipeState)state gestureIsActive:(BOOL)gestureIsActive
  2203. {
  2204. }
  2205. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell tappedButtonAtIndex:(NSInteger)index direction:(MGSwipeDirection)direction fromExpansion:(BOOL)fromExpansion
  2206. {
  2207. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2208. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2209. if (direction == MGSwipeDirectionRightToLeft) {
  2210. [self actionDelete:indexPath];
  2211. }
  2212. if (direction == MGSwipeDirectionLeftToRight) {
  2213. if (self.metadata.favorite)
  2214. [self settingFavorite:self.metadata favorite:NO];
  2215. else
  2216. [self settingFavorite:self.metadata favorite:YES];
  2217. }
  2218. return YES;
  2219. }
  2220. - (void)actionDelete:(NSIndexPath *)indexPath
  2221. {
  2222. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2223. // Directory locked ?
  2224. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:self.metadata.serverUrl addFileName:metadata.fileName];
  2225. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  2226. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  2227. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil) {
  2228. [[NCContentPresenter shared] messageNotification:@"_error_" description:@"_folder_blocked_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  2229. return;
  2230. }
  2231. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  2232. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  2233. [self performSelector:@selector(deleteFile) withObject:nil];
  2234. }]];
  2235. if (localFile) {
  2236. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_remove_local_file_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  2237. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  2238. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId] error:nil];
  2239. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  2240. }]];
  2241. }
  2242. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2243. }]];
  2244. alertController.popoverPresentationController.sourceView = self.tableView;
  2245. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  2246. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  2247. [alertController.view layoutIfNeeded];
  2248. [self presentViewController:alertController animated:YES completion:nil];
  2249. }
  2250. - (void)actionMore:(UITapGestureRecognizer *)gestureRecognizer
  2251. {
  2252. CGPoint touch = [gestureRecognizer locationInView:self.tableView];
  2253. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touch];
  2254. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2255. NSString *titoloLock, *titleFavorite;
  2256. if (self.metadata.favorite) {
  2257. titleFavorite = NSLocalizedString(@"_remove_favorites_", nil);
  2258. } else {
  2259. titleFavorite = NSLocalizedString(@"_add_favorites_", nil);
  2260. }
  2261. if (self.metadata.directory) {
  2262. // calcolo lockServerUrl
  2263. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:self.metadata.serverUrl addFileName:self.metadata.fileName];
  2264. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  2265. if (directory.lock)
  2266. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_remove_passcode_", nil)];
  2267. else
  2268. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_protect_passcode_", nil)];
  2269. }
  2270. // ******************************************* AHKActionSheet *******************************************
  2271. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.tabBarController.view title:nil];
  2272. actionSheet.animationDuration = 0.2;
  2273. actionSheet.buttonHeight = 50.0;
  2274. actionSheet.cancelButtonHeight = 50.0f;
  2275. actionSheet.separatorHeight = 5.0f;
  2276. actionSheet.automaticallyTintButtonImages = @(NO);
  2277. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:NCBrandColor.sharedInstance.encrypted };
  2278. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:NCBrandColor.sharedInstance.textView };
  2279. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont boldSystemFontOfSize:17], NSForegroundColorAttributeName:NCBrandColor.sharedInstance.textView };
  2280. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:NCBrandColor.sharedInstance.textView };
  2281. actionSheet.separatorColor = NCBrandColor.sharedInstance.separator;
  2282. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  2283. actionSheet.cancelButtonBackgroudColor = NCBrandColor.sharedInstance.backgroundForm;
  2284. // ******************************************* DIRECTORY *******************************************
  2285. if (self.metadata.directory) {
  2286. BOOL lockDirectory = NO;
  2287. BOOL isOffline = NO;
  2288. NSString *dirServerUrl = [CCUtility stringAppendServerUrl:self.metadata.serverUrl addFileName:self.metadata.fileName];
  2289. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:[NSString stringWithFormat:@"%@/%@", self.serverUrl, self.metadata.fileName] account:appDelegate.activeAccount];
  2290. // Directory bloccata ?
  2291. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, dirServerUrl]];
  2292. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil) lockDirectory = YES;
  2293. if (directory.offline) isOffline = YES;
  2294. [actionSheet addButtonWithTitle:self.metadata.fileNameView
  2295. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder"] multiplier:2 color:NCBrandColor.sharedInstance.brandElement]
  2296. backgroundColor:NCBrandColor.sharedInstance.backgroundForm
  2297. height:50.0
  2298. type:AHKActionSheetButtonTypeDisabled
  2299. handler:nil
  2300. ];
  2301. [actionSheet addButtonWithTitle: titleFavorite
  2302. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] multiplier:2 color:NCBrandColor.sharedInstance.yellowFavorite]
  2303. backgroundColor: NCBrandColor.sharedInstance.backgroundForm
  2304. height: 50.0
  2305. type: AHKActionSheetButtonTypeDefault
  2306. handler: ^(AHKActionSheet *as) {
  2307. if (self.metadata.favorite) [self settingFavorite:self.metadata favorite:NO];
  2308. else [self settingFavorite:self.metadata favorite:YES];
  2309. }];
  2310. if (!lockDirectory && !isFolderEncrypted) {
  2311. [actionSheet addButtonWithTitle:NSLocalizedString(@"_details_", nil)
  2312. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"details"] width:50 height:50 color:NCBrandColor.sharedInstance.icon]
  2313. backgroundColor:NCBrandColor.sharedInstance.backgroundForm
  2314. height:50.0
  2315. type:AHKActionSheetButtonTypeDefault
  2316. handler:^(AHKActionSheet *as) {
  2317. [[NCMainCommon sharedInstance] openShareWithViewController:self metadata:self.metadata indexPage:0];
  2318. }];
  2319. }
  2320. if (!([self.metadata.fileName isEqualToString:_autoUploadFileName] == YES && [self.metadata.serverUrl isEqualToString:_autoUploadDirectory] == YES) && !lockDirectory && !self.metadata.e2eEncrypted) {
  2321. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  2322. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"rename"] multiplier:2 color:NCBrandColor.sharedInstance.icon]
  2323. backgroundColor:NCBrandColor.sharedInstance.backgroundForm
  2324. height:50.0
  2325. type:AHKActionSheetButtonTypeDefault
  2326. handler:^(AHKActionSheet *as) {
  2327. __weak __typeof(UIAlertController) *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  2328. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  2329. textField.text = self.metadata.fileNameView;
  2330. textField.delegate = self;
  2331. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  2332. }];
  2333. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2334. NSLog(@"[LOG] Cancel action");
  2335. }];
  2336. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  2337. UITextField *fileName = alertController.textFields.firstObject;
  2338. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:self.metadata,fileName.text, nil] waitUntilDone:NO];
  2339. }];
  2340. okAction.enabled = NO;
  2341. [alertController addAction:cancelAction];
  2342. [alertController addAction:okAction];
  2343. [self presentViewController:alertController animated:YES completion:nil];
  2344. }];
  2345. }
  2346. if (!([self.metadata.fileName isEqualToString:_autoUploadFileName] == YES && [self.metadata.serverUrl isEqualToString:_autoUploadDirectory] == YES) && !lockDirectory && !isFolderEncrypted) {
  2347. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  2348. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"move"] multiplier:2 color:NCBrandColor.sharedInstance.icon]
  2349. backgroundColor:NCBrandColor.sharedInstance.backgroundForm
  2350. height:50.0
  2351. type:AHKActionSheetButtonTypeDefault
  2352. handler:^(AHKActionSheet *as) {
  2353. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  2354. }];
  2355. }
  2356. if (!isFolderEncrypted) {
  2357. NSString *title;
  2358. if (isOffline) {
  2359. title = NSLocalizedString(@"_remove_available_offline_", nil);
  2360. } else {
  2361. title = NSLocalizedString(@"_set_available_offline_", nil);
  2362. }
  2363. [actionSheet addButtonWithTitle:title
  2364. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"offline"] multiplier:2 color:NCBrandColor.sharedInstance.icon]
  2365. backgroundColor:NCBrandColor.sharedInstance.backgroundForm
  2366. height:50.0
  2367. type:AHKActionSheetButtonTypeDefault
  2368. handler:^(AHKActionSheet *as) {
  2369. if (isOffline) {
  2370. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:dirServerUrl offline:false account:appDelegate.activeAccount];
  2371. [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
  2372. } else {
  2373. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:dirServerUrl offline:true account:appDelegate.activeAccount];
  2374. [[CCSynchronize sharedSynchronize] readFolder:dirServerUrl selector:selectorReadFolderWithDownload account:appDelegate.activeAccount];
  2375. [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
  2376. }
  2377. }];
  2378. }
  2379. [actionSheet addButtonWithTitle:titoloLock
  2380. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"settingsPasscodeYES"] multiplier:2 color:NCBrandColor.sharedInstance.icon]
  2381. backgroundColor:NCBrandColor.sharedInstance.backgroundForm
  2382. height:50.0
  2383. type:AHKActionSheetButtonTypeDefault
  2384. handler:^(AHKActionSheet *as) {
  2385. [self performSelector:@selector(comandoLockPassword) withObject:nil];
  2386. }];
  2387. if (!self.metadata.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  2388. [actionSheet addButtonWithTitle:NSLocalizedString(@"_e2e_set_folder_encrypted_", nil)
  2389. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"lock"] width:50 height:50 color:NCBrandColor.sharedInstance.icon]
  2390. backgroundColor:NCBrandColor.sharedInstance.backgroundForm
  2391. height:50.0
  2392. type:AHKActionSheetButtonTypeDefault
  2393. handler:^(AHKActionSheet *as) {
  2394. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  2395. 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];
  2396. dispatch_async(dispatch_get_main_queue(), ^{
  2397. if (error) {
  2398. [[NCContentPresenter shared] messageNotification:@"_e2e_error_mark_folder_" description:error.localizedDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  2399. } else {
  2400. [[NCManageDatabase sharedInstance] deleteE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, [NSString stringWithFormat:@"%@/%@", self.serverUrl, self.metadata.fileName]]];
  2401. [self readFolder:self.serverUrl];
  2402. }
  2403. });
  2404. });
  2405. }];
  2406. }
  2407. if (self.metadata.e2eEncrypted && !_metadataFolder.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  2408. [actionSheet addButtonWithTitle:NSLocalizedString(@"_e2e_remove_folder_encrypted_", nil)
  2409. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"lock"] width:50 height:50 color:NCBrandColor.sharedInstance.icon]
  2410. backgroundColor:NCBrandColor.sharedInstance.backgroundForm
  2411. height:50.0
  2412. type:AHKActionSheetButtonTypeDefault
  2413. handler:^(AHKActionSheet *as) {
  2414. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  2415. 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];
  2416. dispatch_async(dispatch_get_main_queue(), ^{
  2417. if (error) {
  2418. [[NCContentPresenter shared] messageNotification:@"_e2e_error_delete_mark_folder_" description:error.localizedDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  2419. } else {
  2420. [[NCManageDatabase sharedInstance] deleteE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, [NSString stringWithFormat:@"%@/%@", self.serverUrl, self.metadata.fileName]]];
  2421. [self readFolder:self.serverUrl];
  2422. }
  2423. });
  2424. });
  2425. }];
  2426. }
  2427. [actionSheet addButtonWithTitle:NSLocalizedString(@"_delete_", nil)
  2428. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"trash"] width:50 height:50 color:[UIColor redColor]]
  2429. backgroundColor:NCBrandColor.sharedInstance.backgroundForm
  2430. height:50.0
  2431. type:AHKActionSheetButtonTypeDestructive
  2432. handler:^(AHKActionSheet *as) {
  2433. [self actionDelete:indexPath];
  2434. }];
  2435. [actionSheet show];
  2436. }
  2437. // ******************************************* FILE *******************************************
  2438. if (!self.metadata.directory) {
  2439. UIImage *iconHeader;
  2440. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  2441. if ([[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconOcId:self.metadata.ocId fileNameView:self.metadata.fileNameView]])
  2442. iconHeader = [UIImage imageWithContentsOfFile:[CCUtility getDirectoryProviderStorageIconOcId:self.metadata.ocId fileNameView:self.metadata.fileNameView]];
  2443. else
  2444. iconHeader = [UIImage imageNamed:self.metadata.iconName];
  2445. [actionSheet addButtonWithTitle: self.metadata.fileNameView
  2446. image: iconHeader
  2447. backgroundColor: NCBrandColor.sharedInstance.backgroundForm
  2448. height: 50.0
  2449. type: AHKActionSheetButtonTypeDisabled
  2450. handler: nil
  2451. ];
  2452. [actionSheet addButtonWithTitle: titleFavorite
  2453. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] multiplier:2 color:NCBrandColor.sharedInstance.yellowFavorite]
  2454. backgroundColor: NCBrandColor.sharedInstance.backgroundForm
  2455. height: 50.0
  2456. type: AHKActionSheetButtonTypeDefault
  2457. handler: ^(AHKActionSheet *as) {
  2458. if (self.metadata.favorite) [self settingFavorite:self.metadata favorite:NO];
  2459. else [self settingFavorite:self.metadata favorite:YES];
  2460. }];
  2461. if (!_metadataFolder.e2eEncrypted) {
  2462. [actionSheet addButtonWithTitle:NSLocalizedString(@"_details_", nil)
  2463. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"details"] width:50 height:50 color:NCBrandColor.sharedInstance.icon]
  2464. backgroundColor:NCBrandColor.sharedInstance.backgroundForm
  2465. height: 50.0
  2466. type:AHKActionSheetButtonTypeDefault
  2467. handler:^(AHKActionSheet *as) {
  2468. [[NCMainCommon sharedInstance] openShareWithViewController:self metadata:self.metadata indexPage:0];
  2469. }];
  2470. }
  2471. if (![NCBrandOptions sharedInstance].disable_openin_file) {
  2472. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil)
  2473. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"openFile"] multiplier:2 color:NCBrandColor.sharedInstance.icon]
  2474. backgroundColor:NCBrandColor.sharedInstance.backgroundForm
  2475. height: 50.0
  2476. type:AHKActionSheetButtonTypeDefault
  2477. handler:^(AHKActionSheet *as) {
  2478. [self performSelector:@selector(openinFile:) withObject:nil];
  2479. }];
  2480. }
  2481. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  2482. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"rename"] multiplier:2 color:NCBrandColor.sharedInstance.icon]
  2483. backgroundColor:NCBrandColor.sharedInstance.backgroundForm
  2484. height: 50.0
  2485. type:AHKActionSheetButtonTypeDefault
  2486. handler:^(AHKActionSheet *as) {
  2487. __weak __typeof(UIAlertController) *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  2488. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  2489. textField.text = self.metadata.fileNameView;
  2490. textField.delegate = self;
  2491. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  2492. }];
  2493. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2494. NSLog(@"[LOG] Cancel action");
  2495. }];
  2496. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  2497. UITextField *fileName = alertController.textFields.firstObject;
  2498. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:self.metadata,fileName.text, nil] waitUntilDone:NO];
  2499. }];
  2500. okAction.enabled = NO;
  2501. [alertController addAction:cancelAction];
  2502. [alertController addAction:okAction];
  2503. [self presentViewController:alertController animated:YES completion:nil];
  2504. }];
  2505. if (!_metadataFolder.e2eEncrypted) {
  2506. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  2507. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"move"] multiplier:2 color:NCBrandColor.sharedInstance.icon]
  2508. backgroundColor:NCBrandColor.sharedInstance.backgroundForm
  2509. height:50.0
  2510. type:AHKActionSheetButtonTypeDefault
  2511. handler:^(AHKActionSheet *as) {
  2512. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  2513. }];
  2514. }
  2515. if ([NCUtility.sharedInstance isEditImage:self.metadata.fileNameView] != nil && !_metadataFolder.e2eEncrypted && self.metadata.status == k_metadataStatusNormal) {
  2516. [actionSheet addButtonWithTitle:NSLocalizedString(@"_modify_photo_", nil)
  2517. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"modifyPhoto"] width:50 height:50 color:NCBrandColor.sharedInstance.icon]
  2518. backgroundColor:NCBrandColor.sharedInstance.backgroundForm
  2519. height:50.0
  2520. type:AHKActionSheetButtonTypeDefault
  2521. handler:^(AHKActionSheet *as) {
  2522. self.metadata.session = k_download_session;
  2523. self.metadata.sessionError = @"";
  2524. self.metadata.sessionSelector = selectorDownloadEditPhoto;
  2525. self.metadata.status = k_metadataStatusWaitDownload;
  2526. (void)[[NCManageDatabase sharedInstance] addMetadata:self.metadata];
  2527. [appDelegate startLoadAutoDownloadUpload];
  2528. }];
  2529. }
  2530. if (!_metadataFolder.e2eEncrypted) {
  2531. NSString *title;
  2532. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", self.metadata.ocId]];
  2533. if (localFile == nil || localFile.offline == false) { title = NSLocalizedString(@"_set_available_offline_", nil); }
  2534. else { title = NSLocalizedString(@"_remove_available_offline_", nil); }
  2535. [actionSheet addButtonWithTitle:title
  2536. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"offline"] multiplier:2 color:NCBrandColor.sharedInstance.icon]
  2537. backgroundColor:NCBrandColor.sharedInstance.backgroundForm
  2538. height:50.0
  2539. type:AHKActionSheetButtonTypeDefault
  2540. handler:^(AHKActionSheet *as) {
  2541. if (localFile == nil || ![CCUtility fileProviderStorageExists:self.metadata.ocId fileNameView:self.metadata.fileNameView]) {
  2542. self.metadata.session = k_download_session;
  2543. self.metadata.sessionError = @"";
  2544. self.metadata.sessionSelector = selectorLoadOffline;
  2545. self.metadata.status = k_metadataStatusWaitDownload;
  2546. // Add Metadata for Download
  2547. (void)[[NCManageDatabase sharedInstance] addMetadata:self.metadata];
  2548. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:self.metadata.ocId action:k_action_MOD];
  2549. [appDelegate startLoadAutoDownloadUpload];
  2550. } else if (localFile.offline == false) {
  2551. [[NCManageDatabase sharedInstance] setLocalFileWithOcId:self.metadata.ocId offline:true];
  2552. [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
  2553. } else {
  2554. [[NCManageDatabase sharedInstance] setLocalFileWithOcId:self.metadata.ocId offline:false];
  2555. [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
  2556. }
  2557. }];
  2558. }
  2559. [actionSheet addButtonWithTitle:NSLocalizedString(@"_delete_", nil)
  2560. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"trash"] width:50 height:50 color:[UIColor redColor]]
  2561. backgroundColor:NCBrandColor.sharedInstance.backgroundForm
  2562. height:50.0
  2563. type:AHKActionSheetButtonTypeDestructive
  2564. handler:^(AHKActionSheet *as) {
  2565. [self actionDelete:indexPath];
  2566. }];
  2567. [actionSheet show];
  2568. }
  2569. }
  2570. #pragma --------------------------------------------------------------------------------------------
  2571. #pragma mark - ==== Datasource ====
  2572. #pragma --------------------------------------------------------------------------------------------
  2573. - (void)clearDateReadDataSource:(NSNotification *)notification
  2574. {
  2575. _dateReadDataSource = Nil;
  2576. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  2577. }
  2578. - (void)reloadDatasource:(NSString *)serverUrl ocId:(NSString *)ocId action:(NSInteger)action
  2579. {
  2580. // test
  2581. if (appDelegate.activeAccount.length == 0 || serverUrl.length == 0 || serverUrl == nil || self.view.window == nil)
  2582. return;
  2583. // Search Mode
  2584. if (self.searchController.isActive) {
  2585. // Create metadatas
  2586. NSMutableArray *metadatas = [NSMutableArray new];
  2587. for (tableMetadata *resultMetadata in _searchResultMetadatas) {
  2588. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", resultMetadata.ocId]];
  2589. if (metadata) {
  2590. [metadatas addObject:metadata];
  2591. }
  2592. }
  2593. // [CCUtility getGroupBySettings]
  2594. sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:metadatas listProgressMetadata:nil groupByField:nil filterocId:appDelegate.filterocId filterTypeFileImage:NO filterTypeFileVideo:NO sorted:@"fileName" ascending:NO activeAccount:appDelegate.activeAccount];
  2595. [self tableViewReloadData];
  2596. if ([sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  2597. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  2598. _noFilesSearchDescription = @"";
  2599. }
  2600. if ([sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  2601. _noFilesSearchTitle = @"";
  2602. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  2603. }
  2604. [self.tableView reloadEmptyDataSet];
  2605. return;
  2606. }
  2607. // Se non siamo nella dir appropriata esci
  2608. if ([serverUrl isEqualToString:self.serverUrl] == NO || self.serverUrl == nil) {
  2609. return;
  2610. }
  2611. // Controllo data lettura Data Source
  2612. tableDirectory *tableDirectory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, serverUrl]];
  2613. if (tableDirectory == nil) {
  2614. return;
  2615. }
  2616. // Get MetadataFolder
  2617. if ([serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]])
  2618. _metadataFolder = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, k_serverUrl_root]];
  2619. else
  2620. _metadataFolder = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", tableDirectory.ocId]];
  2621. // Remove optimization for encrypted directory
  2622. if (_metadataFolder.e2eEncrypted)
  2623. _dateReadDataSource = nil;
  2624. NSDate *dateDateRecordDirectory = tableDirectory.dateReadDirectory;
  2625. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  2626. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  2627. _dateReadDataSource = [NSDate date];
  2628. // Data Source
  2629. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  2630. CCSectionDataSourceMetadata *sectionDataSourceTemp = [self queryDatasourceWithReloadData:NO serverUrl:serverUrl];
  2631. dispatch_async(dispatch_get_main_queue(), ^{
  2632. sectionDataSource = sectionDataSourceTemp;
  2633. [self tableViewReloadData];
  2634. });
  2635. });
  2636. } else {
  2637. [self tableViewReloadData];
  2638. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  2639. }
  2640. // BLINK
  2641. if (self.blinkFileNamePath != nil) {
  2642. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  2643. for (NSString *key in sectionDataSource.allRecordsDataSource) {
  2644. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:key];
  2645. NSString *metadataFileNamePath = [NSString stringWithFormat:@"%@/%@", metadata.serverUrl, metadata.fileName];
  2646. if ([metadataFileNamePath isEqualToString:self.blinkFileNamePath]) {
  2647. for (NSString *key in sectionDataSource.ocIdIndexPath) {
  2648. if ([key isEqualToString:metadata.ocId]) {
  2649. NSIndexPath *indexPath = [sectionDataSource.ocIdIndexPath objectForKey:key];
  2650. [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
  2651. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  2652. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  2653. if (cell) {
  2654. self.blinkFileNamePath = nil;
  2655. [[NCUtility sharedInstance] blinkWithCell:cell];
  2656. }
  2657. });
  2658. }
  2659. }
  2660. }
  2661. }
  2662. });
  2663. }
  2664. }
  2665. - (CCSectionDataSourceMetadata *)queryDatasourceWithReloadData:(BOOL)withReloadData serverUrl:(NSString *)serverUrl
  2666. {
  2667. // test
  2668. if (appDelegate.activeAccount.length == 0 || serverUrl == nil) {
  2669. return nil;
  2670. }
  2671. // get auto upload folder
  2672. _autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  2673. _autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:appDelegate.activeUrl];
  2674. CCSectionDataSourceMetadata *sectionDataSourceTemp = [CCSectionDataSourceMetadata new];
  2675. NSArray *recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND status != %i", appDelegate.activeAccount, serverUrl, k_metadataStatusHide] sorted:nil ascending:NO];
  2676. // [CCUtility getGroupBySettings]
  2677. sectionDataSourceTemp = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:nil filterocId:appDelegate.filterocId filterTypeFileImage:NO filterTypeFileVideo:NO sorted:[CCUtility getOrderSettings] ascending:[CCUtility getAscendingSettings] activeAccount:appDelegate.activeAccount];
  2678. if (withReloadData) {
  2679. sectionDataSource = sectionDataSourceTemp;
  2680. [self tableViewReloadData];
  2681. }
  2682. return sectionDataSourceTemp;
  2683. }
  2684. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  2685. {
  2686. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  2687. if (selectedRows.count > 0) {
  2688. for (NSIndexPath *selectionIndex in selectedRows) {
  2689. NSString *ocId = [[sectionDataSource.sectionArrayRow objectForKey:[sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  2690. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:ocId];
  2691. [metadatas addObject:metadata];
  2692. }
  2693. }
  2694. return metadatas;
  2695. }
  2696. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  2697. {
  2698. NSInteger totSections =[sectionDataSource.sections count] ;
  2699. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  2700. return nil;
  2701. }
  2702. id valueSection = [sectionDataSource.sections objectAtIndex:section];
  2703. return [sectionDataSource.sectionArrayRow objectForKey:valueSection];
  2704. }
  2705. #pragma --------------------------------------------------------------------------------------------
  2706. #pragma mark - ==== Table ====
  2707. #pragma --------------------------------------------------------------------------------------------
  2708. - (void)tableViewSelect:(BOOL)edit
  2709. {
  2710. // chiudiamo eventuali swipe aperti
  2711. if (edit)
  2712. [self.tableView setEditing:NO animated:NO];
  2713. [self.tableView setAllowsMultipleSelectionDuringEditing:edit];
  2714. [self.tableView setEditing:edit animated:YES];
  2715. _isSelectedMode = edit;
  2716. if (edit)
  2717. [self setUINavigationBarSelected];
  2718. else
  2719. [self setUINavigationBarDefault];
  2720. [_selectedocIdsMetadatas removeAllObjects];
  2721. [self setTitle];
  2722. }
  2723. - (void)tableViewReloadData
  2724. {
  2725. // store selected cells before relod
  2726. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  2727. // reload table view
  2728. [self.tableView reloadData];
  2729. // selected cells stored
  2730. for (NSIndexPath *path in indexPaths)
  2731. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  2732. [self setTableViewHeader];
  2733. [self setTableViewFooter];
  2734. if (self.tableView.editing)
  2735. [self setTitle];
  2736. [self.tableView reloadEmptyDataSet];
  2737. }
  2738. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  2739. {
  2740. if (tableView.editing == 1) {
  2741. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2742. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  2743. return NO;
  2744. if (metadata == nil || metadata.status != k_metadataStatusNormal)
  2745. return NO;
  2746. else
  2747. return YES;
  2748. } else {
  2749. [_selectedocIdsMetadatas removeAllObjects];
  2750. }
  2751. return YES;
  2752. }
  2753. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  2754. {
  2755. return 60;
  2756. }
  2757. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  2758. {
  2759. return [[sectionDataSource.sectionArrayRow allKeys] count];
  2760. }
  2761. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  2762. {
  2763. return [[sectionDataSource.sectionArrayRow objectForKey:[sectionDataSource.sections objectAtIndex:section]] count];
  2764. }
  2765. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  2766. {
  2767. NSArray *sections = [sectionDataSource.sectionArrayRow allKeys];
  2768. NSString *sectionTitle = [sections objectAtIndex:section];
  2769. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  2770. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  2771. if ([[CCUtility getGroupBySettings] isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  2772. return 20.f;
  2773. }
  2774. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  2775. {
  2776. float shift;
  2777. UIVisualEffectView *visualEffectView;
  2778. NSString *titleSection;
  2779. if (![self indexPathIsValid:[NSIndexPath indexPathForRow:0 inSection:section]])
  2780. return nil;
  2781. if ([[sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]])
  2782. titleSection = [sectionDataSource.sections objectAtIndex:section];
  2783. if ([[sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]])
  2784. titleSection = [CCUtility getTitleSectionDate:[sectionDataSource.sections objectAtIndex:section]];
  2785. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  2786. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  2787. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  2788. else titleSection = NSLocalizedString(titleSection,nil);
  2789. // Format title
  2790. UIVisualEffect *blurEffect;
  2791. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  2792. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  2793. visualEffectView.backgroundColor = [NCBrandColor.sharedInstance.brand colorWithAlphaComponent:0.2];
  2794. if ([[CCUtility getGroupBySettings] isEqualToString:@"alphabetic"]) {
  2795. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  2796. shift = - 35;
  2797. else
  2798. shift = - 20;
  2799. } else shift = - 10;
  2800. // Title
  2801. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  2802. titleLabel.backgroundColor = [UIColor clearColor];
  2803. titleLabel.textColor = NCBrandColor.sharedInstance.textView;
  2804. titleLabel.font = [UIFont systemFontOfSize:12];
  2805. titleLabel.textAlignment = NSTextAlignmentLeft;
  2806. titleLabel.text = titleSection;
  2807. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  2808. [visualEffectView.contentView addSubview:titleLabel];
  2809. // Elements
  2810. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  2811. elementLabel.backgroundColor = [UIColor clearColor];
  2812. elementLabel.textColor = NCBrandColor.sharedInstance.textView;
  2813. elementLabel.font = [UIFont systemFontOfSize:12];
  2814. elementLabel.textAlignment = NSTextAlignmentRight;
  2815. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  2816. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  2817. NSUInteger rowsCount = [metadatas count];
  2818. if (rowsCount == 0) return nil;
  2819. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  2820. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  2821. [visualEffectView.contentView addSubview:elementLabel];
  2822. return visualEffectView;
  2823. }
  2824. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  2825. {
  2826. return [sectionDataSource.sections indexOfObject:title];
  2827. }
  2828. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  2829. {
  2830. if ([[CCUtility getGroupBySettings] isEqualToString:@"alphabetic"])
  2831. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  2832. else
  2833. return nil;
  2834. }
  2835. /*
  2836. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  2837. {
  2838. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  2839. }
  2840. }
  2841. */
  2842. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  2843. {
  2844. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2845. tableShare *shareCell;
  2846. if (metadata == nil || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata] || (_metadataFolder != nil && [[NCManageDatabase sharedInstance] isTableInvalidated:_metadataFolder])) {
  2847. return [CCCellMain new];
  2848. }
  2849. for (tableShare *share in appDelegate.shares) {
  2850. if ([share.serverUrl isEqualToString:metadata.serverUrl] && [share.fileName isEqualToString:metadata.fileName]) {
  2851. shareCell = share;
  2852. break;
  2853. }
  2854. }
  2855. UITableViewCell *cell = [[NCMainCommon sharedInstance] cellForRowAtIndexPath:indexPath tableView:tableView metadata:metadata metadataFolder:_metadataFolder serverUrl:self.serverUrl autoUploadFileName:_autoUploadFileName autoUploadDirectory:_autoUploadDirectory tableShare:shareCell];
  2856. // NORMAL - > MAIN
  2857. if ([cell isKindOfClass:[CCCellMain class]]) {
  2858. // Comment tap
  2859. if (metadata.commentsUnread) {
  2860. UITapGestureRecognizer *tapComment = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionComment:)];
  2861. [tapComment setNumberOfTapsRequired:1];
  2862. ((CCCellMain *)cell).comment.userInteractionEnabled = YES;
  2863. [((CCCellMain *)cell).comment addGestureRecognizer:tapComment];
  2864. }
  2865. // Share add Tap
  2866. UITapGestureRecognizer *tapShare = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  2867. [tapShare setNumberOfTapsRequired:1];
  2868. ((CCCellMain *)cell).viewShared.userInteractionEnabled = YES;
  2869. [((CCCellMain *)cell).viewShared addGestureRecognizer:tapShare];
  2870. // More
  2871. if ([self canOpenMenuAction:metadata]) {
  2872. UITapGestureRecognizer *tapMore = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionMore:)];
  2873. [tapMore setNumberOfTapsRequired:1];
  2874. ((CCCellMain *)cell).more.userInteractionEnabled = YES;
  2875. [((CCCellMain *)cell).more addGestureRecognizer:tapMore];
  2876. }
  2877. // MGSwipeButton
  2878. ((CCCellMain *)cell).delegate = self;
  2879. // LEFT
  2880. ((CCCellMain *)cell).leftButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:self.cellFavouriteImage backgroundColor:NCBrandColor.sharedInstance.yellowFavorite padding:25]];
  2881. ((CCCellMain *)cell).leftExpansion.buttonIndex = 0;
  2882. ((CCCellMain *)cell).leftExpansion.fillOnTrigger = NO;
  2883. //centerIconOverText
  2884. MGSwipeButton *favoriteButton = (MGSwipeButton *)[((CCCellMain *)cell).leftButtons objectAtIndex:0];
  2885. [favoriteButton centerIconOverText];
  2886. // RIGHT
  2887. ((CCCellMain *)cell).rightButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:self.cellTrashImage backgroundColor:[UIColor redColor] padding:25]];
  2888. ((CCCellMain *)cell).rightExpansion.buttonIndex = 0;
  2889. ((CCCellMain *)cell).rightExpansion.fillOnTrigger = NO;
  2890. //centerIconOverText
  2891. MGSwipeButton *deleteButton = (MGSwipeButton *)[((CCCellMain *)cell).rightButtons objectAtIndex:0];
  2892. [deleteButton centerIconOverText];
  2893. }
  2894. // TRANSFER
  2895. if ([cell isKindOfClass:[CCCellMainTransfer class]]) {
  2896. // gesture Transfer
  2897. [((CCCellMainTransfer *)cell).transferButton.stopButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  2898. UILongPressGestureRecognizer *stopLongGesture = [UILongPressGestureRecognizer new];
  2899. [stopLongGesture addTarget:self action:@selector(cancelAllTask:)];
  2900. [((CCCellMainTransfer *)cell).transferButton.stopButton addGestureRecognizer:stopLongGesture];
  2901. }
  2902. return cell;
  2903. }
  2904. - (void)setTableViewHeader
  2905. {
  2906. CGFloat height = UIScreen.mainScreen.bounds.size.height/5;
  2907. // Nextcloud 18
  2908. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilitesWithAccount:appDelegate.activeAccount];
  2909. if (capabilities.versionMajor < k_nextcloud_version_18_0) {
  2910. [self.tableView setTableHeaderView:nil];
  2911. } else {
  2912. if (self.richWorkspace.length == 0) {
  2913. [self.tableView setTableHeaderView:nil];
  2914. } else {
  2915. [self.viewRichWorkspace setRichWorkspaceText:self.richWorkspace gradient:true];
  2916. [self.viewRichWorkspace setFrame:CGRectMake(0, 0, self.tableView.frame.size.width, height)];
  2917. [self.tableView setTableHeaderView:self.viewRichWorkspace];
  2918. }
  2919. }
  2920. [self.tableView reloadData];
  2921. }
  2922. - (void)setTableViewFooter
  2923. {
  2924. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  2925. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  2926. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  2927. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  2928. UIFont *appFont = [UIFont systemFontOfSize:12];
  2929. footerLabel.font = appFont;
  2930. footerLabel.textColor = [UIColor grayColor];
  2931. footerLabel.backgroundColor = [UIColor clearColor];
  2932. footerLabel.textAlignment = NSTextAlignmentCenter;
  2933. NSString *folders;
  2934. NSString *files;
  2935. NSString *footerText;
  2936. if (sectionDataSource.directories > 1) {
  2937. folders = [NSString stringWithFormat:@"%ld %@", (long)sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  2938. } else if (sectionDataSource.directories == 1){
  2939. folders = [NSString stringWithFormat:@"%ld %@", (long)sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  2940. } else {
  2941. folders = @"";
  2942. }
  2943. if (sectionDataSource.files > 1) {
  2944. files = [NSString stringWithFormat:@"%ld %@ %@", (long)sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:sectionDataSource.totalSize]];
  2945. } else if (sectionDataSource.files == 1){
  2946. files = [NSString stringWithFormat:@"%ld %@ %@", (long)sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:sectionDataSource.totalSize]];
  2947. } else {
  2948. files = @"";
  2949. }
  2950. if ([folders isEqualToString:@""]) {
  2951. footerText = files;
  2952. } else if ([files isEqualToString:@""]) {
  2953. footerText = folders;
  2954. } else {
  2955. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  2956. }
  2957. footerLabel.text = footerText;
  2958. [footerView addSubview:footerLabel];
  2959. [self.tableView setTableFooterView:footerView];
  2960. }
  2961. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  2962. {
  2963. CCCellMain *cell = [tableView cellForRowAtIndexPath:indexPath];
  2964. // settiamo il record file.
  2965. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2966. if (!self.metadata)
  2967. return;
  2968. // se non può essere selezionata deseleziona
  2969. if ([cell isEditing] == NO)
  2970. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  2971. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  2972. if (self.tableView.editing) {
  2973. [_selectedocIdsMetadatas setObject:self.metadata forKey:self.metadata.ocId];
  2974. [self setTitle];
  2975. return;
  2976. }
  2977. // se è in corso una sessione
  2978. if (self.metadata.status != k_metadataStatusNormal)
  2979. return;
  2980. // file
  2981. if (self.metadata.directory == NO) {
  2982. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  2983. if ([CCUtility fileProviderStorageExists:self.metadata.ocId fileNameView:self.metadata.fileNameView]) {
  2984. [[NCNetworkingMain sharedInstance] downloadFileSuccessFailure:self.metadata.fileName ocId:self.metadata.ocId serverUrl:self.metadata.serverUrl selector:selectorLoadFileView errorMessage:@"" errorCode:0];
  2985. } else {
  2986. if (_metadataFolder.e2eEncrypted && ![CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  2987. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  2988. } else {
  2989. 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) {
  2990. [self shouldPerformSegue:self.metadata selector:@""];
  2991. } else if ([self.metadata.typeFile isEqualToString: k_metadataTypeFile_document] && [[NCUtility sharedInstance] isDirectEditing:self.metadata] != nil) {
  2992. if (appDelegate.reachability.isReachable) {
  2993. [self shouldPerformSegue:self.metadata selector:@""];
  2994. } else {
  2995. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_go_online_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  2996. }
  2997. } else if ([self.metadata.typeFile isEqualToString: k_metadataTypeFile_document] && [[NCUtility sharedInstance] isRichDocument:self.metadata]) {
  2998. if (appDelegate.reachability.isReachable) {
  2999. [self shouldPerformSegue:self.metadata selector:@""];
  3000. } else {
  3001. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_go_online_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  3002. }
  3003. } else {
  3004. self.metadata.session = k_download_session;
  3005. self.metadata.sessionError = @"";
  3006. self.metadata.sessionSelector = selectorLoadFileView;
  3007. self.metadata.status = k_metadataStatusWaitDownload;
  3008. // Add Metadata for Download
  3009. (void)[[NCManageDatabase sharedInstance] addMetadata:self.metadata];
  3010. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:self.metadata.ocId action:k_action_MOD];
  3011. [appDelegate startLoadAutoDownloadUpload];
  3012. }
  3013. }
  3014. }
  3015. }
  3016. if (self.metadata.directory) {
  3017. [self performSegueDirectoryWithControlPasscode:true metadata:self.metadata blinkFileNamePath:self.blinkFileNamePath];
  3018. }
  3019. }
  3020. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  3021. {
  3022. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  3023. [_selectedocIdsMetadatas removeObjectForKey:metadata.ocId];
  3024. [self setTitle];
  3025. }
  3026. - (void)didSelectAll
  3027. {
  3028. for (int i = 0; i < self.tableView.numberOfSections; i++) {
  3029. for (int j = 0; j < [self.tableView numberOfRowsInSection:i]; j++) {
  3030. NSIndexPath *indexPath = [NSIndexPath indexPathForRow:j inSection:i];
  3031. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  3032. [_selectedocIdsMetadatas setObject:metadata forKey:metadata.ocId];
  3033. [self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
  3034. }
  3035. }
  3036. [self setTitle];
  3037. }
  3038. - (BOOL)indexPathIsValid:(NSIndexPath *)indexPath
  3039. {
  3040. if (!indexPath)
  3041. return NO;
  3042. NSInteger section = indexPath.section;
  3043. NSInteger row = indexPath.row;
  3044. NSInteger lastSectionIndex = [self numberOfSectionsInTableView:self.tableView] - 1;
  3045. if (section > lastSectionIndex || lastSectionIndex < 0)
  3046. return NO;
  3047. NSInteger rowCount = [self.tableView numberOfRowsInSection:indexPath.section] - 1;
  3048. if (rowCount < 0)
  3049. return NO;
  3050. return row <= rowCount;
  3051. }
  3052. #pragma --------------------------------------------------------------------------------------------
  3053. #pragma mark ===== Navigation ====
  3054. #pragma --------------------------------------------------------------------------------------------
  3055. - (void)shouldPerformSegue:(tableMetadata *)metadata selector:(NSString *)selector
  3056. {
  3057. // if background return
  3058. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return;
  3059. if (self.view.window == NO)
  3060. return;
  3061. // Collapsed ma siamo già in detail esci
  3062. if (self.splitViewController.isCollapsed)
  3063. if (_detailViewController.isViewLoaded && _detailViewController.view.window) return;
  3064. // Metadata for push detail
  3065. self.metadataForPushDetail = metadata;
  3066. self.selectorForPushDetail = selector;
  3067. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  3068. }
  3069. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  3070. {
  3071. id viewController = segue.destinationViewController;
  3072. tableMetadata *metadata;
  3073. if ([viewController isKindOfClass:[UINavigationController class]]) {
  3074. UINavigationController *nav = viewController;
  3075. _detailViewController = (CCDetail *)nav.topViewController;
  3076. } else {
  3077. _detailViewController = segue.destinationViewController;
  3078. }
  3079. NSMutableArray *photoDataSource = [NSMutableArray new];
  3080. if ([sender isKindOfClass:[tableMetadata class]]) {
  3081. metadata = sender;
  3082. [photoDataSource addObject:sender];
  3083. } else {
  3084. metadata = self.metadataForPushDetail;
  3085. for (NSString *ocId in sectionDataSource.allOcId) {
  3086. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:ocId];
  3087. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  3088. [photoDataSource addObject:metadata];
  3089. }
  3090. }
  3091. _detailViewController.metadataDetail = metadata;
  3092. _detailViewController.selectorDetail = self.selectorForPushDetail;
  3093. _detailViewController.photoDataSource = photoDataSource;
  3094. _detailViewController.dateFilterQuery = nil;
  3095. [_detailViewController setTitle:metadata.fileNameView];
  3096. }
  3097. // can i go to next viewcontroller
  3098. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode metadata:(tableMetadata *)metadata blinkFileNamePath:(NSString *)blinkFileNamePath
  3099. {
  3100. NSString *nomeDir;
  3101. if (self.tableView.editing == NO) {
  3102. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:metadata.serverUrl addFileName:metadata.fileName];
  3103. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", metadata.account, lockServerUrl]];
  3104. // 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
  3105. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil && controlPasscode) {
  3106. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  3107. viewController.delegate = self;
  3108. viewController.fromType = CCBKPasscodeFromLockDirectory;
  3109. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  3110. viewController.inputViewTitlePassword = YES;
  3111. if ([CCUtility getSimplyBlockCode]) {
  3112. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  3113. viewController.passcodeInputView.maximumLength = 6;
  3114. } else {
  3115. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  3116. viewController.passcodeInputView.maximumLength = 64;
  3117. }
  3118. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  3119. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  3120. viewController.touchIDManager = touchIDManager;
  3121. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  3122. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  3123. viewController.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
  3124. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  3125. navigationController.modalPresentationStyle = UIModalPresentationFullScreen;
  3126. [self presentViewController:navigationController animated:YES completion:nil];
  3127. return;
  3128. }
  3129. // E2EE Check enable
  3130. if (metadata.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount] == NO) {
  3131. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  3132. return;
  3133. }
  3134. nomeDir = metadata.fileName;
  3135. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:metadata.serverUrl addFileName:nomeDir];
  3136. CCMain *viewController = [appDelegate.listMainVC objectForKey:serverUrlPush];
  3137. if (!viewController) {
  3138. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMain"];
  3139. viewController.serverUrl = serverUrlPush;
  3140. viewController.titleMain = metadata.fileName;
  3141. viewController.blinkFileNamePath = blinkFileNamePath;
  3142. // save self
  3143. [appDelegate.listMainVC setObject:viewController forKey:serverUrlPush];
  3144. [self.navigationController pushViewController:viewController animated:YES];
  3145. } else {
  3146. if (viewController.isViewLoaded) {
  3147. viewController.titleMain = metadata.fileName;
  3148. viewController.blinkFileNamePath = blinkFileNamePath;
  3149. // Fix : Application tried to present modally an active controller
  3150. if ([self.navigationController isBeingPresented]) {
  3151. // being presented
  3152. } else if ([self.navigationController isMovingToParentViewController]) {
  3153. // being pushed
  3154. } else {
  3155. [self.navigationController pushViewController:viewController animated:YES];
  3156. }
  3157. }
  3158. }
  3159. }
  3160. }
  3161. @end