CCMain.m 225 KB

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