CCMain.m 206 KB

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