CCMain.m 239 KB

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