CCMain.m 211 KB

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