CCMain.m 238 KB

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