CCMain.m 232 KB

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