CCMain.m 222 KB

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