CCMain.m 235 KB

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