CCMain.m 210 KB

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