CCMain.m 238 KB

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