CCMain.m 238 KB

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