CCMain.m 238 KB

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