CCMain.m 233 KB

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