CCMain.m 208 KB

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