CCMain.m 237 KB

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