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