CCMain.m 227 KB

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