CCMain.m 222 KB

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