CCMain.m 203 KB

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