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