CCMain.m 228 KB

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