CCMain.m 210 KB

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