CCMain.m 235 KB

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