CCMain.m 223 KB

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