CCMain.m 204 KB

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