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