CCMain.m 238 KB

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