CCMain.m 236 KB

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