CCMain.m 203 KB

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