CCMain.m 231 KB

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