CCMain.m 205 KB

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