CCMain.m 208 KB

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