CCMain.m 229 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176
  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.path = appDelegate.directoryUser;
  993. metadataNet.session = session;
  994. metadataNet.sessionError = @"";
  995. metadataNet.sessionID = @"";
  996. metadataNet.selector = selectorUploadFile;
  997. metadataNet.selectorPost = nil;
  998. metadataNet.serverUrl = serverUrl;
  999. metadataNet.taskStatus = k_taskStatusResume;
  1000. // Check il file already exists
  1001. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileNameView = %@", appDelegate.activeAccount, directoryID, fileName]];
  1002. if (metadata) {
  1003. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:fileName message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1004. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  1005. // NO OVERWITE
  1006. }];
  1007. UIAlertAction *overwriteAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_overwrite_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  1008. // Send to Upload Queue
  1009. (void)[[NCManageDatabase sharedInstance] addQueueUploadWithMetadataNet:metadataNet];
  1010. // Start upload now
  1011. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUpload] waitUntilDone:NO];
  1012. }];
  1013. [alertController addAction:cancelAction];
  1014. [alertController addAction:overwriteAction];
  1015. UIWindow *alertWindow = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
  1016. alertWindow.rootViewController = [[UIViewController alloc]init];
  1017. alertWindow.windowLevel = UIWindowLevelAlert + 1;
  1018. [alertWindow makeKeyAndVisible];
  1019. [alertWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
  1020. } else {
  1021. // Send to Upload Queue
  1022. (void)[[NCManageDatabase sharedInstance] addQueueUploadWithMetadataNet:metadataNet];
  1023. // Start upload now
  1024. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUpload] waitUntilDone:NO];
  1025. }
  1026. }
  1027. }
  1028. #pragma --------------------------------------------------------------------------------------------
  1029. #pragma mark ==== Read File ====
  1030. #pragma --------------------------------------------------------------------------------------------
  1031. - (void)readFileSuccessFailure:(CCMetadataNet *)metadataNet metadata:(tableMetadata *)metadata message:(NSString *)message errorCode:(NSInteger)errorCode
  1032. {
  1033. // Check Active Account
  1034. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1035. return;
  1036. if (errorCode == 0) {
  1037. // Read Folder
  1038. if ([metadataNet.selector isEqualToString:selectorReadFileReloadFolder]) {
  1039. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", metadataNet.account, metadataNet.serverUrl]];
  1040. // Change etag, read folder
  1041. if ([metadata.etag isEqualToString:directory.etag] == NO) {
  1042. [self readFolder:metadataNet.serverUrl];
  1043. }
  1044. }
  1045. } else {
  1046. // Unauthorized
  1047. if (errorCode == kOCErrorServerUnauthorized)
  1048. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  1049. }
  1050. }
  1051. - (void)readFileReloadFolder
  1052. {
  1053. if (!_serverUrl || !appDelegate.activeAccount || appDelegate.maintenanceMode)
  1054. return;
  1055. // Load Datasource
  1056. [self reloadDatasource];
  1057. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1058. metadataNet.action = actionReadFile;
  1059. metadataNet.priority = NSOperationQueuePriorityHigh;
  1060. metadataNet.selector = selectorReadFileReloadFolder;
  1061. metadataNet.serverUrl = _serverUrl;
  1062. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1063. }
  1064. #pragma --------------------------------------------------------------------------------------------
  1065. #pragma mark ==== Read Folder ====
  1066. #pragma --------------------------------------------------------------------------------------------
  1067. - (void)readFolderSuccessFailure:(CCMetadataNet *)metadataNet metadataFolder:(tableMetadata *)metadataFolder metadatas:(NSArray *)metadatas message:(NSString *)message errorCode:(NSInteger)errorCode
  1068. {
  1069. // stoprefresh
  1070. [_refreshControl endRefreshing];
  1071. // Check Active Account
  1072. if (![metadataNet.account isEqualToString:metadataNet.account])
  1073. return;
  1074. // ERROR
  1075. if (errorCode != 0) {
  1076. _loadingFolder = NO;
  1077. // Check Active Account
  1078. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1079. return;
  1080. // Unauthorized
  1081. if (errorCode == kOCErrorServerUnauthorized) {
  1082. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  1083. } else {
  1084. [self tableViewReloadData];
  1085. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1086. [appDelegate messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1087. [self reloadDatasource:metadataNet.serverUrl];
  1088. }
  1089. return;
  1090. }
  1091. // save metadataFolder
  1092. _metadataFolder = metadataFolder;
  1093. // save father e update permission
  1094. if(!_isSearchMode && metadataFolder)
  1095. _fatherPermission = metadataFolder.permissions;
  1096. NSArray *recordsInSessions;
  1097. NSMutableArray *metadatasToInsertInDB = [NSMutableArray new];
  1098. if (_isSearchMode) {
  1099. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session != ''", metadataNet.account] sorted:nil ascending:NO];
  1100. } else {
  1101. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:metadataNet.serverUrl serverUrlTo:nil etag:metadataFolder.etag fileID:metadataFolder.fileID encrypted:metadataFolder.e2eEncrypted];
  1102. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session = ''", metadataNet.account, metadataNet.directoryID] clearDateReadDirectoryID:metadataNet.directoryID];
  1103. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session != ''", metadataNet.account, metadataNet.directoryID] sorted:nil ascending:NO];
  1104. [[NCManageDatabase sharedInstance] setDateReadDirectoryWithDirectoryID:metadataNet.directoryID];
  1105. }
  1106. for (tableMetadata *metadata in metadatas) {
  1107. // verify if the record is in download/upload progress
  1108. if (metadata.directory == NO && [recordsInSessions count] > 0) {
  1109. tableMetadata *metadataTransfer = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileName = %@", appDelegate.activeAccount, metadataNet.directoryID, metadata.fileName]];
  1110. // is in Download or Upload
  1111. if ([metadataTransfer.session containsString:@"upload"] || [metadataTransfer.session containsString:@"download"]) {
  1112. continue;
  1113. }
  1114. }
  1115. // Insert in Array
  1116. [metadatasToInsertInDB addObject:metadata];
  1117. }
  1118. // insert in Database
  1119. metadatasToInsertInDB = (NSMutableArray *)[[NCManageDatabase sharedInstance] addMetadatas:metadatasToInsertInDB serverUrl:metadataNet.serverUrl];
  1120. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1121. // File is changed ??
  1122. if (!_isSearchMode && metadatasToInsertInDB)
  1123. [[CCSynchronize sharedSynchronize] verifyChangeMedatas:metadatasToInsertInDB serverUrl:metadataNet.serverUrl account:appDelegate.activeAccount withDownload:NO];
  1124. });
  1125. // Search Mode
  1126. if (_isSearchMode) {
  1127. // Fix managed -> Unmanaged _searchResultMetadatas
  1128. if (metadatasToInsertInDB)
  1129. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatasToInsertInDB];
  1130. [self reloadDatasource:metadataNet.serverUrl];
  1131. }
  1132. // this is the same directory
  1133. if ([metadataNet.serverUrl isEqualToString:_serverUrl] && !_isSearchMode) {
  1134. // reload
  1135. [self reloadDatasource:metadataNet.serverUrl];
  1136. // Enable change user
  1137. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1138. _loadingFolder = NO;
  1139. [self tableViewReloadData];
  1140. }
  1141. // E2EE Is encrypted folder get metadata
  1142. if (_metadataFolder.e2eEncrypted) {
  1143. // Read Metadata
  1144. if ([CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  1145. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1146. NSString *metadata;
  1147. NSError *error = [[NCNetworkingEndToEnd sharedManager] getEndToEndMetadata:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl fileID:metadataFolder.fileID metadata:&metadata];
  1148. dispatch_async(dispatch_get_main_queue(), ^{
  1149. if (error) {
  1150. if (error.code != 404)
  1151. [appDelegate messageNotification:@"_e2e_error_get_metadata_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  1152. } else {
  1153. if ([[NCEndToEndMetadata sharedInstance] decoderMetadata:metadata privateKey:[CCUtility getEndToEndPrivateKey:appDelegate.activeAccount] serverUrl:self.serverUrl account:appDelegate.activeAccount url:appDelegate.activeUrl] == false)
  1154. [appDelegate messageNotification:@"_error_e2ee_" description:@"_e2e_error_decode_metadata_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  1155. else
  1156. [self reloadDatasource];
  1157. }
  1158. });
  1159. });
  1160. } else {
  1161. [appDelegate messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  1162. }
  1163. }
  1164. // rewrite title
  1165. [self setTitle];
  1166. }
  1167. - (void)readFolder:(NSString *)serverUrl
  1168. {
  1169. // init control
  1170. if (!serverUrl || !appDelegate.activeAccount || appDelegate.maintenanceMode) {
  1171. [_refreshControl endRefreshing];
  1172. return;
  1173. }
  1174. // Search Mode
  1175. if (_isSearchMode) {
  1176. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrl directoryID:nil];
  1177. _searchFileName = @""; // forced reload searchg
  1178. [self updateSearchResultsForSearchController:self.searchController];
  1179. return;
  1180. }
  1181. _loadingFolder = YES;
  1182. [self tableViewReloadData];
  1183. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, serverUrl]];
  1184. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1185. metadataNet.action = actionReadFolder;
  1186. metadataNet.date = [NSDate date];
  1187. metadataNet.depth = @"1";
  1188. metadataNet.directoryID = directory.directoryID;
  1189. metadataNet.priority = NSOperationQueuePriorityHigh;
  1190. metadataNet.selector = selectorReadFolder;
  1191. metadataNet.serverUrl = serverUrl;
  1192. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1193. }
  1194. #pragma mark -
  1195. #pragma --------------------------------------------------------------------------------------------
  1196. #pragma mark ===== Search =====
  1197. #pragma --------------------------------------------------------------------------------------------
  1198. - (void)searchEnabled:(BOOL)enabled
  1199. {
  1200. if (enabled) {
  1201. if (self.tableView.tableHeaderView != nil)
  1202. return;
  1203. self.definesPresentationContext = YES;
  1204. self.searchController.searchResultsUpdater = self;
  1205. self.searchController.dimsBackgroundDuringPresentation = NO;
  1206. self.searchController.searchBar.translucent = NO;
  1207. [self.searchController.searchBar sizeToFit];
  1208. self.searchController.searchBar.delegate = self;
  1209. self.searchController.searchBar.barTintColor = [NCBrandColor sharedInstance].brand;
  1210. self.searchController.searchBar.backgroundColor = [NCBrandColor sharedInstance].brand;
  1211. self.searchController.searchBar.backgroundImage = [UIImage new];
  1212. // color searchbbar button text (cancel)
  1213. UIButton *searchButton = self.searchController.searchBar.subviews.firstObject.subviews.lastObject;
  1214. if (searchButton && [searchButton isKindOfClass:[UIButton class]]) {
  1215. [searchButton setTitleColor:[NCBrandColor sharedInstance].brandText forState:UIControlStateNormal];
  1216. }
  1217. self.tableView.tableHeaderView = self.searchController.searchBar;
  1218. [self.tableView setContentOffset:CGPointMake(0, self.searchController.searchBar.frame.size.height - self.tableView.contentOffset.y)];
  1219. } else {
  1220. self.tableView.tableHeaderView = nil;
  1221. }
  1222. }
  1223. - (void)searchStartTimer
  1224. {
  1225. NSString *startDirectory = [CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl];
  1226. [[CCActions sharedInstance] search:startDirectory fileName:_searchFileName etag:@"" depth:@"infinity" date:nil contenType:nil selector:selectorSearchFiles delegate:self];
  1227. _noFilesSearchTitle = @"";
  1228. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  1229. [self.tableView reloadEmptyDataSet];
  1230. }
  1231. - (void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1232. {
  1233. // Color text "Cancel"
  1234. [[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTintColor:[NCBrandColor sharedInstance].brandText];
  1235. _isSearchMode = YES;
  1236. [self deleteRefreshControl];
  1237. NSString *fileName = [CCUtility removeForbiddenCharactersServer:searchController.searchBar.text];
  1238. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1239. _searchFileName = fileName;
  1240. // First : filter
  1241. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1242. if (!directoryID) return;
  1243. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"directoryID = %@ AND account = %@ AND fileNameView CONTAINS[cd] %@", directoryID, appDelegate.activeAccount, fileName];
  1244. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1245. [_searchResultMetadatas removeAllObjects];
  1246. for (tableMetadata *record in records)
  1247. [_searchResultMetadatas addObject:record];
  1248. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1249. metadataNet.account = appDelegate.activeAccount;
  1250. metadataNet.directoryID = directoryID;
  1251. metadataNet.selector = selectorSearchFiles;
  1252. metadataNet.serverUrl = _serverUrl;
  1253. [self readFolderSuccessFailure:metadataNet metadataFolder:nil metadatas:_searchResultMetadatas message:nil errorCode:0];
  1254. // Version >= 12
  1255. if ([[NCManageDatabase sharedInstance] getServerVersion] >= 12) {
  1256. [_timerWaitInput invalidate];
  1257. _timerWaitInput = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(searchStartTimer) userInfo:nil repeats:NO];
  1258. }
  1259. }
  1260. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1261. [self reloadDatasource];
  1262. }
  1263. }
  1264. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1265. {
  1266. [self cancelSearchBar];
  1267. [self readFolder:_serverUrl];
  1268. }
  1269. - (void)searchSuccessFailure:(CCMetadataNet *)metadataNet metadatas:(NSArray *)metadatas message:(NSString *)message errorCode:(NSInteger)errorCode
  1270. {
  1271. // Check Active Account
  1272. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1273. return;
  1274. if (errorCode == 0) {
  1275. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatas];
  1276. [self readFolderSuccessFailure:metadataNet metadataFolder:nil metadatas:metadatas message:nil errorCode:0];
  1277. } else {
  1278. // Unauthorized
  1279. if (errorCode == kOCErrorServerUnauthorized)
  1280. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  1281. else
  1282. [appDelegate messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1283. _searchFileName = @"";
  1284. }
  1285. }
  1286. - (void)cancelSearchBar
  1287. {
  1288. if (self.searchController.active) {
  1289. [self.searchController setActive:NO];
  1290. [self createRefreshControl];
  1291. _isSearchMode = NO;
  1292. _searchFileName = @"";
  1293. _dateReadDataSource = nil;
  1294. _searchResultMetadatas = [NSMutableArray new];
  1295. [self reloadDatasource];
  1296. }
  1297. //[self setNeedsStatusBarAppearanceUpdate];
  1298. }
  1299. #pragma mark -
  1300. #pragma --------------------------------------------------------------------------------------------
  1301. #pragma mark ===== Delete File or Folder =====
  1302. #pragma --------------------------------------------------------------------------------------------
  1303. - (void)deleteFileOrFolderSuccessFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1304. {
  1305. // Unauthorized
  1306. if (errorCode == kOCErrorServerUnauthorized)
  1307. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  1308. [_queueSelector removeObject:metadataNet.selector];
  1309. if ([_queueSelector count] == 0) {
  1310. [_hud hideHud];
  1311. // next
  1312. [_selectedFileIDsMetadatas removeObjectForKey:metadataNet.fileID];
  1313. if ([_selectedFileIDsMetadatas count] > 0) {
  1314. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1315. [self deleteFileOrFolder:[metadatas objectAtIndex:0] numFile:[_selectedFileIDsMetadatas count] ofFile:_numSelectedFileIDsMetadatas];
  1316. } else {
  1317. // End Select Table View
  1318. [self tableViewSelect:NO];
  1319. // Reload
  1320. if (_isSearchMode)
  1321. [self readFolder:metadataNet.serverUrl];
  1322. else
  1323. [self reloadDatasource:metadataNet.serverUrl];
  1324. }
  1325. }
  1326. }
  1327. - (void)deleteFileOrFolder:(tableMetadata *)metadata numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  1328. {
  1329. [_queueSelector addObject:selectorDelete];
  1330. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self hud:_hud hudTitled:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile]];
  1331. }
  1332. - (void)deleteFile
  1333. {
  1334. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1335. return;
  1336. [_queueSelector removeAllObjects];
  1337. if ([_selectedFileIDsMetadatas count] > 0) {
  1338. _numSelectedFileIDsMetadatas = [_selectedFileIDsMetadatas count];
  1339. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1340. [self deleteFileOrFolder:[metadatas objectAtIndex:0] numFile:[_selectedFileIDsMetadatas count] ofFile:_numSelectedFileIDsMetadatas];
  1341. } else {
  1342. _numSelectedFileIDsMetadatas = 1;
  1343. [self deleteFileOrFolder:_metadata numFile:1 ofFile:_numSelectedFileIDsMetadatas];
  1344. }
  1345. }
  1346. #pragma --------------------------------------------------------------------------------------------
  1347. #pragma mark ===== Rename / Move =====
  1348. #pragma --------------------------------------------------------------------------------------------
  1349. - (void)renameSuccess:(CCMetadataNet *)metadataNet
  1350. {
  1351. [self reloadDatasource:metadataNet.serverUrl];
  1352. }
  1353. - (void)renameFile:(NSArray *)arguments
  1354. {
  1355. tableMetadata* metadata = [arguments objectAtIndex:0];
  1356. NSString *fileName = [arguments objectAtIndex:1];
  1357. // E2EE
  1358. if (_metadataFolder.e2eEncrypted) {
  1359. // verify if exists the new fileName
  1360. if ([[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@ AND fileName = %@", appDelegate.activeAccount, self.serverUrl, fileName]]) {
  1361. [appDelegate messageNotification:@"_error_e2ee_" description:@"_file_already_exists_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  1362. return;
  1363. }
  1364. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  1365. 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];
  1366. if (error) {
  1367. dispatch_async(dispatch_get_main_queue(), ^{
  1368. [appDelegate messageNotification:@"_error_e2ee_" description:@"_e2e_error_send_metadata_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  1369. });
  1370. } else {
  1371. [[NCManageDatabase sharedInstance] setMetadataFileNameViewWithDirectoryID:metadata.directoryID fileName:metadata.fileName newFileNameView:fileName];
  1372. }
  1373. // Unlock
  1374. tableE2eEncryptionLock *tableLock = [[NCManageDatabase sharedInstance] getE2ETokenLockWithServerUrl:self.serverUrl];
  1375. if (tableLock != nil) {
  1376. 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];
  1377. if (error) {
  1378. dispatch_async(dispatch_get_main_queue(), ^{
  1379. [appDelegate messageNotification:@"_e2e_error_unlock_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  1380. });
  1381. }
  1382. }
  1383. dispatch_async(dispatch_get_main_queue(), ^{
  1384. [self reloadDatasource];
  1385. });
  1386. });
  1387. } else {
  1388. // Plain
  1389. [[CCActions sharedInstance] renameFileOrFolder:metadata fileName:fileName delegate:self];
  1390. }
  1391. }
  1392. - (void)renameMoveFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1393. {
  1394. if ([metadataNet.selector isEqualToString:selectorMove]) {
  1395. [_hud hideHud];
  1396. if (message && errorCode != kOCErrorServerUnauthorized)
  1397. [appDelegate messageNotification:@"_move_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1398. // End Select Table View
  1399. [self tableViewSelect:NO];
  1400. // reload Datasource
  1401. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1402. [self readFolder:metadataNet.serverUrl];
  1403. else
  1404. [self reloadDatasource];
  1405. }
  1406. }
  1407. - (void)moveSuccess:(CCMetadataNet *)metadataNet
  1408. {
  1409. [_queueSelector removeObject:metadataNet.selector];
  1410. if ([_queueSelector count] == 0) {
  1411. [_hud hideHud];
  1412. NSString *fileName = metadataNet.fileName;
  1413. NSString *directoryID = metadataNet.directoryID;
  1414. NSString *directoryIDTo = metadataNet.directoryIDTo;
  1415. NSString *serverUrlTo = [[NCManageDatabase sharedInstance] getServerUrl:directoryIDTo];
  1416. if (!serverUrlTo) return;
  1417. // FILE -> Metadata
  1418. if (metadataNet.directory == NO)
  1419. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1420. // DIRECTORY -> Directory - CCMetadata
  1421. if (metadataNet.directory == YES) {
  1422. // delete all dir / subdir
  1423. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:[CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:fileName]];
  1424. // move metadata
  1425. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1426. // Add new directory
  1427. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrlTo, fileName];
  1428. (void) [[NCManageDatabase sharedInstance] addDirectoryWithEncrypted:false favorite:false fileID:nil permissions:nil serverUrl:newDirectory];
  1429. }
  1430. // next
  1431. [_selectedFileIDsMetadatas removeObjectForKey:metadataNet.fileID];
  1432. if ([_selectedFileIDsMetadatas count] > 0) {
  1433. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1434. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrlTo, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1435. } else {
  1436. // End Select Table View
  1437. [self tableViewSelect:NO];
  1438. // reload Datasource
  1439. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1440. [self readFolder:metadataNet.serverUrl];
  1441. else
  1442. [self reloadDatasource];
  1443. }
  1444. }
  1445. }
  1446. - (void)moveFileOrFolderMetadata:(NSArray *)arguments
  1447. {
  1448. tableMetadata *metadata = [arguments objectAtIndex:0];
  1449. NSString *serverUrlTo = [arguments objectAtIndex:1];
  1450. NSInteger numFile = [[arguments objectAtIndex:2] integerValue];
  1451. NSInteger ofFile = [[arguments objectAtIndex:3] integerValue];
  1452. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1453. if (!serverUrl) return;
  1454. NSString *directoryIDTo = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrlTo];
  1455. if (!directoryIDTo) return;
  1456. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:appDelegate.activeUser withUserID:appDelegate.activeUserID withPassword:appDelegate.activePassword withUrl:appDelegate.activeUrl];
  1457. [ocNetworking readFile:metadata.fileName serverUrl:serverUrlTo account:appDelegate.activeAccount success:^(tableMetadata *metadata) {
  1458. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1459. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1460. }];
  1461. [alert addAction:ok];
  1462. [self presentViewController:alert animated:YES completion:nil];
  1463. // End Select Table View
  1464. [self tableViewSelect:NO];
  1465. // reload Datasource
  1466. [self readFileReloadFolder];
  1467. } failure:^(NSString *message, NSInteger errorCode) {
  1468. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1469. metadataNet.action = actionMoveFileOrFolder;
  1470. metadataNet.directory = metadata.directory;
  1471. metadataNet.fileID = metadata.fileID;
  1472. metadataNet.directoryID = metadata.directoryID;
  1473. metadataNet.directoryIDTo = directoryIDTo;
  1474. metadataNet.fileName = metadata.fileName;
  1475. metadataNet.fileNameView = metadata.fileNameView;
  1476. metadataNet.fileNameTo = metadata.fileName;
  1477. metadataNet.etag = metadata.etag;
  1478. metadataNet.selector = selectorMove;
  1479. metadataNet.serverUrl = serverUrl;
  1480. metadataNet.serverUrlTo = serverUrlTo;
  1481. [_queueSelector addObject:metadataNet.selector];
  1482. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1483. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_move_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1484. }];
  1485. }
  1486. // DELEGATE : Move
  1487. - (void)dismissMove
  1488. {
  1489. [self reloadDatasource];
  1490. }
  1491. // DELEGATE : Move
  1492. - (void)moveServerUrlTo:(NSString *)serverUrlTo title:(NSString *)title
  1493. {
  1494. [_queueSelector removeAllObjects];
  1495. // E2EE DENIED
  1496. if ([CCUtility isFolderEncrypted:serverUrlTo account:appDelegate.activeAccount]) {
  1497. [appDelegate messageNotification:@"_move_" description:@"Not possible move files to encrypted directory" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  1498. return;
  1499. }
  1500. if ([_selectedFileIDsMetadatas count] > 0) {
  1501. _numSelectedFileIDsMetadatas = [_selectedFileIDsMetadatas count];
  1502. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1503. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrlTo, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1504. } else {
  1505. _numSelectedFileIDsMetadatas = 1;
  1506. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[_metadata, serverUrlTo, [NSNumber numberWithInteger:1], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1507. }
  1508. }
  1509. - (void)moveOpenWindow:(NSArray *)indexPaths
  1510. {
  1511. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1512. return;
  1513. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"CCMove" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMove"];
  1514. CCMove *viewController = (CCMove *)navigationController.topViewController;
  1515. viewController.delegate = self;
  1516. viewController.move.title = NSLocalizedString(@"_move_", nil);
  1517. viewController.tintColor = [NCBrandColor sharedInstance].brandText;
  1518. viewController.barTintColor = [NCBrandColor sharedInstance].brand;
  1519. viewController.tintColorTitle = [NCBrandColor sharedInstance].brandText;
  1520. viewController.networkingOperationQueue = appDelegate.netQueue;
  1521. // E2EE
  1522. viewController.includeDirectoryE2EEncryption = NO;
  1523. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  1524. [self presentViewController:navigationController animated:YES completion:nil];
  1525. }
  1526. #pragma --------------------------------------------------------------------------------------------
  1527. #pragma mark ===== Create folder =====
  1528. #pragma --------------------------------------------------------------------------------------------
  1529. - (void)createFolderSuccessFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1530. {
  1531. if (errorCode == 0) {
  1532. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", metadataNet.serverUrl, metadataNet.fileName];
  1533. if (_metadataFolder.e2eEncrypted) {
  1534. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1535. NSError *error = [[NCNetworkingEndToEnd sharedManager] markEndToEndFolderEncrypted:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl fileID:metadataNet.fileID serverUrl:newDirectory];
  1536. dispatch_async(dispatch_get_main_queue(), ^{
  1537. if (error) {
  1538. [appDelegate messageNotification:@"_e2e_error_mark_folder_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  1539. }
  1540. [self readFolder:self.serverUrl];
  1541. });
  1542. });
  1543. } else {
  1544. [self readFolder:self.serverUrl];
  1545. }
  1546. } else {
  1547. // Unauthorized
  1548. if (errorCode == kOCErrorServerUnauthorized)
  1549. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  1550. else
  1551. [appDelegate messageNotification:@"_create_folder_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1552. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID] clearDateReadDirectoryID:nil];
  1553. [self reloadDatasource];
  1554. // We are in directory fail ?
  1555. CCMain *vc = [appDelegate.listMainVC objectForKey:[CCUtility stringAppendServerUrl:_serverUrl addFileName:metadataNet.fileName]];
  1556. if (vc)
  1557. [vc.navigationController popViewControllerAnimated:YES];
  1558. }
  1559. }
  1560. - (void)createFolder:(NSString *)fileNameFolder serverUrl:(NSString *)serverUrl
  1561. {
  1562. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1563. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1564. if (![fileNameFolder length]) return;
  1565. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1566. if (!directoryID) return;
  1567. metadataNet.action = actionCreateFolder;
  1568. metadataNet.directoryID = directoryID;
  1569. metadataNet.fileID = [[NSUUID UUID] UUIDString];
  1570. metadataNet.fileName = fileNameFolder;
  1571. metadataNet.selector = selectorCreateFolder;
  1572. metadataNet.serverUrl = serverUrl;
  1573. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1574. // Create Directory on metadata
  1575. 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];
  1576. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1577. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:_serverUrl directoryID:nil];
  1578. [self reloadDatasource];
  1579. }
  1580. #pragma --------------------------------------------------------------------------------------------
  1581. #pragma mark ===== Progress & Task Button =====
  1582. #pragma --------------------------------------------------------------------------------------------
  1583. - (void)triggerProgressTask:(NSNotification *)notification
  1584. {
  1585. NSDictionary *dict = notification.userInfo;
  1586. NSString *fileID = [dict valueForKey:@"fileID"];
  1587. NSString *serverUrl = [dict valueForKey:@"serverUrl"];
  1588. float progress = [[dict valueForKey:@"progress"] floatValue];
  1589. // Check
  1590. if (!fileID || [fileID isEqualToString: @""])
  1591. return;
  1592. [appDelegate.listProgressMetadata setObject:[NSNumber numberWithFloat:progress] forKey:fileID];
  1593. if (![serverUrl isEqualToString:_serverUrl])
  1594. return;
  1595. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:fileID];
  1596. if ([self indexPathIsValid:indexPath]) {
  1597. CCTransfersCell *cell = (CCTransfersCell *)[self.tableView cellForRowAtIndexPath:indexPath];
  1598. cell.progressView.progressTintColor = [UIColor blackColor];
  1599. cell.progressView.hidden = NO;
  1600. [cell.progressView setProgress:progress];
  1601. }
  1602. }
  1603. - (void)reloadTaskButton:(id)sender withEvent:(UIEvent *)event
  1604. {
  1605. UITouch * touch = [[event allTouches] anyObject];
  1606. CGPoint location = [touch locationInView:self.tableView];
  1607. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1608. if ([self indexPathIsValid:indexPath]) {
  1609. tableMetadata *metadataSection = [self getMetadataFromSectionDataSource:indexPath];
  1610. if (metadataSection) {
  1611. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataSection.fileID]];
  1612. if (metadata)
  1613. [self reloadTaskButton:metadata];
  1614. }
  1615. }
  1616. }
  1617. - (void)reloadTaskButton:(tableMetadata *)metadata
  1618. {
  1619. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1620. __block NSURLSessionTask *findTask;
  1621. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1622. NSString *fileID = metadata.fileID;
  1623. // DOWNLOAD
  1624. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  1625. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1626. for (NSURLSessionUploadTask *task in downloadTasks)
  1627. if (task.taskIdentifier == sessionTaskIdentifier) {
  1628. findTask = task;
  1629. [appDelegate.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  1630. [task cancel];
  1631. }
  1632. if (!findTask) {
  1633. [appDelegate.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  1634. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1635. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1636. }
  1637. }];
  1638. }
  1639. // UPLOAD
  1640. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1641. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1642. for (NSURLSessionUploadTask *task in uploadTasks)
  1643. if (task.taskIdentifier == sessionTaskIdentifier) {
  1644. findTask = task;
  1645. [appDelegate.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  1646. [task cancel];
  1647. }
  1648. if (!findTask) {
  1649. [appDelegate.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  1650. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1651. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1652. }
  1653. }];
  1654. }
  1655. }
  1656. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  1657. {
  1658. UITouch * touch = [[event allTouches] anyObject];
  1659. CGPoint location = [touch locationInView:self.tableView];
  1660. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1661. if ([self indexPathIsValid:indexPath]) {
  1662. tableMetadata *metadataSection = [self getMetadataFromSectionDataSource:indexPath];
  1663. if (metadataSection) {
  1664. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataSection.fileID]];
  1665. if (metadata)
  1666. [self cancelTaskButton:metadata reloadTable:YES];
  1667. }
  1668. }
  1669. }
  1670. - (void)cancelTaskButton:(tableMetadata *)metadata reloadTable:(BOOL)reloadTable
  1671. {
  1672. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1673. __block NSURLSessionTask *findTask;
  1674. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1675. NSString *fileID = metadata.fileID;
  1676. // DOWNLOAD
  1677. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  1678. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1679. for (NSURLSessionTask *task in downloadTasks)
  1680. if (task.taskIdentifier == sessionTaskIdentifier) {
  1681. findTask = task;
  1682. [appDelegate.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  1683. [task cancel];
  1684. }
  1685. if (!findTask) {
  1686. [appDelegate.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  1687. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1688. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1689. }
  1690. }];
  1691. }
  1692. // UPLOAD
  1693. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1694. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1695. for (NSURLSessionUploadTask *task in uploadTasks)
  1696. if (task.taskIdentifier == sessionTaskIdentifier) {
  1697. findTask = task;
  1698. [appDelegate.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  1699. [task cancel];
  1700. }
  1701. if (!findTask) {
  1702. [appDelegate.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  1703. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1704. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1705. }
  1706. }];
  1707. }
  1708. }
  1709. - (void)stopTaskButton:(id)sender withEvent:(UIEvent *)event
  1710. {
  1711. UITouch * touch = [[event allTouches] anyObject];
  1712. CGPoint location = [touch locationInView:self.tableView];
  1713. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1714. if ([self indexPathIsValid:indexPath]) {
  1715. tableMetadata *metadataSection = [self getMetadataFromSectionDataSource:indexPath];
  1716. if (metadataSection) {
  1717. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataSection.fileID]];
  1718. if (metadata)
  1719. [self stopTaskButton:metadata];
  1720. }
  1721. }
  1722. }
  1723. - (void)stopTaskButton:(tableMetadata *)metadata
  1724. {
  1725. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1726. __block NSURLSessionTask *findTask;
  1727. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1728. NSString *fileID = metadata.fileID;
  1729. // UPLOAD
  1730. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1731. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1732. for (NSURLSessionUploadTask *task in uploadTasks)
  1733. if (task.taskIdentifier == sessionTaskIdentifier) {
  1734. [appDelegate.listChangeTask setObject:@"stopUpload" forKey:fileID];
  1735. findTask = task;
  1736. [task cancel];
  1737. }
  1738. if (!findTask) {
  1739. [appDelegate.listChangeTask setObject:@"stopUpload" forKey:fileID];
  1740. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1741. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1742. }
  1743. }];
  1744. }
  1745. }
  1746. #pragma --------------------------------------------------------------------------------------------
  1747. #pragma mark ===== Shared =====
  1748. #pragma --------------------------------------------------------------------------------------------
  1749. - (void)readSharedSuccess:(CCMetadataNet *)metadataNet items:(NSDictionary *)items openWindow:(BOOL)openWindow
  1750. {
  1751. [_hud hideHud];
  1752. // Check Active Account
  1753. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1754. return;
  1755. NSArray *result = [[NCManageDatabase sharedInstance] updateShare:items activeUrl:appDelegate.activeUrl];
  1756. if (result) {
  1757. appDelegate.sharesLink = result[0];
  1758. appDelegate.sharesUserAndGroup = result[1];
  1759. }
  1760. // Notify Shares View
  1761. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"SharesReloadDatasource" object:nil userInfo:nil];
  1762. if (openWindow) {
  1763. if (_shareOC) {
  1764. [_shareOC reloadData];
  1765. } else {
  1766. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  1767. // Apriamo la view
  1768. _shareOC = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareOC"];
  1769. _shareOC.delegate = self;
  1770. _shareOC.metadata = metadata;
  1771. _shareOC.serverUrl = metadataNet.serverUrl;
  1772. _shareOC.shareLink = [appDelegate.sharesLink objectForKey:metadata.fileID];
  1773. _shareOC.shareUserAndGroup = [appDelegate.sharesUserAndGroup objectForKey:metadata.fileID];
  1774. [_shareOC setModalPresentationStyle:UIModalPresentationFormSheet];
  1775. [self presentViewController:_shareOC animated:YES completion:nil];
  1776. }
  1777. }
  1778. [self tableViewReloadData];
  1779. }
  1780. - (void)shareFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1781. {
  1782. [_hud hideHud];
  1783. // Check Active Account
  1784. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1785. return;
  1786. // Unauthorized
  1787. if (errorCode == kOCErrorServerUnauthorized)
  1788. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  1789. else
  1790. [appDelegate messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1791. if (_shareOC)
  1792. [_shareOC reloadData];
  1793. [self tableViewReloadData];
  1794. }
  1795. - (void)share:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password
  1796. {
  1797. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1798. metadataNet.action = actionShare;
  1799. metadataNet.fileID = metadata.fileID;
  1800. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:appDelegate.activeUrl];
  1801. metadataNet.fileNameView = metadata.fileNameView;
  1802. metadataNet.password = password;
  1803. metadataNet.selector = selectorShare;
  1804. metadataNet.serverUrl = serverUrl;
  1805. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1806. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1807. }
  1808. - (void)unShareSuccess:(CCMetadataNet *)metadataNet
  1809. {
  1810. [_hud hideHud];
  1811. // Check Active Account
  1812. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1813. return;
  1814. // rimuoviamo la condivisione da db
  1815. NSArray *result = [[NCManageDatabase sharedInstance] unShare:metadataNet.share fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl sharesLink:appDelegate.sharesLink sharesUserAndGroup:appDelegate.sharesUserAndGroup];
  1816. if (result) {
  1817. appDelegate.sharesLink = result[0];
  1818. appDelegate.sharesUserAndGroup = result[1];
  1819. }
  1820. if (_shareOC)
  1821. [_shareOC reloadData];
  1822. [self tableViewReloadData];
  1823. }
  1824. - (void)unShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl
  1825. {
  1826. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1827. metadataNet.action = actionUnShare;
  1828. metadataNet.fileID = metadata.fileID;
  1829. metadataNet.fileName = metadata.fileName;
  1830. metadataNet.fileNameView = metadata.fileNameView;
  1831. metadataNet.selector = selectorUnshare;
  1832. metadataNet.serverUrl = serverUrl;
  1833. metadataNet.share = share;
  1834. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1835. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1836. }
  1837. - (void)updateShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password expirationTime:(NSString *)expirationTime permission:(NSInteger)permission
  1838. {
  1839. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1840. metadataNet.action = actionUpdateShare;
  1841. metadataNet.fileID = metadata.fileID;
  1842. metadataNet.expirationTime = expirationTime;
  1843. metadataNet.password = password;
  1844. metadataNet.selector = selectorUpdateShare;
  1845. metadataNet.serverUrl = serverUrl;
  1846. metadataNet.share = share;
  1847. metadataNet.sharePermission = permission;
  1848. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1849. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1850. }
  1851. - (void)getUserAndGroupSuccess:(CCMetadataNet *)metadataNet items:(NSArray *)items
  1852. {
  1853. [_hud hideHud];
  1854. // Check Active Account
  1855. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1856. return;
  1857. if (_shareOC)
  1858. [_shareOC reloadUserAndGroup:items];
  1859. }
  1860. - (void)getUserAndGroupFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1861. {
  1862. [_hud hideHud];
  1863. // Check Active Account
  1864. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1865. return;
  1866. // Unauthorized
  1867. if (errorCode == kOCErrorServerUnauthorized)
  1868. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  1869. else
  1870. [appDelegate messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1871. }
  1872. - (void)getUserAndGroup:(NSString *)find
  1873. {
  1874. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1875. metadataNet.action = actionGetUserAndGroup;
  1876. metadataNet.options = find;
  1877. metadataNet.selector = selectorGetUserAndGroup;
  1878. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1879. [_hud visibleIndeterminateHud];
  1880. }
  1881. - (void)shareUserAndGroup:(NSString *)user shareeType:(NSInteger)shareeType permission:(NSInteger)permission metadata:(tableMetadata *)metadata directoryID:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  1882. {
  1883. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1884. metadataNet.action = actionShareWith;
  1885. metadataNet.fileID = metadata.fileID;
  1886. metadataNet.directoryID = directoryID;
  1887. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:appDelegate.activeUrl];
  1888. metadataNet.fileNameView = metadata.fileNameView;
  1889. metadataNet.serverUrl = serverUrl;
  1890. metadataNet.selector = selectorShare;
  1891. metadataNet.share = user;
  1892. metadataNet.shareeType = shareeType;
  1893. metadataNet.sharePermission = permission;
  1894. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1895. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1896. }
  1897. - (void)openWindowShare:(tableMetadata *)metadata
  1898. {
  1899. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1900. if (!serverUrl) return;
  1901. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1902. metadataNet.action = actionReadShareServer;
  1903. metadataNet.fileID = metadata.fileID;
  1904. metadataNet.fileName = metadata.fileName;
  1905. metadataNet.fileNameView = metadata.fileNameView;
  1906. metadataNet.selector = selectorOpenWindowShare;
  1907. metadataNet.serverUrl = serverUrl;
  1908. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1909. [_hud visibleIndeterminateHud];
  1910. }
  1911. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  1912. {
  1913. CGPoint location = [tapGesture locationInView:self.tableView];
  1914. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1915. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1916. if (metadata)
  1917. [self openWindowShare:metadata];
  1918. }
  1919. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  1920. {
  1921. CGPoint location = [tapGesture locationInView:self.tableView];
  1922. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1923. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1924. if (metadata) {
  1925. CCShareInfoCMOC *vc = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareInfoCMOC"];
  1926. vc.metadata = metadata;
  1927. [vc setModalPresentationStyle:UIModalPresentationFormSheet];
  1928. [self presentViewController:vc animated:YES completion:nil];
  1929. }
  1930. }
  1931. #pragma --------------------------------------------------------------------------------------------
  1932. #pragma mark ===== Favorite =====
  1933. #pragma --------------------------------------------------------------------------------------------
  1934. - (void)settingFavoriteSuccessFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1935. {
  1936. // Check Active Account
  1937. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1938. return;
  1939. if (errorCode == 0) {
  1940. _dateReadDataSource = nil;
  1941. [[NCManageDatabase sharedInstance] setMetadataFavoriteWithFileID:metadataNet.fileID favorite:[metadataNet.options boolValue]];
  1942. if (_isSearchMode)
  1943. [self readFolder:metadataNet.serverUrl];
  1944. else
  1945. [self reloadDatasource:metadataNet.serverUrl];
  1946. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  1947. if (metadata.directory && metadata.favorite) {
  1948. NSString *dir = [CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:metadata.fileName];
  1949. [appDelegate.activeFavorites addFavoriteFolder:dir];
  1950. }
  1951. } else {
  1952. if (errorCode == kOCErrorServerUnauthorized)
  1953. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  1954. NSLog(@"[LOG] Setting Favorite failure error %d, %@", (int)errorCode, message);
  1955. }
  1956. }
  1957. - (void)addFavorite:(tableMetadata *)metadata
  1958. {
  1959. if (metadata.directory) {
  1960. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  1961. } else {
  1962. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1963. if (serverUrl)
  1964. [[CCNetworking sharedNetworking] downloadFile:metadata.fileName fileID:metadata.fileID serverUrl:serverUrl selector:selectorAddFavorite selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  1965. }
  1966. }
  1967. - (void)removeFavorite:(tableMetadata *)metadata
  1968. {
  1969. [[CCActions sharedInstance] settingFavorite:metadata favorite:NO delegate:self];
  1970. }
  1971. #pragma --------------------------------------------------------------------------------------------
  1972. #pragma mark ===== Open in... =====
  1973. #pragma --------------------------------------------------------------------------------------------
  1974. - (void)openIn:(tableMetadata *)metadata
  1975. {
  1976. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1977. if (!serverUrl) return;
  1978. [[CCNetworking sharedNetworking] downloadFile:metadata.fileName fileID:metadata.fileID serverUrl:serverUrl selector:selectorOpenIn selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  1979. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  1980. if ([self indexPathIsValid:indexPath])
  1981. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  1982. }
  1983. #pragma --------------------------------------------------------------------------------------------
  1984. #pragma mark ===== Remove Local File =====
  1985. #pragma --------------------------------------------------------------------------------------------
  1986. - (void)removeLocalFile:(tableMetadata *)metadata
  1987. {
  1988. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  1989. if (!serverUrl) return;
  1990. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  1991. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadata.fileID] error:nil];
  1992. [self reloadDatasource:serverUrl];
  1993. }
  1994. #pragma --------------------------------------------------------------------------------------------
  1995. #pragma mark ===== Order Table & GroupBy & DirectoryOnTop =====
  1996. #pragma --------------------------------------------------------------------------------------------
  1997. - (void)orderTable:(NSString *)order
  1998. {
  1999. [CCUtility setOrderSettings:order];
  2000. // Clear data-read of DataSource
  2001. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2002. }
  2003. - (void)ascendingTable:(BOOL)ascending
  2004. {
  2005. [CCUtility setAscendingSettings:ascending];
  2006. // Clear data-read of DataSource
  2007. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2008. }
  2009. - (void)directoryOnTop:(BOOL)directoryOnTop
  2010. {
  2011. [CCUtility setDirectoryOnTop:directoryOnTop];
  2012. // Clear data-read of DataSource
  2013. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2014. }
  2015. - (void)tableGroupBy:(NSString *)groupBy
  2016. {
  2017. [CCUtility setGroupBySettings:groupBy];
  2018. // Clear data-read of DataSource
  2019. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2020. }
  2021. #pragma --------------------------------------------------------------------------------------------
  2022. #pragma mark ==== Menu LOGO ====
  2023. #pragma --------------------------------------------------------------------------------------------
  2024. - (void)menuLogo:(UIGestureRecognizer *)theGestureRecognizer
  2025. {
  2026. if (appDelegate.reSelectMenu.isOpen || appDelegate.reMainMenu.isOpen)
  2027. return;
  2028. // Brand
  2029. if ([NCBrandOptions sharedInstance].disable_multiaccount)
  2030. return;
  2031. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  2032. NSMutableArray *menuArray = [NSMutableArray new];
  2033. for (NSString *account in listAccount) {
  2034. CCMenuItem *item = [[CCMenuItem alloc] init];
  2035. item.title = [account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  2036. item.argument = account;
  2037. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ ", account]];
  2038. NSString *directoryUser = [CCUtility getDirectoryActiveUser:tableAccount.user activeUrl:tableAccount.url];
  2039. UIImage *avatar = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/avatar.png", directoryUser]];
  2040. if (avatar) {
  2041. avatar = [CCGraphics scaleImage:avatar toSize:CGSizeMake(25, 25) isAspectRation:YES];
  2042. CCAvatar *avatarImageView = [[CCAvatar alloc] initWithImage:avatar borderColor:[UIColor lightGrayColor] borderWidth:0.5];
  2043. CGSize imageSize = avatarImageView.bounds.size;
  2044. UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
  2045. CGContextRef context = UIGraphicsGetCurrentContext();
  2046. [avatarImageView.layer renderInContext:context];
  2047. avatar = UIGraphicsGetImageFromCurrentImageContext();
  2048. UIGraphicsEndImageContext();
  2049. } else {
  2050. avatar = [UIImage imageNamed:@"menuLogoUser"];
  2051. }
  2052. item.image = avatar;
  2053. item.target = self;
  2054. if ([account isEqualToString:appDelegate.activeAccount]) {
  2055. item.action = nil;
  2056. [menuArray insertObject:item atIndex:0];
  2057. } else {
  2058. item.action = @selector(changeDefaultAccount:);
  2059. [menuArray addObject:item];
  2060. }
  2061. }
  2062. // Add + new account
  2063. CCMenuItem *item = [[CCMenuItem alloc] init];
  2064. item.title = NSLocalizedString(@"_add_account_", nil);
  2065. item.argument = @"";
  2066. item.image = [UIImage imageNamed:@"add"];
  2067. item.target = self;
  2068. item.action = @selector(addNewAccount:);
  2069. [menuArray addObject:item];
  2070. OptionalConfiguration options;
  2071. Color textColor, backgroundColor;
  2072. textColor.R = 0;
  2073. textColor.G = 0;
  2074. textColor.B = 0;
  2075. backgroundColor.R = 1;
  2076. backgroundColor.G = 1;
  2077. backgroundColor.B = 1;
  2078. options.arrowSize = 9;
  2079. options.marginXSpacing = 7;
  2080. options.marginYSpacing = 10;
  2081. options.intervalSpacing = 20;
  2082. options.menuCornerRadius = 6.5;
  2083. options.maskToBackground = NO;
  2084. options.shadowOfMenu = YES;
  2085. options.hasSeperatorLine = YES;
  2086. options.seperatorLineHasInsets = YES;
  2087. options.textColor = textColor;
  2088. options.menuBackgroundColor = backgroundColor;
  2089. CGRect rect = self.view.frame;
  2090. CGFloat locationY = [theGestureRecognizer locationInView: self.navigationController.navigationBar].y;
  2091. CGFloat safeAreaTop = 0;
  2092. CGFloat offsetY = 35;
  2093. if (@available(iOS 11, *)) {
  2094. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top / 2;
  2095. }
  2096. rect.origin.y = locationY + safeAreaTop + offsetY;
  2097. rect.size.height = rect.size.height - locationY - safeAreaTop - offsetY;
  2098. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  2099. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  2100. }
  2101. - (void)changeDefaultAccount:(CCMenuItem *)sender
  2102. {
  2103. // Verify session in progress
  2104. if ([[[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND sessionTaskIdentifier > 0", appDelegate.activeAccount] sorted:nil ascending:NO] count] > 0) {
  2105. [JDStatusBarNotification showWithStatus:NSLocalizedString(@"_transfers_in_queue_", nil) dismissAfter:k_dismissAfterSecond styleName:JDStatusBarStyleDefault];
  2106. return;
  2107. }
  2108. [appDelegate.netQueue cancelAllOperations];
  2109. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2110. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:[sender argument]];
  2111. if (tableAccount) {
  2112. [appDelegate settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activeUserID:tableAccount.userID activePassword:tableAccount.password];
  2113. // go to home sweet home
  2114. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initializeMain" object:nil];
  2115. }
  2116. });
  2117. }
  2118. - (void)addNewAccount:(CCMenuItem *)sender
  2119. {
  2120. // Verify session in progress
  2121. if ([[[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND sessionTaskIdentifier > 0", appDelegate.activeAccount] sorted:nil ascending:NO] count] > 0) {
  2122. [JDStatusBarNotification showWithStatus:NSLocalizedString(@"_transfers_in_queue_", nil) dismissAfter:k_dismissAfterSecond styleName:JDStatusBarStyleDefault];
  2123. return;
  2124. }
  2125. [appDelegate.netQueue cancelAllOperations];
  2126. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2127. [appDelegate openLoginView:self loginType:loginAdd];
  2128. });
  2129. }
  2130. #pragma --------------------------------------------------------------------------------------------
  2131. #pragma mark ==== ReMenu ====
  2132. #pragma --------------------------------------------------------------------------------------------
  2133. - (void)createReMenuBackgroundView:(REMenu *)menu
  2134. {
  2135. CGFloat safeAreaBottom = 0;
  2136. CGFloat safeAreaTop = 0;
  2137. CGFloat statusBar = 0;
  2138. if (@available(iOS 11, *)) {
  2139. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top;
  2140. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  2141. }
  2142. if ([UIApplication sharedApplication].isStatusBarHidden) {
  2143. statusBar = 13;
  2144. }
  2145. CGFloat computeNavigationBarOffset = [menu computeNavigationBarOffset];
  2146. UIViewController *rootController = [[[[UIApplication sharedApplication]delegate] window] rootViewController];
  2147. CGRect globalPositionMenu = [menu.menuView convertRect:menu.menuView.bounds toView:rootController.view];
  2148. _reMenuBackgroundView.frame = CGRectMake(0, computeNavigationBarOffset, globalPositionMenu.size.width, rootController.view.frame.size.height);
  2149. [UIView animateWithDuration:0.2 animations:^{
  2150. CGFloat minimum = safeAreaBottom + self.tabBarController.tabBar.frame.size.height;
  2151. CGFloat y = rootController.view.frame.size.height - menu.menuView.frame.size.height - globalPositionMenu.origin.y + statusBar;
  2152. if (y>minimum) {
  2153. _reMenuBackgroundView.frame = CGRectMake(0, rootController.view.frame.size.height, globalPositionMenu.size.width, - y);
  2154. [self.tabBarController.view addSubview:_reMenuBackgroundView];
  2155. }
  2156. }];
  2157. }
  2158. - (void)createReMainMenu
  2159. {
  2160. NSString *ordinamento;
  2161. NSString *groupBy = _directoryGroupBy;
  2162. __block NSString *nuovoOrdinamento;
  2163. NSString *titoloNuovo, *titoloAttuale;
  2164. BOOL ascendente;
  2165. __block BOOL nuovoAscendente;
  2166. UIImage *image;
  2167. // ITEM SELECT ----------------------------------------------------------------------------------------------------
  2168. appDelegate.selezionaItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_", nil)subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"select"] color:[NCBrandColor sharedInstance].brandElement] highlightedImage:nil action:^(REMenuItem *item) {
  2169. if ([_sectionDataSource.allRecordsDataSource count] > 0) {
  2170. [self tableViewSelect:YES];
  2171. }
  2172. }];
  2173. // ITEM ORDER ----------------------------------------------------------------------------------------------------
  2174. ordinamento = _directoryOrder;
  2175. if ([ordinamento isEqualToString:@"fileName"]) {
  2176. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdeyByDate"] color:[NCBrandColor sharedInstance].brandElement];
  2177. titoloNuovo = NSLocalizedString(@"_order_by_date_", nil);
  2178. titoloAttuale = NSLocalizedString(@"_current_order_name_", nil);
  2179. nuovoOrdinamento = @"date";
  2180. }
  2181. if ([ordinamento isEqualToString:@"date"]) {
  2182. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrderByFileName"] color:[NCBrandColor sharedInstance].brandElement];
  2183. titoloNuovo = NSLocalizedString(@"_order_by_name_", nil);
  2184. titoloAttuale = NSLocalizedString(@"_current_order_date_", nil);
  2185. nuovoOrdinamento = @"fileName";
  2186. }
  2187. appDelegate.ordinaItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2188. [self orderTable:nuovoOrdinamento];
  2189. }];
  2190. // ITEM ASCENDING -----------------------------------------------------------------------------------------------------
  2191. ascendente = [CCUtility getAscendingSettings];
  2192. if (ascendente) {
  2193. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoDiscendente"] color:[NCBrandColor sharedInstance].brandElement];
  2194. titoloNuovo = NSLocalizedString(@"_sort_descending_", nil);
  2195. titoloAttuale = NSLocalizedString(@"_current_sort_ascending_", nil);
  2196. nuovoAscendente = false;
  2197. }
  2198. if (!ascendente) {
  2199. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoAscendente"] color:[NCBrandColor sharedInstance].brandElement];
  2200. titoloNuovo = NSLocalizedString(@"_sort_ascending_", nil);
  2201. titoloAttuale = NSLocalizedString(@"_current_sort_descending_", nil);
  2202. nuovoAscendente = true;
  2203. }
  2204. appDelegate.ascendenteItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2205. [self ascendingTable:nuovoAscendente];
  2206. }];
  2207. // ITEM ALPHABETIC -----------------------------------------------------------------------------------------------------
  2208. if ([groupBy isEqualToString:@"alphabetic"]) { titoloNuovo = NSLocalizedString(@"_group_alphabetic_yes_", nil); }
  2209. else { titoloNuovo = NSLocalizedString(@"_group_alphabetic_no_", nil); }
  2210. appDelegate.alphabeticItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByAlphabetic"] color:[NCBrandColor sharedInstance].brandElement] highlightedImage:nil action:^(REMenuItem *item) {
  2211. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  2212. else [self tableGroupBy:@"alphabetic"];
  2213. }];
  2214. // ITEM TYPEFILE -------------------------------------------------------------------------------------------------------
  2215. if ([groupBy isEqualToString:@"typefile"]) { titoloNuovo = NSLocalizedString(@"_group_typefile_yes_", nil); }
  2216. else { titoloNuovo = NSLocalizedString(@"_group_typefile_no_", nil); }
  2217. appDelegate.typefileItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"file"] color:[NCBrandColor sharedInstance].brandElement] highlightedImage:nil action:^(REMenuItem *item) {
  2218. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  2219. else [self tableGroupBy:@"typefile"];
  2220. }];
  2221. // ITEM DATE -------------------------------------------------------------------------------------------------------
  2222. if ([groupBy isEqualToString:@"date"]) { titoloNuovo = NSLocalizedString(@"_group_date_yes_", nil); }
  2223. else { titoloNuovo = NSLocalizedString(@"_group_date_no_", nil); }
  2224. appDelegate.dateItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByDate"] color:[NCBrandColor sharedInstance].brandElement] highlightedImage:nil action:^(REMenuItem *item) {
  2225. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  2226. else [self tableGroupBy:@"date"];
  2227. }];
  2228. // ITEM DIRECTORY ON TOP ------------------------------------------------------------------------------------------------
  2229. if ([CCUtility getDirectoryOnTop]) { titoloNuovo = NSLocalizedString(@"_directory_on_top_yes_", nil); }
  2230. else { titoloNuovo = NSLocalizedString(@"_directory_on_top_no_", nil); }
  2231. appDelegate.directoryOnTopItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder"] color:[NCBrandColor sharedInstance].brandElement] highlightedImage:nil action:^(REMenuItem *item) {
  2232. if ([CCUtility getDirectoryOnTop])
  2233. [self directoryOnTop:NO];
  2234. else
  2235. [self directoryOnTop:YES];
  2236. }];
  2237. // REMENU --------------------------------------------------------------------------------------------------------------
  2238. appDelegate.reMainMenu = [[REMenu alloc] initWithItems:@[appDelegate.selezionaItem, appDelegate.ordinaItem, appDelegate.ascendenteItem, appDelegate.alphabeticItem, appDelegate.typefileItem, appDelegate.dateItem, appDelegate.directoryOnTopItem]];
  2239. appDelegate.reMainMenu.imageOffset = CGSizeMake(5, -1);
  2240. appDelegate.reMainMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2241. appDelegate.reMainMenu.imageOffset = CGSizeMake(0, 0);
  2242. appDelegate.reMainMenu.waitUntilAnimationIsComplete = NO;
  2243. appDelegate.reMainMenu.separatorHeight = 0.5;
  2244. appDelegate.reMainMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2245. appDelegate.reMainMenu.backgroundColor = [NCBrandColor sharedInstance].backgroundView;
  2246. appDelegate.reMainMenu.textColor = [UIColor blackColor];
  2247. appDelegate.reMainMenu.textAlignment = NSTextAlignmentLeft;
  2248. appDelegate.reMainMenu.textShadowColor = nil;
  2249. appDelegate.reMainMenu.textOffset = CGSizeMake(50, 0.0);
  2250. appDelegate.reMainMenu.font = [UIFont systemFontOfSize:14.0];
  2251. appDelegate.reMainMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2252. appDelegate.reMainMenu.highlightedSeparatorColor = nil;
  2253. appDelegate.reMainMenu.highlightedTextColor = [UIColor blackColor];
  2254. appDelegate.reMainMenu.highlightedTextShadowColor = nil;
  2255. appDelegate.reMainMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2256. appDelegate.reMainMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  2257. appDelegate.reMainMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2258. appDelegate.reMainMenu.subtitleTextShadowColor = nil;
  2259. appDelegate.reMainMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2260. appDelegate.reMainMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2261. appDelegate.reMainMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2262. appDelegate.reMainMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2263. appDelegate.reMainMenu.subtitleHighlightedTextShadowColor = nil;
  2264. appDelegate.reMainMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2265. appDelegate.reMainMenu.borderWidth = 0.3;
  2266. appDelegate.reMainMenu.borderColor = [UIColor lightGrayColor];
  2267. appDelegate.reMainMenu.animationDuration = 0.2;
  2268. appDelegate.reMainMenu.closeAnimationDuration = 0.2;
  2269. appDelegate.reMainMenu.bounce = NO;
  2270. __weak typeof(self) weakSelf = self;
  2271. [appDelegate.reMainMenu setClosePreparationBlock:^{
  2272. // Backgroun reMenu (Gesture)
  2273. [weakSelf.reMenuBackgroundView removeFromSuperview];
  2274. [weakSelf.reMenuBackgroundView removeGestureRecognizer:weakSelf.singleFingerTap];
  2275. }];
  2276. }
  2277. - (void)toggleReMainMenu
  2278. {
  2279. if (appDelegate.reMainMenu.isOpen) {
  2280. [appDelegate.reMainMenu close];
  2281. } else {
  2282. [self createReMainMenu];
  2283. [appDelegate.reMainMenu showFromNavigationController:self.navigationController];
  2284. // Backgroun reMenu & (Gesture)
  2285. [self createReMenuBackgroundView:appDelegate.reMainMenu];
  2286. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReMainMenu)];
  2287. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2288. }
  2289. }
  2290. - (void)createReSelectMenu
  2291. {
  2292. // ITEM DELETE ------------------------------------------------------------------------------------------------------
  2293. appDelegate.deleteItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_delete_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"delete"] color:[NCBrandColor sharedInstance].brandElement] highlightedImage:nil action:^(REMenuItem *item) {
  2294. [self deleteFile];
  2295. }];
  2296. // ITEM MOVE ------------------------------------------------------------------------------------------------------
  2297. appDelegate.moveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_move_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"move"] color:[NCBrandColor sharedInstance].brandElement] highlightedImage:nil action:^(REMenuItem *item) {
  2298. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2299. }];
  2300. // ITEM DOWNLOAD ----------------------------------------------------------------------------------------------------
  2301. 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) {
  2302. [self downloadSelectedFilesFolders];
  2303. }];
  2304. // ITEM SAVE IMAGE & VIDEO -------------------------------------------------------------------------------------------
  2305. 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) {
  2306. [self saveSelectedFiles];
  2307. }];
  2308. // E2EE
  2309. if (_metadataFolder.e2eEncrypted) {
  2310. appDelegate.reSelectMenu = [[REMenu alloc] initWithItems:@[appDelegate.deleteItem,appDelegate.downloadItem, appDelegate.saveItem]];
  2311. } else {
  2312. appDelegate.reSelectMenu = [[REMenu alloc] initWithItems:@[appDelegate.deleteItem,appDelegate.moveItem, appDelegate.downloadItem, appDelegate.saveItem]];
  2313. }
  2314. appDelegate.reSelectMenu.imageOffset = CGSizeMake(5, -1);
  2315. appDelegate.reSelectMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2316. appDelegate.reSelectMenu.imageOffset = CGSizeMake(0, 0);
  2317. appDelegate.reSelectMenu.waitUntilAnimationIsComplete = NO;
  2318. appDelegate.reSelectMenu.separatorHeight = 0.5;
  2319. appDelegate.reSelectMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2320. appDelegate.reSelectMenu.backgroundColor = [NCBrandColor sharedInstance].backgroundView;
  2321. appDelegate.reSelectMenu.textColor = [UIColor blackColor];
  2322. appDelegate.reSelectMenu.textAlignment = NSTextAlignmentLeft;
  2323. appDelegate.reSelectMenu.textShadowColor = nil;
  2324. appDelegate.reSelectMenu.textOffset = CGSizeMake(50, 0.0);
  2325. appDelegate.reSelectMenu.font = [UIFont systemFontOfSize:14.0];
  2326. appDelegate.reSelectMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2327. appDelegate.reSelectMenu.highlightedSeparatorColor = nil;
  2328. appDelegate.reSelectMenu.highlightedTextColor = [UIColor blackColor];
  2329. appDelegate.reSelectMenu.highlightedTextShadowColor = nil;
  2330. appDelegate.reSelectMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2331. appDelegate.reSelectMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1.000];
  2332. appDelegate.reSelectMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2333. appDelegate.reSelectMenu.subtitleTextShadowColor = nil;
  2334. appDelegate.reSelectMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2335. appDelegate.reSelectMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2336. appDelegate.reSelectMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2337. appDelegate.reSelectMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2338. appDelegate.reSelectMenu.subtitleHighlightedTextShadowColor = nil;
  2339. appDelegate.reSelectMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2340. appDelegate.reSelectMenu.borderWidth = 0.3;
  2341. appDelegate.reSelectMenu.borderColor = [UIColor lightGrayColor];
  2342. appDelegate.reSelectMenu.closeAnimationDuration = 0.2;
  2343. appDelegate.reSelectMenu.animationDuration = 0.2;
  2344. appDelegate.reSelectMenu.bounce = NO;
  2345. __weak typeof(self) weakSelf = self;
  2346. [appDelegate.reSelectMenu setClosePreparationBlock:^{
  2347. // Backgroun reMenu (Gesture)
  2348. [weakSelf.reMenuBackgroundView removeFromSuperview];
  2349. [weakSelf.reMenuBackgroundView removeGestureRecognizer:weakSelf.singleFingerTap];
  2350. }];
  2351. }
  2352. - (void)toggleReSelectMenu
  2353. {
  2354. if (appDelegate.reSelectMenu.isOpen) {
  2355. [appDelegate.reSelectMenu close];
  2356. } else {
  2357. [self createReSelectMenu];
  2358. [appDelegate.reSelectMenu showFromNavigationController:self.navigationController];
  2359. // Backgroun reMenu & (Gesture)
  2360. [self createReMenuBackgroundView:appDelegate.reSelectMenu];
  2361. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReSelectMenu)];
  2362. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2363. }
  2364. }
  2365. #pragma --------------------------------------------------------------------------------------------
  2366. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  2367. #pragma --------------------------------------------------------------------------------------------
  2368. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  2369. {
  2370. if (recognizer.state == UIGestureRecognizerStateBegan) {
  2371. CGPoint touchPoint = [recognizer locationInView:self.tableView];
  2372. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touchPoint];
  2373. if ([self indexPathIsValid:indexPath])
  2374. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2375. else
  2376. _metadata = nil;
  2377. [self becomeFirstResponder];
  2378. UIMenuController *menuController = [UIMenuController sharedMenuController];
  2379. UIMenuItem *copyFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)];
  2380. UIMenuItem *copyFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)];
  2381. UIMenuItem *openinFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)];
  2382. UIMenuItem *pasteFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)];
  2383. UIMenuItem *pasteFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)];
  2384. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, nil]];
  2385. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:self.tableView];
  2386. [menuController setMenuVisible:YES animated:YES];
  2387. }
  2388. }
  2389. - (BOOL)canBecomeFirstResponder
  2390. {
  2391. return YES;
  2392. }
  2393. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  2394. {
  2395. // For copy file, copy files, Open in ... :
  2396. //
  2397. // NO Directory
  2398. // NO Error Passcode
  2399. // NO In Session mode (download/upload)
  2400. // NO Template
  2401. if (@selector(copyFile:) == action || @selector(openinFile:) == action) {
  2402. if (_isSelectedMode == NO && _metadata && !_metadata.directory && [_metadata.session length] == 0) return YES;
  2403. else return NO;
  2404. }
  2405. if (@selector(copyFiles:) == action) {
  2406. if (_isSelectedMode) {
  2407. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2408. for (tableMetadata *metadata in selectedMetadatas) {
  2409. if (!metadata.directory && metadata.session.length == 0)
  2410. return YES;
  2411. }
  2412. }
  2413. return NO;
  2414. }
  2415. if (@selector(pasteFile:) == action) {
  2416. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2417. NSArray *items = [pasteboard items];
  2418. if ([items count] == 1) {
  2419. // Value : (NSData) fileID
  2420. NSDictionary *dic = [items objectAtIndex:0];
  2421. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2422. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2423. if (fileID) {
  2424. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2425. if (metadata) {
  2426. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", metadata.account]];
  2427. if (account) {
  2428. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2429. if (directoryUser)
  2430. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]])
  2431. return YES;
  2432. }
  2433. }
  2434. }
  2435. }
  2436. return NO;
  2437. }
  2438. if (@selector(pasteFiles:) == action) {
  2439. BOOL isValid = NO;
  2440. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2441. NSArray *items = [pasteboard items];
  2442. if ([items count] <= 1) return NO;
  2443. for (NSDictionary *dic in items) {
  2444. // Value : (NSData) fileID
  2445. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2446. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2447. if (fileID) {
  2448. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2449. if (metadata) {
  2450. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", metadata.account]];
  2451. if (account) {
  2452. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2453. if (directoryUser) {
  2454. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]]) {
  2455. isValid = YES;
  2456. } else {
  2457. isValid = NO;
  2458. break;
  2459. }
  2460. } else {
  2461. isValid = NO;
  2462. break;
  2463. }
  2464. } else {
  2465. isValid = NO;
  2466. break;
  2467. }
  2468. } else {
  2469. isValid = NO;
  2470. break;
  2471. }
  2472. } else {
  2473. isValid = NO;
  2474. break;
  2475. }
  2476. }
  2477. return isValid;
  2478. }
  2479. return NO;
  2480. }
  2481. /************************************ COPY ************************************/
  2482. - (void)copyFile:(id)sender
  2483. {
  2484. // Remove all item
  2485. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2486. pasteboard.items = [[NSArray alloc] init];
  2487. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser,_metadata.fileID]]) {
  2488. [self copyFileToPasteboard:_metadata];
  2489. } else {
  2490. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2491. if (serverUrl)
  2492. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileName fileID:_metadata.fileID serverUrl:serverUrl selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2493. }
  2494. }
  2495. - (void)copyFiles:(id)sender
  2496. {
  2497. // Remove all item
  2498. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2499. pasteboard.items = [[NSArray alloc] init];
  2500. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2501. for (tableMetadata *metadata in selectedMetadatas) {
  2502. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadata.fileID]]) {
  2503. [self copyFileToPasteboard:metadata];
  2504. } else {
  2505. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2506. if (serverUrl)
  2507. [[CCNetworking sharedNetworking] downloadFile:metadata.fileName fileID:metadata.fileID serverUrl:serverUrl selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2508. }
  2509. }
  2510. [self tableViewSelect:NO];
  2511. }
  2512. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  2513. {
  2514. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2515. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  2516. // Value : (NSData) fileID
  2517. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata.fileID], k_metadataKeyedUnarchiver,nil];
  2518. [items addObject:item];
  2519. [pasteboard setItems:items];
  2520. }
  2521. /************************************ OPEN IN ... ******************************/
  2522. - (void)openinFile:(id)sender
  2523. {
  2524. [self openIn:_metadata];
  2525. }
  2526. /************************************ PASTE ************************************/
  2527. - (void)pasteFile:(id)sender
  2528. {
  2529. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2530. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2531. }
  2532. - (void)pasteFiles:(id)sender
  2533. {
  2534. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2535. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2536. }
  2537. - (void)uploadFilePasteArray:(NSArray *)items cryptated:(BOOL)cryptated
  2538. {
  2539. float timer = 0;
  2540. for (NSDictionary *dic in items) {
  2541. // Value : (NSData) fileID
  2542. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2543. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2544. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2545. if (metadata) {
  2546. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", metadata.account]];
  2547. if (account) {
  2548. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2549. if (directoryUser) {
  2550. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]]) {
  2551. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadata.fileNameView]];
  2552. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timer * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2553. [[CCNetworking sharedNetworking] uploadFile:metadata.fileNameView serverUrl:_serverUrl fileID:nil assetLocalIdentifier:nil session:k_upload_session taskStatus:k_taskStatusResume selector:@"" selectorPost:@"" errorCode:0 delegate:nil];
  2554. });
  2555. timer += 0.1;
  2556. }
  2557. }
  2558. }
  2559. }
  2560. }
  2561. }
  2562. #pragma --------------------------------------------------------------------------------------------
  2563. #pragma mark ===== Lock Passcode =====
  2564. #pragma --------------------------------------------------------------------------------------------
  2565. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  2566. {
  2567. return _failedAttempts;
  2568. }
  2569. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  2570. {
  2571. return _lockUntilDate;
  2572. }
  2573. - (void)passcodeViewCloseButtonPressed:(id)sender
  2574. {
  2575. [self dismissViewControllerAnimated:YES completion:nil];
  2576. }
  2577. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  2578. {
  2579. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  2580. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  2581. _lockUntilDate = nil;
  2582. _failedAttempts = 0;
  2583. aResultHandler(YES);
  2584. } else aResultHandler(NO);
  2585. } else aResultHandler(YES);
  2586. }
  2587. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  2588. {
  2589. [aViewController dismissViewControllerAnimated:YES completion:nil];
  2590. switch (aViewController.type) {
  2591. case BKPasscodeViewControllerCheckPasscodeType: {
  2592. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  2593. // possiamo procedere alla prossima directory
  2594. [self performSegueDirectoryWithControlPasscode:false];
  2595. // avviamo la sessione Passcode Lock con now
  2596. appDelegate.sessionePasscodeLock = [NSDate date];
  2597. }
  2598. // disattivazione lock cartella
  2599. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  2600. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2601. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2602. if (![[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:NO]) {
  2603. [appDelegate messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  2604. }
  2605. [self tableViewReloadData];
  2606. }
  2607. }
  2608. break;
  2609. default:
  2610. break;
  2611. }
  2612. }
  2613. - (void)comandoLockPassword
  2614. {
  2615. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2616. if (!serverUrl) return;
  2617. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2618. // se non è abilitato il Lock Passcode esci
  2619. if ([[CCUtility getBlockCode] length] == 0) {
  2620. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) preferredStyle:UIAlertControllerStyleAlert];
  2621. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  2622. [alertController addAction:okAction];
  2623. [self presentViewController:alertController animated:YES completion:nil];
  2624. return;
  2625. }
  2626. // se è richiesta la disattivazione si chiede la password
  2627. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, lockServerUrl]];
  2628. if (directory.lock) {
  2629. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2630. viewController.delegate = self;
  2631. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  2632. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2633. viewController.inputViewTitlePassword = YES;
  2634. if ([CCUtility getSimplyBlockCode]) {
  2635. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2636. viewController.passcodeInputView.maximumLength = 6;
  2637. } else {
  2638. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2639. viewController.passcodeInputView.maximumLength = 64;
  2640. }
  2641. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  2642. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2643. viewController.touchIDManager = touchIDManager;
  2644. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  2645. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2646. viewController.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
  2647. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2648. [self presentViewController:navigationController animated:YES completion:nil];
  2649. return;
  2650. }
  2651. // ---------------- ACTIVATE PASSWORD
  2652. if ([[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:YES]) {
  2653. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  2654. if ([self indexPathIsValid:indexPath])
  2655. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2656. } else {
  2657. [appDelegate messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  2658. }
  2659. }
  2660. #pragma mark -
  2661. #pragma --------------------------------------------------------------------------------------------
  2662. #pragma mark ===== menu action : Favorite, More, Delete [swipe] =====
  2663. #pragma --------------------------------------------------------------------------------------------
  2664. - (BOOL)canOpenMenuAction:(tableMetadata *)metadata
  2665. {
  2666. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  2667. return NO;
  2668. if (metadata == nil || metadata.sessionTaskIdentifier != k_taskIdentifierDone)
  2669. return NO;
  2670. // E2EE
  2671. if (_metadataFolder.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount] == NO)
  2672. return NO;
  2673. return YES;
  2674. }
  2675. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell canSwipe:(MGSwipeDirection)direction
  2676. {
  2677. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2678. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2679. return [self canOpenMenuAction:metadata];
  2680. }
  2681. -(void)swipeTableCell:(nonnull MGSwipeTableCell *)cell didChangeSwipeState:(MGSwipeState)state gestureIsActive:(BOOL)gestureIsActive
  2682. {
  2683. }
  2684. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell tappedButtonAtIndex:(NSInteger)index direction:(MGSwipeDirection)direction fromExpansion:(BOOL)fromExpansion
  2685. {
  2686. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2687. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2688. if (direction == MGSwipeDirectionRightToLeft) {
  2689. [self actionDelete:indexPath];
  2690. }
  2691. if (direction == MGSwipeDirectionLeftToRight) {
  2692. if (_metadata.favorite)
  2693. [self removeFavorite:_metadata];
  2694. else
  2695. [self addFavorite:_metadata];
  2696. }
  2697. return YES;
  2698. }
  2699. - (void)actionDelete:(NSIndexPath *)indexPath
  2700. {
  2701. // Directory locked ?
  2702. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:[[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID] addFileName:_metadata.fileName];
  2703. if (!lockServerUrl) return;
  2704. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, lockServerUrl]];
  2705. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", _metadata.fileID]];
  2706. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil) {
  2707. [appDelegate messageNotification:@"_error_" description:@"_folder_blocked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  2708. return;
  2709. }
  2710. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  2711. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  2712. [self performSelector:@selector(deleteFile) withObject:nil];
  2713. }]];
  2714. if (localFile || [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, _metadata.fileID]]) {
  2715. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_remove_local_file_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  2716. [self performSelector:@selector(removeLocalFile:) withObject:_metadata];
  2717. }]];
  2718. }
  2719. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2720. [alertController dismissViewControllerAnimated:YES completion:nil];
  2721. }]];
  2722. alertController.popoverPresentationController.sourceView = self.view;
  2723. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  2724. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  2725. [alertController.view layoutIfNeeded];
  2726. [self presentViewController:alertController animated:YES completion:nil];
  2727. }
  2728. - (void)actionMore:(UITapGestureRecognizer *)gestureRecognizer
  2729. {
  2730. CGPoint touch = [gestureRecognizer locationInView:self.tableView];
  2731. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touch];
  2732. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2733. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2734. if (!serverUrl) return;
  2735. NSString *titoloLock, *titleFavorite;
  2736. if (_metadata.favorite) {
  2737. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_remove_favorites_", nil)];
  2738. } else {
  2739. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_add_favorites_", nil)];
  2740. }
  2741. if (_metadata.directory) {
  2742. // calcolo lockServerUrl
  2743. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2744. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, lockServerUrl]];
  2745. if (directory.lock)
  2746. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_remove_passcode_", nil)];
  2747. else
  2748. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_protect_passcode_", nil)];
  2749. }
  2750. // ******************************************* AHKActionSheet *******************************************
  2751. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.tabBarController.view title:nil];
  2752. actionSheet.animationDuration = 0.2;
  2753. actionSheet.buttonHeight = 50.0;
  2754. actionSheet.cancelButtonHeight = 50.0f;
  2755. actionSheet.separatorHeight = 5.0f;
  2756. actionSheet.automaticallyTintButtonImages = @(NO);
  2757. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].encrypted };
  2758. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  2759. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont boldSystemFontOfSize:17], NSForegroundColorAttributeName:[UIColor blackColor] };
  2760. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor darkGrayColor] };
  2761. actionSheet.separatorColor = [NCBrandColor sharedInstance].seperator;
  2762. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  2763. // ******************************************* DIRECTORY *******************************************
  2764. if (_metadata.directory) {
  2765. BOOL lockDirectory = NO;
  2766. NSString *dirServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2767. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:[NSString stringWithFormat:@"%@/%@", self.serverUrl, _metadata.fileName] account:appDelegate.activeAccount];
  2768. // Directory bloccata ?
  2769. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, dirServerUrl]];
  2770. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil) lockDirectory = YES;
  2771. [actionSheet addButtonWithTitle:_metadata.fileNameView
  2772. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder"] color:[NCBrandColor sharedInstance].brandElement]
  2773. backgroundColor:[NCBrandColor sharedInstance].tabBar
  2774. height:50.0
  2775. type:AHKActionSheetButtonTypeDisabled
  2776. handler:nil
  2777. ];
  2778. [actionSheet addButtonWithTitle: titleFavorite
  2779. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] color:[NCBrandColor sharedInstance].brandElement]
  2780. backgroundColor: [NCBrandColor sharedInstance].backgroundView
  2781. height: 50.0
  2782. type: AHKActionSheetButtonTypeDefault
  2783. handler: ^(AHKActionSheet *as) {
  2784. if (_metadata.favorite) [self removeFavorite:_metadata];
  2785. else [self addFavorite:_metadata];
  2786. }];
  2787. if (!lockDirectory && !isFolderEncrypted) {
  2788. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  2789. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"share"] color:[NCBrandColor sharedInstance].brandElement]
  2790. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2791. height:50.0
  2792. type:AHKActionSheetButtonTypeDefault
  2793. handler:^(AHKActionSheet *as) {
  2794. [self openWindowShare:_metadata];
  2795. }];
  2796. }
  2797. if (!([_metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES) && !lockDirectory && !_metadata.e2eEncrypted) {
  2798. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  2799. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"rename"] color:[NCBrandColor sharedInstance].brandElement]
  2800. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2801. height:50.0
  2802. type:AHKActionSheetButtonTypeDefault
  2803. handler:^(AHKActionSheet *as) {
  2804. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  2805. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  2806. textField.text = _metadata.fileNameView;
  2807. //textField.selectedTextRange = [textField textRangeFromPosition:textField.beginningOfDocument toPosition:textField.endOfDocument];
  2808. //textField.delegate = self;
  2809. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  2810. }];
  2811. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2812. NSLog(@"[LOG] Cancel action");
  2813. }];
  2814. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  2815. UITextField *fileName = alertController.textFields.firstObject;
  2816. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  2817. }];
  2818. okAction.enabled = NO;
  2819. [alertController addAction:cancelAction];
  2820. [alertController addAction:okAction];
  2821. [self presentViewController:alertController animated:YES completion:nil];
  2822. }];
  2823. }
  2824. if (!([_metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES) && !lockDirectory && !isFolderEncrypted) {
  2825. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  2826. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"move"] color:[NCBrandColor sharedInstance].brandElement]
  2827. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2828. height:50.0
  2829. type:AHKActionSheetButtonTypeDefault
  2830. handler:^(AHKActionSheet *as) {
  2831. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  2832. }];
  2833. }
  2834. [actionSheet addButtonWithTitle:NSLocalizedString(@"_delete_", nil)
  2835. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"delete"] color:[NCBrandColor sharedInstance].brandElement]
  2836. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2837. height:50.0
  2838. type:AHKActionSheetButtonTypeDefault
  2839. handler:^(AHKActionSheet *as) {
  2840. [self actionDelete:indexPath];
  2841. }];
  2842. if (!([_metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES)) {
  2843. [actionSheet addButtonWithTitle:NSLocalizedString(@"_folder_automatic_upload_", nil)
  2844. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderPhotos"] color:[NCBrandColor sharedInstance].brandElement]
  2845. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2846. height:50.0
  2847. type:AHKActionSheetButtonTypeDefault
  2848. handler:^(AHKActionSheet *as) {
  2849. // Settings new folder Automatatic upload
  2850. [[NCManageDatabase sharedInstance] setAccountAutoUploadFileName:_metadata.fileName];
  2851. [[NCManageDatabase sharedInstance] setAccountAutoUploadDirectory:serverUrl activeUrl:appDelegate.activeUrl];
  2852. // Clear data (old) Auto Upload
  2853. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:_autoUploadDirectory directoryID:nil];
  2854. [self readFolder:serverUrl];
  2855. }];
  2856. }
  2857. if (!([_metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES)) {
  2858. [actionSheet addButtonWithTitle:titoloLock
  2859. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"settingsPasscodeYES"] color:[NCBrandColor sharedInstance].brandElement]
  2860. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2861. height:50.0
  2862. type:AHKActionSheetButtonTypeDefault
  2863. handler:^(AHKActionSheet *as) {
  2864. [self performSelector:@selector(comandoLockPassword) withObject:nil];
  2865. }];
  2866. }
  2867. if (!_metadata.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  2868. [actionSheet addButtonWithTitle:NSLocalizedString(@"_e2e_set_folder_encrypted_", nil)
  2869. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"lock"] color:[NCBrandColor sharedInstance].encrypted]
  2870. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2871. height:50.0
  2872. type:AHKActionSheetButtonTypeEncrypted
  2873. handler:^(AHKActionSheet *as) {
  2874. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  2875. 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]];
  2876. dispatch_async(dispatch_get_main_queue(), ^{
  2877. if (error) {
  2878. [appDelegate messageNotification:@"_e2e_error_mark_folder_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  2879. } else {
  2880. [[NCManageDatabase sharedInstance] deleteE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, [NSString stringWithFormat:@"%@/%@", self.serverUrl, _metadata.fileName]]];
  2881. [self readFolder:self.serverUrl];
  2882. }
  2883. });
  2884. });
  2885. }];
  2886. }
  2887. if (_metadata.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  2888. [actionSheet addButtonWithTitle:NSLocalizedString(@"_e2e_remove_folder_encrypted_", nil)
  2889. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"lock"] color:[NCBrandColor sharedInstance].encrypted]
  2890. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2891. height:50.0
  2892. type:AHKActionSheetButtonTypeEncrypted
  2893. handler:^(AHKActionSheet *as) {
  2894. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  2895. 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]];
  2896. dispatch_async(dispatch_get_main_queue(), ^{
  2897. if (error) {
  2898. [appDelegate messageNotification:@"_e2e_error_delete_mark_folder_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  2899. } else {
  2900. [[NCManageDatabase sharedInstance] deleteE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, [NSString stringWithFormat:@"%@/%@", self.serverUrl, _metadata.fileName]]];
  2901. [self readFolder:self.serverUrl];
  2902. }
  2903. });
  2904. });
  2905. }];
  2906. }
  2907. [actionSheet show];
  2908. }
  2909. // ******************************************* FILE *******************************************
  2910. if (!_metadata.directory) {
  2911. UIImage *iconHeader;
  2912. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  2913. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, _metadata.fileID]])
  2914. iconHeader = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, _metadata.fileID]];
  2915. else
  2916. iconHeader = [UIImage imageNamed:_metadata.iconName];
  2917. [actionSheet addButtonWithTitle: _metadata.fileNameView
  2918. image: iconHeader
  2919. backgroundColor: [NCBrandColor sharedInstance].tabBar
  2920. height: 50.0
  2921. type: AHKActionSheetButtonTypeDisabled
  2922. handler: nil
  2923. ];
  2924. [actionSheet addButtonWithTitle: titleFavorite
  2925. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] color:[NCBrandColor sharedInstance].brandElement]
  2926. backgroundColor: [NCBrandColor sharedInstance].backgroundView
  2927. height: 50.0
  2928. type: AHKActionSheetButtonTypeDefault
  2929. handler: ^(AHKActionSheet *as) {
  2930. if (_metadata.favorite) [self removeFavorite:_metadata];
  2931. else [self addFavorite:_metadata];
  2932. }];
  2933. if (!_metadataFolder.e2eEncrypted) {
  2934. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  2935. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"share"]color:[NCBrandColor sharedInstance].brandElement]
  2936. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2937. height: 50.0
  2938. type:AHKActionSheetButtonTypeDefault
  2939. handler:^(AHKActionSheet *as) {
  2940. [self openWindowShare:_metadata];
  2941. }];
  2942. }
  2943. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil)
  2944. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"openFile"] color:[NCBrandColor sharedInstance].brandElement]
  2945. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2946. height: 50.0
  2947. type:AHKActionSheetButtonTypeDefault
  2948. handler:^(AHKActionSheet *as) {
  2949. [self performSelector:@selector(openIn:) withObject:_metadata];
  2950. }];
  2951. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  2952. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"rename"] color:[NCBrandColor sharedInstance].brandElement]
  2953. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2954. height: 50.0
  2955. type:AHKActionSheetButtonTypeDefault
  2956. handler:^(AHKActionSheet *as) {
  2957. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  2958. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  2959. textField.text = _metadata.fileNameView;
  2960. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  2961. }];
  2962. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2963. NSLog(@"[LOG] Cancel action");
  2964. }];
  2965. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  2966. UITextField *fileName = alertController.textFields.firstObject;
  2967. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  2968. }];
  2969. okAction.enabled = NO;
  2970. [alertController addAction:cancelAction];
  2971. [alertController addAction:okAction];
  2972. [self presentViewController:alertController animated:YES completion:nil];
  2973. }];
  2974. if (!_metadataFolder.e2eEncrypted) {
  2975. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  2976. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"move"] color:[NCBrandColor sharedInstance].brandElement]
  2977. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2978. height:50.0
  2979. type:AHKActionSheetButtonTypeDefault
  2980. handler:^(AHKActionSheet *as) {
  2981. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  2982. }];
  2983. }
  2984. [actionSheet addButtonWithTitle:NSLocalizedString(@"_delete_", nil)
  2985. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"delete"] color:[NCBrandColor sharedInstance].brandElement]
  2986. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2987. height:50.0
  2988. type:AHKActionSheetButtonTypeDefault
  2989. handler:^(AHKActionSheet *as) {
  2990. [self actionDelete:indexPath];
  2991. }];
  2992. [actionSheet show];
  2993. }
  2994. }
  2995. #pragma --------------------------------------------------------------------------------------------
  2996. #pragma mark - ==== Datasource ====
  2997. #pragma --------------------------------------------------------------------------------------------
  2998. - (void)clearDateReadDataSource:(NSNotification *)notification
  2999. {
  3000. _dateReadDataSource = Nil;
  3001. [self reloadDatasource];
  3002. }
  3003. - (void)reloadDatasource
  3004. {
  3005. [self reloadDatasource:_serverUrl];
  3006. }
  3007. - (void)reloadDatasource:(NSString *)serverUrl
  3008. {
  3009. // test
  3010. if (appDelegate.activeAccount.length == 0 || serverUrl.length == 0 || serverUrl == nil)
  3011. return;
  3012. // Search Mode
  3013. if (_isSearchMode) {
  3014. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:_searchResultMetadatas listProgressMetadata:nil groupByField:_directoryGroupBy activeAccount:appDelegate.activeAccount];
  3015. [self tableViewReloadData];
  3016. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  3017. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  3018. _noFilesSearchDescription = @"";
  3019. }
  3020. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  3021. _noFilesSearchTitle = @"";
  3022. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  3023. }
  3024. [self.tableView reloadEmptyDataSet];
  3025. return;
  3026. }
  3027. // Reload -> Self se non siamo nella dir appropriata cercala e se è in memoria reindirizza il reload
  3028. if ([serverUrl isEqualToString:_serverUrl] == NO || _serverUrl == nil) {
  3029. CCMain *main = [appDelegate.listMainVC objectForKey:serverUrl];
  3030. if (main) {
  3031. [main reloadDatasource];
  3032. } else {
  3033. [self tableViewReloadData];
  3034. [appDelegate.activeTransfers reloadDatasource];
  3035. }
  3036. return;
  3037. }
  3038. [appDelegate.activeTransfers reloadDatasource];
  3039. // Settaggio variabili per le ottimizzazioni
  3040. _directoryGroupBy = [CCUtility getGroupBySettings];
  3041. _directoryOrder = [CCUtility getOrderSettings];
  3042. // Remove optimization for encrypted directory
  3043. if (_metadataFolder.e2eEncrypted)
  3044. _dateReadDataSource = nil;
  3045. // current directoryID
  3046. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  3047. // Controllo data lettura Data Source
  3048. tableDirectory *tableDirectory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, serverUrl]];
  3049. // Get MetadataFolder
  3050. if (![serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]])
  3051. _metadataFolder = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND fileID = %@", appDelegate.activeAccount, tableDirectory.fileID]];
  3052. NSDate *dateDateRecordDirectory = tableDirectory.dateReadDirectory;
  3053. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  3054. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  3055. _dateReadDataSource = [NSDate date];
  3056. // Data Source
  3057. NSString *sorted = _directoryOrder;
  3058. if ([sorted isEqualToString:@"fileName"])
  3059. sorted = @"fileName";
  3060. if (directoryID) {
  3061. NSArray *recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND status = %i", appDelegate.activeAccount, directoryID, k_metadataStatusNormal] sorted:sorted ascending:[CCUtility getAscendingSettings]];
  3062. _sectionDataSource = [CCSectionDataSourceMetadata new];
  3063. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:_directoryGroupBy activeAccount:appDelegate.activeAccount];
  3064. // get auto upload folder
  3065. _autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  3066. _autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:appDelegate.activeUrl];
  3067. }
  3068. } else {
  3069. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  3070. }
  3071. [self tableViewReloadData];
  3072. }
  3073. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  3074. {
  3075. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  3076. if (selectedRows.count > 0) {
  3077. for (NSIndexPath *selectionIndex in selectedRows) {
  3078. NSString *fileID = [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  3079. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3080. [metadatas addObject:metadata];
  3081. }
  3082. }
  3083. return metadatas;
  3084. }
  3085. - (tableMetadata *)getMetadataFromSectionDataSource:(NSIndexPath *)indexPath
  3086. {
  3087. NSInteger section = indexPath.section + 1;
  3088. NSInteger row = indexPath.row + 1;
  3089. NSInteger totSections = [_sectionDataSource.sections count] ;
  3090. if ((totSections < section) || (section > totSections)) {
  3091. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [0] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section]);
  3092. return nil;
  3093. }
  3094. id valueSection = [_sectionDataSource.sections objectAtIndex:indexPath.section];
  3095. NSArray *fileIDs = [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3096. if (fileIDs) {
  3097. NSInteger totRows =[fileIDs count] ;
  3098. if ((totRows < row) || (row > totRows)) {
  3099. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [1] : error row, totRows = %lu - row = %lu", (long)totRows, (long)row]);
  3100. return nil;
  3101. }
  3102. } else {
  3103. NSLog(@"[LOG] DEBUG [2] : fileIDs is NIL");
  3104. return nil;
  3105. }
  3106. NSString *fileID = [fileIDs objectAtIndex:indexPath.row];
  3107. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3108. return metadata;
  3109. }
  3110. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  3111. {
  3112. NSInteger totSections =[_sectionDataSource.sections count] ;
  3113. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  3114. return nil;
  3115. }
  3116. id valueSection = [_sectionDataSource.sections objectAtIndex:section];
  3117. return [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3118. }
  3119. #pragma --------------------------------------------------------------------------------------------
  3120. #pragma mark - ==== Table ====
  3121. #pragma --------------------------------------------------------------------------------------------
  3122. - (void)tableViewSelect:(BOOL)edit
  3123. {
  3124. // chiudiamo eventuali swipe aperti
  3125. if (edit)
  3126. [self.tableView setEditing:NO animated:NO];
  3127. [self.tableView setAllowsMultipleSelectionDuringEditing:edit];
  3128. [self.tableView setEditing:edit animated:YES];
  3129. _isSelectedMode = edit;
  3130. if (edit)
  3131. [self setUINavigationBarSelected];
  3132. else
  3133. [self setUINavigationBarDefault];
  3134. [_selectedFileIDsMetadatas removeAllObjects];
  3135. [self setTitle];
  3136. }
  3137. - (void)tableViewReloadData
  3138. {
  3139. // store selected cells before relod
  3140. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  3141. //store swipeOffset before relod
  3142. [_statusSwipeCell removeAllObjects];
  3143. for (MGSwipeTableCell *cell in self.tableView.visibleCells) {
  3144. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  3145. if (cell != nil && indexPath != nil)
  3146. [_statusSwipeCell setObject:[NSNumber numberWithDouble:cell.swipeOffset] forKey:indexPath];
  3147. }
  3148. // reload table view
  3149. [self.tableView reloadData];
  3150. // selected cells stored
  3151. for (NSIndexPath *path in indexPaths)
  3152. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  3153. [self setTableViewFooter];
  3154. if (self.tableView.editing)
  3155. [self setTitle];
  3156. }
  3157. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  3158. {
  3159. if (tableView.editing == 1) {
  3160. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3161. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  3162. return NO;
  3163. if (metadata == nil || metadata.sessionTaskIdentifier != k_taskIdentifierDone)
  3164. return NO;
  3165. else
  3166. return YES;
  3167. } else {
  3168. [_selectedFileIDsMetadatas removeAllObjects];
  3169. }
  3170. return YES;
  3171. }
  3172. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  3173. {
  3174. return 60;
  3175. }
  3176. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  3177. {
  3178. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  3179. }
  3180. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  3181. {
  3182. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  3183. }
  3184. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  3185. {
  3186. NSArray *sections = [_sectionDataSource.sectionArrayRow allKeys];
  3187. NSString *sectionTitle = [sections objectAtIndex:section];
  3188. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  3189. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  3190. if ([_directoryGroupBy isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  3191. return 20.f;
  3192. }
  3193. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  3194. {
  3195. float shift;
  3196. UIVisualEffectView *visualEffectView;
  3197. NSString *titleSection;
  3198. if (![self indexPathIsValid:[NSIndexPath indexPathForRow:0 inSection:section]])
  3199. return nil;
  3200. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]])
  3201. titleSection = [_sectionDataSource.sections objectAtIndex:section];
  3202. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]])
  3203. titleSection = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:section]];
  3204. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  3205. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  3206. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  3207. else titleSection = NSLocalizedString(titleSection,nil);
  3208. // Format title
  3209. NSString *currentDevice = [CCUtility currentDevice];
  3210. if ([currentDevice rangeOfString:@"iPad3"].location != NSNotFound) {
  3211. visualEffectView = [[UIVisualEffectView alloc] init];
  3212. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.3];
  3213. } else {
  3214. UIVisualEffect *blurEffect;
  3215. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  3216. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  3217. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.2];
  3218. }
  3219. if ([_directoryGroupBy isEqualToString:@"alphabetic"]) {
  3220. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  3221. shift = - 35;
  3222. else
  3223. shift = - 20;
  3224. } else shift = - 10;
  3225. // Title
  3226. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  3227. titleLabel.backgroundColor = [UIColor clearColor];
  3228. titleLabel.textColor = [UIColor blackColor];
  3229. titleLabel.font = [UIFont systemFontOfSize:12];
  3230. titleLabel.textAlignment = NSTextAlignmentLeft;
  3231. titleLabel.text = titleSection;
  3232. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3233. [visualEffectView.contentView addSubview:titleLabel];
  3234. // Elements
  3235. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  3236. elementLabel.backgroundColor = [UIColor clearColor];
  3237. elementLabel.textColor = [UIColor blackColor];;
  3238. elementLabel.font = [UIFont systemFontOfSize:12];
  3239. elementLabel.textAlignment = NSTextAlignmentRight;
  3240. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3241. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  3242. NSUInteger rowsCount = [metadatas count];
  3243. if (rowsCount == 0) return nil;
  3244. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  3245. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  3246. [visualEffectView.contentView addSubview:elementLabel];
  3247. return visualEffectView;
  3248. }
  3249. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  3250. {
  3251. return [_sectionDataSource.sections indexOfObject:title];
  3252. }
  3253. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  3254. {
  3255. if ([_directoryGroupBy isEqualToString:@"alphabetic"])
  3256. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  3257. else
  3258. return nil;
  3259. }
  3260. /*
  3261. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  3262. {
  3263. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  3264. }
  3265. }
  3266. */
  3267. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  3268. {
  3269. NSString *typeCell;
  3270. NSString *dataFile;
  3271. NSString *lunghezzaFile;
  3272. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3273. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  3274. return [tableView dequeueReusableCellWithIdentifier:@"CellMain"];
  3275. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  3276. if (!serverUrl)
  3277. return [tableView dequeueReusableCellWithIdentifier:@"CellMain"];
  3278. if ([metadata.session isEqualToString:@""] || metadata.session == nil) typeCell = @"CellMain";
  3279. else typeCell = @"CellMainTransfer";
  3280. CCCellMainTransfer *cell = (CCCellMainTransfer *)[tableView dequeueReusableCellWithIdentifier:typeCell forIndexPath:indexPath];
  3281. // variable base
  3282. cell.delegate = self;
  3283. cell.indexPath = indexPath;
  3284. // separator
  3285. cell.separatorInset = UIEdgeInsetsMake(0.f, 60.f, 0.f, 0.f);
  3286. // change color selection
  3287. UIView *selectionColor = [[UIView alloc] init];
  3288. selectionColor.backgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  3289. cell.selectedBackgroundView = selectionColor;
  3290. // for checkmark color in editing mode
  3291. cell.tintColor = [NCBrandColor sharedInstance].brandElement;
  3292. if ([typeCell isEqualToString:@"CellMain"]) cell.backgroundColor = [NCBrandColor sharedInstance].backgroundView;
  3293. if ([typeCell isEqualToString:@"CellMainTransfer"]) cell.backgroundColor = [NCBrandColor sharedInstance].transferBackground;
  3294. // ----------------------------------------------------------------------------------------------------------
  3295. // DEFAULT
  3296. // ----------------------------------------------------------------------------------------------------------
  3297. cell.file.image = nil;
  3298. cell.status.image = nil;
  3299. cell.favorite.image = nil;
  3300. cell.shared.image = nil;
  3301. cell.local.image = nil;
  3302. cell.imageTitleSegue = nil;
  3303. cell.labelTitle.enabled = YES;
  3304. cell.labelTitle.text = @"";
  3305. cell.labelInfoFile.enabled = YES;
  3306. cell.labelInfoFile.text = @"";
  3307. cell.progressView.progress = 0.0;
  3308. cell.progressView.hidden = YES;
  3309. cell.cancelTaskButton.hidden = YES;
  3310. cell.reloadTaskButton.hidden = YES;
  3311. cell.stopTaskButton.hidden = YES;
  3312. cell.labelTitle.textColor = [UIColor blackColor];
  3313. // ----------------------------------------------------------------------------------------------------------
  3314. // File Name & Folder
  3315. // ----------------------------------------------------------------------------------------------------------
  3316. // nome del file
  3317. cell.labelTitle.text = metadata.fileNameView;
  3318. // è una directory
  3319. if (metadata.directory) {
  3320. // cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  3321. cell.accessoryType = UITableViewCellAccessoryNone;
  3322. cell.labelInfoFile.text = [CCUtility dateDiff:metadata.date];
  3323. lunghezzaFile = @" ";
  3324. // ----------------------------------------------------------------------------------------------------------
  3325. // Favorite Folder
  3326. // ----------------------------------------------------------------------------------------------------------
  3327. if (metadata.favorite) {
  3328. cell.favorite.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] color:[NCBrandColor sharedInstance].yellowFavorite];
  3329. }
  3330. } else {
  3331. // File
  3332. dataFile = [CCUtility dateDiff:metadata.date];
  3333. lunghezzaFile = [CCUtility transformedSize:metadata.size];
  3334. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  3335. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  3336. [dateFormatter setDateStyle:NSDateFormatterShortStyle];
  3337. [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
  3338. if (localFile && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadata.fileID]])
  3339. cell.local.image = [UIImage imageNamed:@"local"];
  3340. else
  3341. cell.local.image = nil;
  3342. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ %@", dataFile, lunghezzaFile];
  3343. cell.accessoryType = UITableViewCellAccessoryNone;
  3344. }
  3345. // ----------------------------------------------------------------------------------------------------------
  3346. // File Image View
  3347. // ----------------------------------------------------------------------------------------------------------
  3348. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3349. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, metadata.fileID]]) {
  3350. cell.file.image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, metadata.fileID]];
  3351. } else {
  3352. if (metadata.directory) {
  3353. if (metadata.e2eEncrypted) {
  3354. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderEncrypted"] color:[NCBrandColor sharedInstance].brandElement];
  3355. cell.imageTitleSegue = [UIImage imageNamed:@"lock"];
  3356. } else if ([metadata.fileName isEqualToString:_autoUploadFileName] && [self.serverUrl isEqualToString:_autoUploadDirectory]) {
  3357. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderPhotos"] color:[NCBrandColor sharedInstance].brandElement];
  3358. cell.imageTitleSegue = [UIImage imageNamed:@"photos"];
  3359. } else
  3360. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder"] color:[NCBrandColor sharedInstance].brandElement];
  3361. } else {
  3362. cell.file.image = [UIImage imageNamed:metadata.iconName];
  3363. }
  3364. if (metadata.thumbnailExists && _metadataFolder.e2eEncrypted == NO)
  3365. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  3366. }
  3367. // ----------------------------------------------------------------------------------------------------------
  3368. // Image Status Lock Passcode
  3369. // ----------------------------------------------------------------------------------------------------------
  3370. // Directory con passcode lock attivato
  3371. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName];
  3372. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, lockServerUrl]];
  3373. if (metadata.directory && (directory.lock && [[CCUtility getBlockCode] length]))
  3374. cell.status.image = [UIImage imageNamed:@"passcode"];
  3375. // ----------------------------------------------------------------------------------------------------------
  3376. // E2EE Image Status Encrypted
  3377. // ----------------------------------------------------------------------------------------------------------
  3378. if (_metadataFolder.e2eEncrypted && !metadata.directory) {
  3379. tableE2eEncryption *tableE2eEncryption = [[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND fileNameIdentifier = %@", appDelegate.activeAccount, metadata.fileName]];
  3380. if (tableE2eEncryption)
  3381. cell.status.image = [UIImage imageNamed:@"encrypted"];
  3382. }
  3383. // ----------------------------------------------------------------------------------------------------------
  3384. // Favorite
  3385. // ----------------------------------------------------------------------------------------------------------
  3386. if (metadata.favorite) {
  3387. cell.favorite.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] color:[NCBrandColor sharedInstance].yellowFavorite];
  3388. }
  3389. // ----------------------------------------------------------------------------------------------------------
  3390. // Share
  3391. // ----------------------------------------------------------------------------------------------------------
  3392. NSString *shareLink = [appDelegate.sharesLink objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3393. NSString *shareUserAndGroup = [appDelegate.sharesUserAndGroup objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3394. BOOL isShare = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_shared].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_shared].location == NSNotFound);
  3395. BOOL isMounted = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_mounted].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_mounted].location == NSNotFound);
  3396. // Aggiungiamo il Tap per le shared
  3397. if (isShare || [shareLink length] > 0 || [shareUserAndGroup length] > 0 || isMounted) {
  3398. // Shared with you
  3399. if (isShare) {
  3400. if (metadata.directory) {
  3401. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brandElement];
  3402. cell.imageTitleSegue = [UIImage imageNamed:@"share"];
  3403. cell.accessoryType = UITableViewCellAccessoryNone;
  3404. }
  3405. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"share"] color:[NCBrandColor sharedInstance].gray];
  3406. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3407. [tap setNumberOfTapsRequired:1];
  3408. cell.shared.userInteractionEnabled = YES;
  3409. [cell.shared addGestureRecognizer:tap];
  3410. }
  3411. // Mounted with you
  3412. if (isMounted) {
  3413. if (metadata.directory) {
  3414. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_external"] color:[NCBrandColor sharedInstance].brandElement];
  3415. cell.imageTitleSegue = [UIImage imageNamed:@"shareMounted"];
  3416. cell.accessoryType = UITableViewCellAccessoryNone;
  3417. }
  3418. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareMounted"] color:[NCBrandColor sharedInstance].gray];
  3419. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3420. [tap setNumberOfTapsRequired:1];
  3421. cell.shared.userInteractionEnabled = YES;
  3422. [cell.shared addGestureRecognizer:tap];
  3423. }
  3424. // You share
  3425. if ([shareLink length] > 0 || [shareUserAndGroup length] > 0) {
  3426. if (metadata.directory) {
  3427. if ([shareUserAndGroup length] > 0) {
  3428. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brandElement];
  3429. cell.imageTitleSegue = [UIImage imageNamed:@"share"];
  3430. } if ([shareLink length] > 0) {
  3431. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_public"] color:[NCBrandColor sharedInstance].brandElement];
  3432. cell.imageTitleSegue = [UIImage imageNamed:@"sharebylink"];
  3433. }
  3434. cell.shared.userInteractionEnabled = NO;
  3435. } else {
  3436. if ([shareLink length] > 0) {
  3437. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"sharebylink"] color:[NCBrandColor sharedInstance].gray];
  3438. } if ([shareUserAndGroup length] > 0) {
  3439. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"share"] color:[NCBrandColor sharedInstance].gray];
  3440. }
  3441. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  3442. [tap setNumberOfTapsRequired:1];
  3443. cell.shared.userInteractionEnabled = YES;
  3444. [cell.shared addGestureRecognizer:tap];
  3445. }
  3446. }
  3447. } else {
  3448. cell.shared.userInteractionEnabled = NO;
  3449. }
  3450. // ----------------------------------------------------------------------------------------------------------
  3451. // downloadFile
  3452. // ----------------------------------------------------------------------------------------------------------
  3453. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  3454. cell.status.image = [UIImage imageNamed:@"statusdownload"];
  3455. // sessionTaskIdentifier : RELOAD + STOP
  3456. if (metadata.sessionTaskIdentifier != k_taskIdentifierDone) {
  3457. [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3458. cell.cancelTaskButton.hidden = NO;
  3459. [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3460. cell.reloadTaskButton.hidden = NO;
  3461. }
  3462. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3463. float progress = [[appDelegate.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3464. if (progress > 0) {
  3465. cell.progressView.progressTintColor = [UIColor blackColor];
  3466. cell.progressView.progress = progress;
  3467. cell.progressView.hidden = NO;
  3468. }
  3469. // ----------------------------------------------------------------------------------------------------------
  3470. // downloadFile Error
  3471. // ----------------------------------------------------------------------------------------------------------
  3472. if (metadata.sessionTaskIdentifier == k_taskIdentifierError) {
  3473. cell.status.image = [UIImage imageNamed:@"statuserror"];
  3474. if ([metadata.sessionError length] == 0) {
  3475. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_downloaded_",nil)];
  3476. } else {
  3477. cell.labelInfoFile.text = metadata.sessionError;
  3478. }
  3479. }
  3480. }
  3481. // ----------------------------------------------------------------------------------------------------------
  3482. // uploadFile
  3483. // ----------------------------------------------------------------------------------------------------------
  3484. if ([metadata.session length] > 0 && [metadata.session rangeOfString:@"upload"].location != NSNotFound) {
  3485. cell.status.image = [UIImage imageNamed:@"statusupload"];
  3486. [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"removetask"] forState:UIControlStateNormal];
  3487. cell.cancelTaskButton.hidden = NO;
  3488. if (metadata.sessionTaskIdentifier == k_taskIdentifierStop) {
  3489. [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3490. cell.status.image = [UIImage imageNamed:@"statusstop"];
  3491. cell.reloadTaskButton.hidden = NO;
  3492. cell.stopTaskButton.hidden = YES;
  3493. } else {
  3494. [cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3495. cell.stopTaskButton.hidden = NO;
  3496. cell.reloadTaskButton.hidden = YES;
  3497. }
  3498. // se non c'è una preview in bianconero metti l'immagine di default
  3499. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, metadata.fileID]] == NO)
  3500. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"uploaddisable"] color:[NCBrandColor sharedInstance].brandElement];
  3501. cell.labelTitle.enabled = NO;
  3502. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3503. float progress = [[appDelegate.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3504. if (progress > 0) {
  3505. cell.progressView.progressTintColor = [UIColor blackColor];
  3506. cell.progressView.progress = progress;
  3507. cell.progressView.hidden = NO;
  3508. }
  3509. // ----------------------------------------------------------------------------------------------------------
  3510. // uploadFileError
  3511. // ----------------------------------------------------------------------------------------------------------
  3512. if (metadata.sessionTaskIdentifier == k_taskIdentifierError) {
  3513. cell.labelTitle.enabled = NO;
  3514. cell.status.image = [UIImage imageNamed:@"statuserror"];
  3515. if ([metadata.sessionError length] == 0) {
  3516. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_uploaded_",nil)];
  3517. } else {
  3518. cell.labelInfoFile.text = metadata.sessionError;
  3519. }
  3520. }
  3521. }
  3522. [cell.reloadTaskButton addTarget:self action:@selector(reloadTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3523. [cell.cancelTaskButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3524. [cell.stopTaskButton addTarget:self action:@selector(stopTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3525. // ----------------------------------------------------------------------------------------------------------
  3526. // swipe
  3527. // ----------------------------------------------------------------------------------------------------------
  3528. // LEFT
  3529. cell.leftButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] color:[UIColor whiteColor]] backgroundColor:[NCBrandColor sharedInstance].yellowFavorite padding:25]];
  3530. cell.leftExpansion.buttonIndex = 0;
  3531. cell.leftExpansion.fillOnTrigger = NO;
  3532. //centerIconOverText
  3533. MGSwipeButton *favoriteButton = (MGSwipeButton *)[cell.leftButtons objectAtIndex:0];
  3534. [favoriteButton centerIconOverText];
  3535. // RIGHT
  3536. cell.rightButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"delete"] color:[UIColor whiteColor]] backgroundColor:[UIColor redColor] padding:25]];
  3537. cell.rightExpansion.buttonIndex = 0;
  3538. cell.rightExpansion.fillOnTrigger = NO;
  3539. //centerIconOverText
  3540. MGSwipeButton *deleteButton = (MGSwipeButton *)[cell.rightButtons objectAtIndex:0];
  3541. [deleteButton centerIconOverText];
  3542. //restore swipeOffset after relod
  3543. CGFloat swipeOffset = [[_statusSwipeCell objectForKey:indexPath] doubleValue];
  3544. if (swipeOffset < 0) {
  3545. [cell showSwipe:MGSwipeDirectionRightToLeft animated:NO];
  3546. [_statusSwipeCell removeObjectForKey:indexPath];
  3547. } else if (swipeOffset > 0) {
  3548. [cell showSwipe:MGSwipeDirectionLeftToRight animated:NO];
  3549. [_statusSwipeCell removeObjectForKey:indexPath];
  3550. }
  3551. // ----------------------------------------------------------------------------------------------------------
  3552. // more
  3553. // ----------------------------------------------------------------------------------------------------------
  3554. cell.more.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"more"] color:[NCBrandColor sharedInstance].gray];
  3555. if ([self canOpenMenuAction:metadata]) {
  3556. UITapGestureRecognizer *tapMore = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionMore:)];
  3557. [tapMore setNumberOfTapsRequired:1];
  3558. cell.more.userInteractionEnabled = YES;
  3559. [cell.more addGestureRecognizer:tapMore];
  3560. }
  3561. return cell;
  3562. }
  3563. - (void)setTableViewFooter
  3564. {
  3565. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3566. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3567. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3568. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3569. UIFont *appFont = [UIFont systemFontOfSize:12];
  3570. footerLabel.font = appFont;
  3571. footerLabel.textColor = [UIColor grayColor];
  3572. footerLabel.backgroundColor = [UIColor clearColor];
  3573. footerLabel.textAlignment = NSTextAlignmentCenter;
  3574. NSString *folders;
  3575. NSString *files;
  3576. NSString *footerText;
  3577. if (_sectionDataSource.directories > 1) {
  3578. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  3579. } else if (_sectionDataSource.directories == 1){
  3580. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  3581. } else {
  3582. folders = @"";
  3583. }
  3584. if (_sectionDataSource.files > 1) {
  3585. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3586. } else if (_sectionDataSource.files == 1){
  3587. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3588. } else {
  3589. files = @"";
  3590. }
  3591. if ([folders isEqualToString:@""]) {
  3592. footerText = files;
  3593. } else if ([files isEqualToString:@""]) {
  3594. footerText = folders;
  3595. } else {
  3596. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  3597. }
  3598. footerLabel.text = footerText;
  3599. [footerView addSubview:footerLabel];
  3600. [self.tableView setTableFooterView:footerView];
  3601. }
  3602. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  3603. {
  3604. CCCellMain *cell = [tableView cellForRowAtIndexPath:indexPath];
  3605. // settiamo il record file.
  3606. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3607. if (!_metadata)
  3608. return;
  3609. // se non può essere selezionata deseleziona
  3610. if ([cell isEditing] == NO)
  3611. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  3612. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  3613. if (self.tableView.editing) {
  3614. [_selectedFileIDsMetadatas setObject:_metadata forKey:_metadata.fileID];
  3615. [self setTitle];
  3616. return;
  3617. }
  3618. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3619. if (!serverUrl) return;
  3620. // se è in corso una sessione
  3621. if ([_metadata.session length] > 0) return;
  3622. // file
  3623. if (_metadata.directory == NO) {
  3624. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  3625. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, _metadata.fileID]]) {
  3626. [self downloadFileSuccessFailure:_metadata.fileName fileID:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:@"" errorMessage:@"" errorCode:0];
  3627. } else {
  3628. if (_metadataFolder.e2eEncrypted && ![CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  3629. [appDelegate messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  3630. } else {
  3631. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileName fileID:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  3632. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  3633. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  3634. }
  3635. }
  3636. }
  3637. if (_metadata.directory) {
  3638. imageTitleSegue = cell.imageTitleSegue;
  3639. [self performSegueDirectoryWithControlPasscode:true];
  3640. }
  3641. }
  3642. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  3643. {
  3644. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3645. [_selectedFileIDsMetadatas removeObjectForKey:metadata.fileID];
  3646. [self setTitle];
  3647. }
  3648. - (BOOL)indexPathIsValid:(NSIndexPath *)indexPath
  3649. {
  3650. if (!indexPath)
  3651. return NO;
  3652. NSInteger section = indexPath.section;
  3653. NSInteger row = indexPath.row;
  3654. NSInteger lastSectionIndex = [self numberOfSectionsInTableView:self.tableView] - 1;
  3655. if (section > lastSectionIndex || lastSectionIndex < 0)
  3656. return NO;
  3657. NSInteger rowCount = [self.tableView numberOfRowsInSection:indexPath.section] - 1;
  3658. if (rowCount < 0)
  3659. return NO;
  3660. return row <= rowCount;
  3661. }
  3662. #pragma --------------------------------------------------------------------------------------------
  3663. #pragma mark ===== Navigation ====
  3664. #pragma --------------------------------------------------------------------------------------------
  3665. - (BOOL)shouldPerformSegue
  3666. {
  3667. // if background return
  3668. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return NO;
  3669. if (self.view.window == NO)
  3670. return NO;
  3671. // Collapsed ma siamo già in detail esci
  3672. if (self.splitViewController.isCollapsed)
  3673. if (_detailViewController.isViewLoaded && _detailViewController.view.window) return NO;
  3674. return YES;
  3675. }
  3676. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  3677. {
  3678. id viewController = segue.destinationViewController;
  3679. NSMutableArray *allRecordsDataSourceImagesVideos = [NSMutableArray new];
  3680. tableMetadata *metadata;
  3681. if ([viewController isKindOfClass:[UINavigationController class]]) {
  3682. UINavigationController *nav = viewController;
  3683. _detailViewController = (CCDetail *)nav.topViewController;
  3684. } else {
  3685. _detailViewController = segue.destinationViewController;
  3686. }
  3687. if ([sender isKindOfClass:[tableMetadata class]]) {
  3688. metadata = sender;
  3689. [allRecordsDataSourceImagesVideos addObject:sender];
  3690. } else {
  3691. metadata = _metadata;
  3692. for (NSString *fileID in _sectionDataSource.allEtag) {
  3693. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3694. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video] || [metadata.typeFile isEqualToString: k_metadataTypeFile_audio])
  3695. [allRecordsDataSourceImagesVideos addObject:metadata];
  3696. }
  3697. }
  3698. _detailViewController.metadataDetail = metadata;
  3699. _detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  3700. _detailViewController.dateFilterQuery = nil;
  3701. [_detailViewController setTitle:metadata.fileNameView];
  3702. }
  3703. // can i go to next viewcontroller
  3704. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode
  3705. {
  3706. NSString *nomeDir;
  3707. if (self.tableView.editing == NO) {
  3708. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3709. if (!serverUrl) return;
  3710. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  3711. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, lockServerUrl]];
  3712. // 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
  3713. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil && controlPasscode) {
  3714. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  3715. viewController.delegate = self;
  3716. viewController.fromType = CCBKPasscodeFromLockDirectory;
  3717. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  3718. viewController.inputViewTitlePassword = YES;
  3719. if ([CCUtility getSimplyBlockCode]) {
  3720. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  3721. viewController.passcodeInputView.maximumLength = 6;
  3722. } else {
  3723. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  3724. viewController.passcodeInputView.maximumLength = 64;
  3725. }
  3726. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  3727. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  3728. viewController.touchIDManager = touchIDManager;
  3729. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  3730. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  3731. viewController.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
  3732. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  3733. [self presentViewController:navController animated:YES completion:nil];
  3734. return;
  3735. }
  3736. // E2EE Check enable
  3737. if (_metadata.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount] == NO) {
  3738. [appDelegate messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  3739. return;
  3740. }
  3741. nomeDir = _metadata.fileName;
  3742. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:serverUrl addFileName:nomeDir];
  3743. CCMain *viewController = [appDelegate.listMainVC objectForKey:serverUrlPush];
  3744. if (!viewController) {
  3745. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMain"];
  3746. viewController.serverUrl = serverUrlPush;
  3747. viewController.titleMain = _metadata.fileName;
  3748. viewController.textBackButton = _titleMain;
  3749. viewController.imageTitle = imageTitleSegue;
  3750. // save self
  3751. [appDelegate.listMainVC setObject:viewController forKey:serverUrlPush];
  3752. [self.navigationController pushViewController:viewController animated:YES];
  3753. } else {
  3754. if (viewController.isViewLoaded) {
  3755. // Icon Title
  3756. viewController.imageTitle = imageTitleSegue;
  3757. // Fix : Application tried to present modally an active controller
  3758. if ([self.navigationController isBeingPresented]) {
  3759. // being presented
  3760. } else if ([self.navigationController isMovingToParentViewController]) {
  3761. // being pushed
  3762. } else {
  3763. [self.navigationController pushViewController:viewController animated:YES];
  3764. }
  3765. }
  3766. }
  3767. }
  3768. }
  3769. @end