CCMain.m 235 KB

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