CCMain.m 235 KB

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