CCMain.m 222 KB

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