CCMain.m 221 KB

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