CCMain.m 236 KB

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