CCMain.m 206 KB

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