CCMain.m 207 KB

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