CCMain.m 237 KB

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