CCMain.m 225 KB

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