CCMain.m 215 KB

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