CCMain.m 208 KB

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