CCMain.m 229 KB

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