CCMain.m 221 KB

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