CCMain.m 206 KB

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