CCMain.m 229 KB

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