CCMain.m 222 KB

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