CCMain.m 237 KB

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