CCMain.m 233 KB

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