CCMain.m 231 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245
  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. if ([CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  1298. [appDelegate.endToEndInterface getEndToEndMetadata:_metadataFolder.fileName fileID:_metadataFolder.fileID serverUrl:self.serverUrl];
  1299. } else {
  1300. [appDelegate messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  1301. }
  1302. }
  1303. // rewrite title
  1304. [self setTitle];
  1305. }
  1306. - (void)readFolder:(NSString *)serverUrl
  1307. {
  1308. // init control
  1309. if (!serverUrl || !appDelegate.activeAccount || appDelegate.maintenanceMode) {
  1310. [_refreshControl endRefreshing];
  1311. return;
  1312. }
  1313. // Search Mode
  1314. if (_isSearchMode) {
  1315. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrl directoryID:nil];
  1316. _searchFileName = @""; // forced reload searchg
  1317. [self updateSearchResultsForSearchController:self.searchController];
  1318. return;
  1319. }
  1320. _loadingFolder = YES;
  1321. [self tableViewReloadData];
  1322. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, serverUrl]];
  1323. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1324. metadataNet.action = actionReadFolder;
  1325. metadataNet.date = [NSDate date];
  1326. metadataNet.depth = @"1";
  1327. metadataNet.directoryID = directory.directoryID;
  1328. metadataNet.priority = NSOperationQueuePriorityHigh;
  1329. metadataNet.selector = selectorReadFolder;
  1330. metadataNet.serverUrl = serverUrl;
  1331. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1332. }
  1333. #pragma mark -
  1334. #pragma --------------------------------------------------------------------------------------------
  1335. #pragma mark ===== Search =====
  1336. #pragma --------------------------------------------------------------------------------------------
  1337. - (void)searchEnabled:(BOOL)enabled
  1338. {
  1339. if (enabled) {
  1340. if (self.tableView.tableHeaderView != nil)
  1341. return;
  1342. self.definesPresentationContext = YES;
  1343. self.searchController.searchResultsUpdater = self;
  1344. self.searchController.dimsBackgroundDuringPresentation = NO;
  1345. self.searchController.searchBar.translucent = NO;
  1346. self.searchController.searchBar.barTintColor = [NCBrandColor sharedInstance].brand;
  1347. [self.searchController.searchBar sizeToFit];
  1348. self.searchController.searchBar.delegate = self;
  1349. self.searchController.searchBar.backgroundColor = [NCBrandColor sharedInstance].brand;
  1350. self.searchController.searchBar.backgroundImage = [UIImage new];
  1351. // Color Text "Cancel"
  1352. [[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTintColor:[NCBrandColor sharedInstance].brandText];
  1353. self.tableView.tableHeaderView = self.searchController.searchBar;
  1354. [self.tableView setContentOffset:CGPointMake(0, self.searchController.searchBar.frame.size.height - self.tableView.contentOffset.y)];
  1355. } else {
  1356. self.tableView.tableHeaderView = nil;
  1357. }
  1358. }
  1359. - (void)searchStartTimer
  1360. {
  1361. NSString *home = [CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl];
  1362. [[CCActions sharedInstance] search:home fileName:_searchFileName depth:@"infinity" date:nil selector:selectorSearch delegate:self];
  1363. _noFilesSearchTitle = @"";
  1364. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  1365. [self.tableView reloadEmptyDataSet];
  1366. }
  1367. - (void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1368. {
  1369. //[self setNeedsStatusBarAppearanceUpdate];
  1370. _isSearchMode = YES;
  1371. [self deleteRefreshControl];
  1372. NSString *fileName = [CCUtility removeForbiddenCharactersServer:searchController.searchBar.text];
  1373. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1374. _searchFileName = fileName;
  1375. // First : filter
  1376. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1377. if (!directoryID) return;
  1378. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"directoryID = %@ AND account = %@ AND fileNameView CONTAINS[cd] %@", directoryID, appDelegate.activeAccount, fileName];
  1379. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1380. [_searchResultMetadatas removeAllObjects];
  1381. for (tableMetadata *record in records)
  1382. [_searchResultMetadatas addObject:record];
  1383. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1384. metadataNet.account = appDelegate.activeAccount;
  1385. metadataNet.directoryID = directoryID;
  1386. metadataNet.selector = selectorSearch;
  1387. metadataNet.serverUrl = _serverUrl;
  1388. [self readFolderSuccess:metadataNet metadataFolder:nil metadatas:_searchResultMetadatas];
  1389. // Version >= 12
  1390. if ([[NCManageDatabase sharedInstance] getServerVersion] >= 12) {
  1391. [_timerWaitInput invalidate];
  1392. _timerWaitInput = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(searchStartTimer) userInfo:nil repeats:NO];
  1393. }
  1394. }
  1395. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1396. [self reloadDatasource];
  1397. }
  1398. }
  1399. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1400. {
  1401. [self cancelSearchBar];
  1402. [self readFolder:_serverUrl];
  1403. }
  1404. - (void)searchFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1405. {
  1406. // Unauthorized
  1407. if (errorCode == kOCErrorServerUnauthorized)
  1408. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  1409. if (message && errorCode != kOCErrorServerUnauthorized)
  1410. [appDelegate messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1411. _searchFileName = @"";
  1412. }
  1413. - (void)searchSuccess:(CCMetadataNet *)metadataNet metadatas:(NSArray *)metadatas
  1414. {
  1415. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatas];
  1416. [self readFolderSuccess:metadataNet metadataFolder:nil metadatas:metadatas];
  1417. }
  1418. - (void)cancelSearchBar
  1419. {
  1420. if (self.searchController.active) {
  1421. [self.searchController setActive:NO];
  1422. [self createRefreshControl];
  1423. _isSearchMode = NO;
  1424. _searchFileName = @"";
  1425. _dateReadDataSource = nil;
  1426. _searchResultMetadatas = [NSMutableArray new];
  1427. [self reloadDatasource];
  1428. }
  1429. //[self setNeedsStatusBarAppearanceUpdate];
  1430. }
  1431. #pragma mark -
  1432. #pragma --------------------------------------------------------------------------------------------
  1433. #pragma mark ===== Delete File or Folder =====
  1434. #pragma --------------------------------------------------------------------------------------------
  1435. - (void)deleteFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1436. {
  1437. // Unauthorized
  1438. if (errorCode == kOCErrorServerUnauthorized)
  1439. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  1440. NSLog(@"[LOG] Delete File failure error %lu, %@", (long)errorCode, message);
  1441. [self deleteFileOrFolderSuccess:metadataNet];
  1442. }
  1443. - (void)deleteFileOrFolderSuccess:(CCMetadataNet *)metadataNet
  1444. {
  1445. [_queueSelector removeObject:metadataNet.selector];
  1446. if ([_queueSelector count] == 0) {
  1447. [_hud hideHud];
  1448. // next
  1449. [_selectedFileIDsMetadatas removeObjectForKey:metadataNet.fileID];
  1450. if ([_selectedFileIDsMetadatas count] > 0) {
  1451. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1452. [self deleteFileOrFolder:[metadatas objectAtIndex:0] numFile:[_selectedFileIDsMetadatas count] ofFile:_numSelectedFileIDsMetadatas];
  1453. } else {
  1454. // End Select Table View
  1455. [self tableViewSelect:NO];
  1456. // Reload
  1457. if (_isSearchMode)
  1458. [self readFolder:metadataNet.serverUrl];
  1459. else
  1460. [self reloadDatasource:metadataNet.serverUrl];
  1461. }
  1462. }
  1463. }
  1464. - (void)deleteFileOrFolder:(tableMetadata *)metadata numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  1465. {
  1466. [_queueSelector addObject:selectorDelete];
  1467. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self];
  1468. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1469. }
  1470. - (void)deleteFile
  1471. {
  1472. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1473. return;
  1474. [_queueSelector removeAllObjects];
  1475. if ([_selectedFileIDsMetadatas count] > 0) {
  1476. _numSelectedFileIDsMetadatas = [_selectedFileIDsMetadatas count];
  1477. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1478. [self deleteFileOrFolder:[metadatas objectAtIndex:0] numFile:[_selectedFileIDsMetadatas count] ofFile:_numSelectedFileIDsMetadatas];
  1479. } else {
  1480. _numSelectedFileIDsMetadatas = 1;
  1481. [self deleteFileOrFolder:_metadata numFile:1 ofFile:_numSelectedFileIDsMetadatas];
  1482. }
  1483. }
  1484. #pragma --------------------------------------------------------------------------------------------
  1485. #pragma mark ===== Rename / Move =====
  1486. #pragma --------------------------------------------------------------------------------------------
  1487. - (void)renameSuccess:(CCMetadataNet *)metadataNet
  1488. {
  1489. [self readFolder:metadataNet.serverUrl];
  1490. }
  1491. - (void)renameFile:(NSArray *)arguments
  1492. {
  1493. tableMetadata* metadata = [arguments objectAtIndex:0];
  1494. NSString *fileName = [arguments objectAtIndex:1];
  1495. // E2E
  1496. if ([CCUtility isFolderEncrypted:self.serverUrl account:appDelegate.activeAccount]) {
  1497. // verify if exists the new fileName
  1498. if ([[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@ AND fileName = %@", appDelegate.activeAccount, self.serverUrl, fileName]]) {
  1499. [appDelegate messageNotification:@"_error_" description:@"_file_already_exists_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1500. return;
  1501. }
  1502. if ([[NCManageDatabase sharedInstance] renameFileE2eEncryptionWithServerUrl:self.serverUrl fileNameIdentifier:metadata.fileName newFileName:fileName newFileNamePath:[CCUtility returnFileNamePathFromFileName:fileName serverUrl:self.serverUrl activeUrl:appDelegate.activeUrl]]) {
  1503. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  1504. NSError *error = [[CCNetworking sharedNetworking] SendEndToEndMetadataOnServerUrl:self.serverUrl];
  1505. if (error == nil) {
  1506. dispatch_async(dispatch_get_main_queue(), ^{
  1507. [[NCManageDatabase sharedInstance] setMetadataFileNameViewWithDirectoryID:metadata.directoryID fileName:metadata.fileName newFileNameView:fileName];
  1508. [self reloadDatasource];
  1509. });
  1510. } else {
  1511. // Restore previuos fileName on DB
  1512. (void)[[NCManageDatabase sharedInstance] renameFileE2eEncryptionWithServerUrl:self.serverUrl fileNameIdentifier:metadata.fileName newFileName:metadata.fileNameView newFileNamePath:[CCUtility returnFileNamePathFromFileName:metadata.fileNameView serverUrl:self.serverUrl activeUrl:appDelegate.activeUrl]];
  1513. [appDelegate messageNotification:@"_error_" description:[NSString stringWithFormat:@"Error to send metadata %lu", (unsigned long)error.code] visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1514. }
  1515. });
  1516. } else {
  1517. [appDelegate messageNotification:@"_error_" description:@"Error file not found" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1518. }
  1519. } else {
  1520. // Plain
  1521. [[CCActions sharedInstance] renameFileOrFolder:metadata fileName:fileName delegate:self];
  1522. }
  1523. }
  1524. - (void)renameMoveFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1525. {
  1526. if ([metadataNet.selector isEqualToString:selectorMove]) {
  1527. [_hud hideHud];
  1528. if (message && errorCode != kOCErrorServerUnauthorized)
  1529. [appDelegate messageNotification:@"_move_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1530. // End Select Table View
  1531. [self tableViewSelect:NO];
  1532. // reload Datasource
  1533. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1534. [self readFolder:metadataNet.serverUrl];
  1535. else
  1536. [self reloadDatasource];
  1537. }
  1538. }
  1539. - (void)moveSuccess:(CCMetadataNet *)metadataNet
  1540. {
  1541. [_queueSelector removeObject:metadataNet.selector];
  1542. if ([_queueSelector count] == 0) {
  1543. [_hud hideHud];
  1544. NSString *fileName = metadataNet.fileName;
  1545. NSString *directoryID = metadataNet.directoryID;
  1546. NSString *directoryIDTo = metadataNet.directoryIDTo;
  1547. NSString *serverUrlTo = [[NCManageDatabase sharedInstance] getServerUrl:directoryIDTo];
  1548. if (!serverUrlTo) return;
  1549. // FILE -> Metadata
  1550. if (metadataNet.directory == NO)
  1551. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1552. // DIRECTORY -> Directory - CCMetadata
  1553. if (metadataNet.directory == YES) {
  1554. // delete all dir / subdir
  1555. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:[CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:fileName]];
  1556. // move metadata
  1557. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1558. // Add new directory
  1559. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrlTo, fileName];
  1560. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:newDirectory permissions:nil encrypted:false];
  1561. }
  1562. // next
  1563. [_selectedFileIDsMetadatas removeObjectForKey:metadataNet.fileID];
  1564. if ([_selectedFileIDsMetadatas count] > 0) {
  1565. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1566. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrlTo, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1567. } else {
  1568. // End Select Table View
  1569. [self tableViewSelect:NO];
  1570. // reload Datasource
  1571. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1572. [self readFolder:metadataNet.serverUrl];
  1573. else
  1574. [self reloadDatasource];
  1575. }
  1576. }
  1577. }
  1578. - (void)moveFileOrFolderMetadata:(NSArray *)arguments
  1579. {
  1580. tableMetadata *metadata = [arguments objectAtIndex:0];
  1581. NSString *serverUrlTo = [arguments objectAtIndex:1];
  1582. NSInteger numFile = [[arguments objectAtIndex:2] integerValue];
  1583. NSInteger ofFile = [[arguments objectAtIndex:3] integerValue];
  1584. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1585. if (!serverUrl) return;
  1586. NSString *directoryIDTo = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrlTo];
  1587. if (!directoryIDTo) return;
  1588. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  1589. NSArray *items;
  1590. NSError *error = [[NCNetworkingSync sharedManager] readFile:[NSString stringWithFormat:@"%@/%@", serverUrlTo, metadata.fileName] user:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword items:&items];
  1591. if(!error) {
  1592. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1593. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1594. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1595. }];
  1596. [alert addAction:ok];
  1597. [self presentViewController:alert animated:YES completion:nil];
  1598. // End Select Table View
  1599. [self tableViewSelect:NO];
  1600. // reload Datasource
  1601. [self readFileReloadFolder];
  1602. });
  1603. return;
  1604. }
  1605. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1606. metadataNet.action = actionMoveFileOrFolder;
  1607. metadataNet.directory = metadata.directory;
  1608. metadataNet.fileID = metadata.fileID;
  1609. metadataNet.directoryID = metadata.directoryID;
  1610. metadataNet.directoryIDTo = directoryIDTo;
  1611. metadataNet.fileName = metadata.fileName;
  1612. metadataNet.fileNameView = metadata.fileNameView;
  1613. metadataNet.fileNameTo = metadata.fileName;
  1614. metadataNet.etag = metadata.etag;
  1615. metadataNet.selector = selectorMove;
  1616. metadataNet.serverUrl = serverUrl;
  1617. metadataNet.serverUrlTo = serverUrlTo;
  1618. [_queueSelector addObject:metadataNet.selector];
  1619. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1620. dispatch_async(dispatch_get_main_queue(), ^{
  1621. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_move_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1622. });
  1623. });
  1624. }
  1625. // DELEGATE : Move
  1626. - (void)dismissMove
  1627. {
  1628. [self reloadDatasource];
  1629. }
  1630. // DELEGATE : Move
  1631. - (void)moveServerUrlTo:(NSString *)serverUrlTo title:(NSString *)title
  1632. {
  1633. [_queueSelector removeAllObjects];
  1634. // E2E DENIED
  1635. if ([CCUtility isFolderEncrypted:serverUrlTo account:appDelegate.activeAccount]) {
  1636. [appDelegate messageNotification:@"_move_" description:@"Not possible move files to encrypted directory" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  1637. return;
  1638. }
  1639. if ([_selectedFileIDsMetadatas count] > 0) {
  1640. _numSelectedFileIDsMetadatas = [_selectedFileIDsMetadatas count];
  1641. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1642. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrlTo, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1643. } else {
  1644. _numSelectedFileIDsMetadatas = 1;
  1645. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[_metadata, serverUrlTo, [NSNumber numberWithInteger:1], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1646. }
  1647. }
  1648. - (void)moveOpenWindow:(NSArray *)indexPaths
  1649. {
  1650. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1651. return;
  1652. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"CCMove" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMove"];
  1653. CCMove *viewController = (CCMove *)navigationController.topViewController;
  1654. viewController.delegate = self;
  1655. viewController.move.title = NSLocalizedString(@"_move_", nil);
  1656. viewController.tintColor = [NCBrandColor sharedInstance].brandText;
  1657. viewController.barTintColor = [NCBrandColor sharedInstance].brand;
  1658. viewController.tintColorTitle = [NCBrandColor sharedInstance].brandText;
  1659. viewController.networkingOperationQueue = appDelegate.netQueue;
  1660. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  1661. [self presentViewController:navigationController animated:YES completion:nil];
  1662. }
  1663. #pragma --------------------------------------------------------------------------------------------
  1664. #pragma mark ===== Create folder =====
  1665. #pragma --------------------------------------------------------------------------------------------
  1666. - (void)createFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1667. {
  1668. // Unauthorized
  1669. if (errorCode == kOCErrorServerUnauthorized)
  1670. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  1671. if (message && errorCode != kOCErrorServerUnauthorized)
  1672. [appDelegate messageNotification:@"_create_folder_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1673. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID] clearDateReadDirectoryID:nil];
  1674. [self reloadDatasource];
  1675. // We are in directory fail ?
  1676. CCMain *vc = [appDelegate.listMainVC objectForKey:[CCUtility stringAppendServerUrl:_serverUrl addFileName:metadataNet.fileName]];
  1677. if (vc)
  1678. [vc.navigationController popViewControllerAnimated:YES];
  1679. }
  1680. - (void)createFolderSuccess:(CCMetadataNet *)metadataNet
  1681. {
  1682. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", metadataNet.serverUrl, metadataNet.fileName];
  1683. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:newDirectory permissions:nil encrypted:false];
  1684. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileName = %@ AND directoryID = %@", metadataNet.fileName, metadataNet.directoryID]];
  1685. if (metadata) {
  1686. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileName = %@ AND directoryID = %@", metadataNet.fileName, metadataNet.directoryID] clearDateReadDirectoryID:nil];
  1687. metadata.fileID = metadataNet.fileID;
  1688. metadata.date = metadataNet.date;
  1689. metadata.permissions = @"RDNVCK";
  1690. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1691. [self reloadDatasource];
  1692. } else {
  1693. [self readFileReloadFolder];
  1694. }
  1695. }
  1696. - (void)createFolder:(NSString *)fileNameFolder serverUrl:(NSString *)serverUrl
  1697. {
  1698. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1699. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1700. if (![fileNameFolder length]) return;
  1701. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1702. if (!directoryID) return;
  1703. metadataNet.action = actionCreateFolder;
  1704. metadataNet.directoryID = directoryID;
  1705. metadataNet.fileID = [[NSUUID UUID] UUIDString];
  1706. metadataNet.fileName = fileNameFolder;
  1707. metadataNet.selector = selectorCreateFolder;
  1708. metadataNet.serverUrl = serverUrl;
  1709. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1710. // Create Directory on metadata
  1711. 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];
  1712. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1713. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:_serverUrl directoryID:nil];
  1714. [self reloadDatasource];
  1715. }
  1716. #pragma --------------------------------------------------------------------------------------------
  1717. #pragma mark ===== Progress & Task Button =====
  1718. #pragma --------------------------------------------------------------------------------------------
  1719. - (void)triggerProgressTask:(NSNotification *)notification
  1720. {
  1721. NSDictionary *dict = notification.userInfo;
  1722. NSString *fileID = [dict valueForKey:@"fileID"];
  1723. NSString *serverUrl = [dict valueForKey:@"serverUrl"];
  1724. float progress = [[dict valueForKey:@"progress"] floatValue];
  1725. // Check
  1726. if (!fileID || [fileID isEqualToString: @""])
  1727. return;
  1728. [appDelegate.listProgressMetadata setObject:[NSNumber numberWithFloat:progress] forKey:fileID];
  1729. if (![serverUrl isEqualToString:_serverUrl])
  1730. return;
  1731. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:fileID];
  1732. if ([self indexPathIsValid:indexPath]) {
  1733. CCTransfersCell *cell = (CCTransfersCell *)[self.tableView cellForRowAtIndexPath:indexPath];
  1734. cell.progressView.progressTintColor = [UIColor blackColor];
  1735. cell.progressView.hidden = NO;
  1736. [cell.progressView setProgress:progress];
  1737. }
  1738. }
  1739. - (void)reloadTaskButton:(id)sender withEvent:(UIEvent *)event
  1740. {
  1741. UITouch * touch = [[event allTouches] anyObject];
  1742. CGPoint location = [touch locationInView:self.tableView];
  1743. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1744. if ([self indexPathIsValid:indexPath]) {
  1745. tableMetadata *metadataSection = [self getMetadataFromSectionDataSource:indexPath];
  1746. if (metadataSection) {
  1747. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataSection.fileID]];
  1748. if (metadata)
  1749. [self reloadTaskButton:metadata];
  1750. }
  1751. }
  1752. }
  1753. - (void)reloadTaskButton:(tableMetadata *)metadata
  1754. {
  1755. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1756. __block NSURLSessionTask *findTask;
  1757. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1758. NSString *fileID = metadata.fileID;
  1759. // DOWNLOAD
  1760. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  1761. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1762. for (NSURLSessionUploadTask *task in downloadTasks)
  1763. if (task.taskIdentifier == sessionTaskIdentifier) {
  1764. findTask = task;
  1765. [appDelegate.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  1766. [task cancel];
  1767. }
  1768. if (!findTask) {
  1769. [appDelegate.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  1770. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1771. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1772. }
  1773. }];
  1774. }
  1775. // UPLOAD
  1776. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1777. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1778. for (NSURLSessionUploadTask *task in uploadTasks)
  1779. if (task.taskIdentifier == sessionTaskIdentifier) {
  1780. findTask = task;
  1781. [appDelegate.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  1782. [task cancel];
  1783. }
  1784. if (!findTask) {
  1785. [appDelegate.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  1786. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1787. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1788. }
  1789. }];
  1790. }
  1791. }
  1792. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  1793. {
  1794. UITouch * touch = [[event allTouches] anyObject];
  1795. CGPoint location = [touch locationInView:self.tableView];
  1796. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1797. if ([self indexPathIsValid:indexPath]) {
  1798. tableMetadata *metadataSection = [self getMetadataFromSectionDataSource:indexPath];
  1799. if (metadataSection) {
  1800. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataSection.fileID]];
  1801. if (metadata)
  1802. [self cancelTaskButton:metadata reloadTable:YES];
  1803. }
  1804. }
  1805. }
  1806. - (void)cancelTaskButton:(tableMetadata *)metadata reloadTable:(BOOL)reloadTable
  1807. {
  1808. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1809. __block NSURLSessionTask *findTask;
  1810. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1811. NSString *fileID = metadata.fileID;
  1812. // DOWNLOAD
  1813. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  1814. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1815. for (NSURLSessionTask *task in downloadTasks)
  1816. if (task.taskIdentifier == sessionTaskIdentifier) {
  1817. findTask = task;
  1818. [appDelegate.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  1819. [task cancel];
  1820. }
  1821. if (!findTask) {
  1822. [appDelegate.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  1823. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1824. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1825. }
  1826. }];
  1827. }
  1828. // UPLOAD
  1829. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1830. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1831. for (NSURLSessionUploadTask *task in uploadTasks)
  1832. if (task.taskIdentifier == sessionTaskIdentifier) {
  1833. findTask = task;
  1834. [appDelegate.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  1835. [task cancel];
  1836. }
  1837. if (!findTask) {
  1838. [appDelegate.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  1839. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1840. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1841. }
  1842. }];
  1843. }
  1844. }
  1845. - (void)stopTaskButton:(id)sender withEvent:(UIEvent *)event
  1846. {
  1847. UITouch * touch = [[event allTouches] anyObject];
  1848. CGPoint location = [touch locationInView:self.tableView];
  1849. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1850. if ([self indexPathIsValid:indexPath]) {
  1851. tableMetadata *metadataSection = [self getMetadataFromSectionDataSource:indexPath];
  1852. if (metadataSection) {
  1853. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataSection.fileID]];
  1854. if (metadata)
  1855. [self stopTaskButton:metadata];
  1856. }
  1857. }
  1858. }
  1859. - (void)stopTaskButton:(tableMetadata *)metadata
  1860. {
  1861. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1862. __block NSURLSessionTask *findTask;
  1863. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1864. NSString *fileID = metadata.fileID;
  1865. // UPLOAD
  1866. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1867. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1868. for (NSURLSessionUploadTask *task in uploadTasks)
  1869. if (task.taskIdentifier == sessionTaskIdentifier) {
  1870. [appDelegate.listChangeTask setObject:@"stopUpload" forKey:fileID];
  1871. findTask = task;
  1872. [task cancel];
  1873. }
  1874. if (!findTask) {
  1875. [appDelegate.listChangeTask setObject:@"stopUpload" forKey:fileID];
  1876. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1877. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1878. }
  1879. }];
  1880. }
  1881. }
  1882. #pragma --------------------------------------------------------------------------------------------
  1883. #pragma mark ===== Shared =====
  1884. #pragma --------------------------------------------------------------------------------------------
  1885. - (void)readSharedSuccess:(CCMetadataNet *)metadataNet items:(NSDictionary *)items openWindow:(BOOL)openWindow
  1886. {
  1887. [_hud hideHud];
  1888. // change account ?
  1889. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1890. if([record.account isEqualToString:metadataNet.account] == NO)
  1891. return;
  1892. NSArray *result = [[NCManageDatabase sharedInstance] updateShare:items activeUrl:appDelegate.activeUrl];
  1893. if (result) {
  1894. appDelegate.sharesLink = result[0];
  1895. appDelegate.sharesUserAndGroup = result[1];
  1896. }
  1897. // Notify Shares View
  1898. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"SharesReloadDatasource" object:nil userInfo:nil];
  1899. if (openWindow) {
  1900. if (_shareOC) {
  1901. [_shareOC reloadData];
  1902. } else {
  1903. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  1904. // Apriamo la view
  1905. _shareOC = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareOC"];
  1906. _shareOC.delegate = self;
  1907. _shareOC.metadata = metadata;
  1908. _shareOC.serverUrl = metadataNet.serverUrl;
  1909. _shareOC.shareLink = [appDelegate.sharesLink objectForKey:metadata.fileID];
  1910. _shareOC.shareUserAndGroup = [appDelegate.sharesUserAndGroup objectForKey:metadata.fileID];
  1911. [_shareOC setModalPresentationStyle:UIModalPresentationFormSheet];
  1912. [self presentViewController:_shareOC animated:YES completion:nil];
  1913. }
  1914. }
  1915. [self tableViewReloadData];
  1916. }
  1917. - (void)shareFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1918. {
  1919. [_hud hideHud];
  1920. // Unauthorized
  1921. if (errorCode == kOCErrorServerUnauthorized)
  1922. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  1923. if (errorCode != kOCErrorServerUnauthorized)
  1924. [appDelegate messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1925. if (_shareOC)
  1926. [_shareOC reloadData];
  1927. [self tableViewReloadData];
  1928. }
  1929. - (void)share:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password
  1930. {
  1931. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1932. metadataNet.action = actionShare;
  1933. metadataNet.fileID = metadata.fileID;
  1934. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:appDelegate.activeUrl];
  1935. metadataNet.fileNameView = metadata.fileNameView;
  1936. metadataNet.password = password;
  1937. metadataNet.selector = selectorShare;
  1938. metadataNet.serverUrl = serverUrl;
  1939. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1940. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1941. }
  1942. - (void)unShareSuccess:(CCMetadataNet *)metadataNet
  1943. {
  1944. [_hud hideHud];
  1945. // rimuoviamo la condivisione da db
  1946. NSArray *result = [[NCManageDatabase sharedInstance] unShare:metadataNet.share fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl sharesLink:appDelegate.sharesLink sharesUserAndGroup:appDelegate.sharesUserAndGroup];
  1947. if (result) {
  1948. appDelegate.sharesLink = result[0];
  1949. appDelegate.sharesUserAndGroup = result[1];
  1950. }
  1951. if (_shareOC)
  1952. [_shareOC reloadData];
  1953. [self tableViewReloadData];
  1954. }
  1955. - (void)unShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl
  1956. {
  1957. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1958. metadataNet.action = actionUnShare;
  1959. metadataNet.fileID = metadata.fileID;
  1960. metadataNet.fileName = metadata.fileName;
  1961. metadataNet.fileNameView = metadata.fileNameView;
  1962. metadataNet.selector = selectorUnshare;
  1963. metadataNet.serverUrl = serverUrl;
  1964. metadataNet.share = share;
  1965. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1966. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1967. }
  1968. - (void)updateShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password expirationTime:(NSString *)expirationTime permission:(NSInteger)permission
  1969. {
  1970. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1971. metadataNet.action = actionUpdateShare;
  1972. metadataNet.fileID = metadata.fileID;
  1973. metadataNet.expirationTime = expirationTime;
  1974. metadataNet.password = password;
  1975. metadataNet.selector = selectorUpdateShare;
  1976. metadataNet.serverUrl = serverUrl;
  1977. metadataNet.share = share;
  1978. metadataNet.sharePermission = permission;
  1979. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1980. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1981. }
  1982. - (void)getUserAndGroupSuccess:(CCMetadataNet *)metadataNet items:(NSArray *)items
  1983. {
  1984. [_hud hideHud];
  1985. if (_shareOC)
  1986. [_shareOC reloadUserAndGroup:items];
  1987. }
  1988. - (void)getUserAndGroupFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1989. {
  1990. [_hud hideHud];
  1991. // Unauthorized
  1992. if (errorCode == kOCErrorServerUnauthorized)
  1993. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  1994. if (errorCode != kOCErrorServerUnauthorized)
  1995. [appDelegate messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1996. }
  1997. - (void)getUserAndGroup:(NSString *)find
  1998. {
  1999. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  2000. metadataNet.action = actionGetUserAndGroup;
  2001. metadataNet.options = find;
  2002. metadataNet.selector = selectorGetUserAndGroup;
  2003. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  2004. [_hud visibleIndeterminateHud];
  2005. }
  2006. - (void)shareUserAndGroup:(NSString *)user shareeType:(NSInteger)shareeType permission:(NSInteger)permission metadata:(tableMetadata *)metadata directoryID:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  2007. {
  2008. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  2009. metadataNet.action = actionShareWith;
  2010. metadataNet.fileID = metadata.fileID;
  2011. metadataNet.directoryID = directoryID;
  2012. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:appDelegate.activeUrl];
  2013. metadataNet.fileNameView = metadata.fileNameView;
  2014. metadataNet.serverUrl = serverUrl;
  2015. metadataNet.selector = selectorShare;
  2016. metadataNet.share = user;
  2017. metadataNet.shareeType = shareeType;
  2018. metadataNet.sharePermission = permission;
  2019. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  2020. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2021. }
  2022. - (void)openWindowShare:(tableMetadata *)metadata
  2023. {
  2024. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2025. if (!serverUrl) return;
  2026. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  2027. metadataNet.action = actionReadShareServer;
  2028. metadataNet.fileID = metadata.fileID;
  2029. metadataNet.fileName = metadata.fileName;
  2030. metadataNet.fileNameView = metadata.fileNameView;
  2031. metadataNet.selector = selectorOpenWindowShare;
  2032. metadataNet.serverUrl = serverUrl;
  2033. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  2034. [_hud visibleIndeterminateHud];
  2035. }
  2036. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  2037. {
  2038. CGPoint location = [tapGesture locationInView:self.tableView];
  2039. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  2040. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2041. if (metadata)
  2042. [self openWindowShare:metadata];
  2043. }
  2044. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  2045. {
  2046. CGPoint location = [tapGesture locationInView:self.tableView];
  2047. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  2048. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2049. if (metadata) {
  2050. CCShareInfoCMOC *vc = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareInfoCMOC"];
  2051. vc.metadata = metadata;
  2052. [vc setModalPresentationStyle:UIModalPresentationFormSheet];
  2053. [self presentViewController:vc animated:YES completion:nil];
  2054. }
  2055. }
  2056. #pragma --------------------------------------------------------------------------------------------
  2057. #pragma mark ===== Favorite =====
  2058. #pragma --------------------------------------------------------------------------------------------
  2059. - (void)settingFavoriteSuccess:(CCMetadataNet *)metadataNet
  2060. {
  2061. _dateReadDataSource = nil;
  2062. [[NCManageDatabase sharedInstance] setMetadataFavoriteWithFileID:metadataNet.fileID favorite:[metadataNet.options boolValue]];
  2063. if (_isSearchMode)
  2064. [self readFolder:metadataNet.serverUrl];
  2065. else
  2066. [self reloadDatasource:metadataNet.serverUrl];
  2067. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  2068. if (metadata.directory && metadata.favorite) {
  2069. NSString *dir = [CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:metadata.fileName];
  2070. [appDelegate.activeFavorites addFavoriteFolder:dir];
  2071. }
  2072. }
  2073. - (void)settingFavoriteFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2074. {
  2075. // Unauthorized
  2076. if (errorCode == kOCErrorServerUnauthorized)
  2077. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  2078. NSLog(@"[LOG] Setting Favorite failure error %lu, %@", (long)errorCode, message);
  2079. }
  2080. - (void)addFavorite:(tableMetadata *)metadata
  2081. {
  2082. if (metadata.directory) {
  2083. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  2084. } else {
  2085. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2086. if (serverUrl)
  2087. [[CCNetworking sharedNetworking] downloadFile:metadata.fileName fileID:metadata.fileID serverUrl:serverUrl selector:selectorAddFavorite selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2088. }
  2089. }
  2090. - (void)removeFavorite:(tableMetadata *)metadata
  2091. {
  2092. [[CCActions sharedInstance] settingFavorite:metadata favorite:NO delegate:self];
  2093. }
  2094. #pragma --------------------------------------------------------------------------------------------
  2095. #pragma mark ===== Open in... =====
  2096. #pragma --------------------------------------------------------------------------------------------
  2097. - (void)openIn:(tableMetadata *)metadata
  2098. {
  2099. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2100. if (!serverUrl) return;
  2101. [[CCNetworking sharedNetworking] downloadFile:metadata.fileName fileID:metadata.fileID serverUrl:serverUrl selector:selectorOpenIn selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2102. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2103. if ([self indexPathIsValid:indexPath])
  2104. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2105. }
  2106. #pragma --------------------------------------------------------------------------------------------
  2107. #pragma mark ===== Remove Local File =====
  2108. #pragma --------------------------------------------------------------------------------------------
  2109. - (void)removeLocalFile:(tableMetadata *)metadata
  2110. {
  2111. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2112. if (!serverUrl) return;
  2113. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  2114. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadata.fileID] error:nil];
  2115. [self reloadDatasource:serverUrl];
  2116. }
  2117. #pragma --------------------------------------------------------------------------------------------
  2118. #pragma mark ===== Order Table & GroupBy & DirectoryOnTop =====
  2119. #pragma --------------------------------------------------------------------------------------------
  2120. - (void)orderTable:(NSString *)order
  2121. {
  2122. [CCUtility setOrderSettings:order];
  2123. // Clear data-read of DataSource
  2124. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2125. }
  2126. - (void)ascendingTable:(BOOL)ascending
  2127. {
  2128. [CCUtility setAscendingSettings:ascending];
  2129. // Clear data-read of DataSource
  2130. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2131. }
  2132. - (void)directoryOnTop:(BOOL)directoryOnTop
  2133. {
  2134. [CCUtility setDirectoryOnTop:directoryOnTop];
  2135. // Clear data-read of DataSource
  2136. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2137. }
  2138. - (void)tableGroupBy:(NSString *)groupBy
  2139. {
  2140. [CCUtility setGroupBySettings:groupBy];
  2141. // Clear data-read of DataSource
  2142. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2143. }
  2144. #pragma --------------------------------------------------------------------------------------------
  2145. #pragma mark ==== Menu LOGO ====
  2146. #pragma --------------------------------------------------------------------------------------------
  2147. - (void)menuLogo:(UIGestureRecognizer *)theGestureRecognizer
  2148. {
  2149. if (appDelegate.reSelectMenu.isOpen || appDelegate.reMainMenu.isOpen)
  2150. return;
  2151. // Brand
  2152. if ([NCBrandOptions sharedInstance].disable_multiaccount)
  2153. return;
  2154. NSUInteger numInSession = [[[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session != ''", appDelegate.activeAccount] sorted:nil ascending:NO] count];
  2155. NSUInteger numInQueue = [appDelegate.netQueue operationCount];
  2156. if (numInSession+numInQueue > 0) {
  2157. [JDStatusBarNotification showWithStatus:NSLocalizedString(@"_transfers_in_queue_", nil) dismissAfter:k_dismissAfterSecond styleName:JDStatusBarStyleDefault];
  2158. return;
  2159. }
  2160. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  2161. NSMutableArray *menuArray = [NSMutableArray new];
  2162. for (NSString *account in listAccount) {
  2163. if ([account isEqualToString:appDelegate.activeAccount]) continue;
  2164. CCMenuItem *item = [[CCMenuItem alloc] init];
  2165. item.title = [account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  2166. item.argument = account;
  2167. item.image = [UIImage imageNamed:@"menuLogoUser"];
  2168. item.target = self;
  2169. item.action = @selector(changeDefaultAccount:);
  2170. [menuArray addObject:item];
  2171. }
  2172. if ([menuArray count] == 0)
  2173. return;
  2174. OptionalConfiguration options;
  2175. Color textColor, backgroundColor;
  2176. textColor.R = 0;
  2177. textColor.G = 0;
  2178. textColor.B = 0;
  2179. backgroundColor.R = 1;
  2180. backgroundColor.G = 1;
  2181. backgroundColor.B = 1;
  2182. options.arrowSize = 9;
  2183. options.marginXSpacing = 7;
  2184. options.marginYSpacing = 10;
  2185. options.intervalSpacing = 20;
  2186. options.menuCornerRadius = 6.5;
  2187. options.maskToBackground = NO;
  2188. options.shadowOfMenu = YES;
  2189. options.hasSeperatorLine = YES;
  2190. options.seperatorLineHasInsets = YES;
  2191. options.textColor = textColor;
  2192. options.menuBackgroundColor = backgroundColor;
  2193. CGRect rect = self.view.frame;
  2194. CGFloat locationY = [theGestureRecognizer locationInView: self.navigationController.navigationBar].y;
  2195. CGFloat safeAreaTop = 0;
  2196. CGFloat offsetY = 35;
  2197. if (@available(iOS 11, *)) {
  2198. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top / 2;
  2199. }
  2200. rect.origin.y = locationY + safeAreaTop + offsetY;
  2201. rect.size.height = rect.size.height - locationY - safeAreaTop - offsetY;
  2202. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  2203. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  2204. }
  2205. - (void)changeDefaultAccount:(CCMenuItem *)sender
  2206. {
  2207. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  2208. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2209. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:[sender argument]];
  2210. if (tableAccount) {
  2211. [appDelegate settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activeUserID:tableAccount.userID activePassword:tableAccount.password];
  2212. // go to home sweet home
  2213. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initializeMain" object:nil];
  2214. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  2215. }
  2216. });
  2217. }
  2218. #pragma --------------------------------------------------------------------------------------------
  2219. #pragma mark ==== ReMenu ====
  2220. #pragma --------------------------------------------------------------------------------------------
  2221. - (void)createReMenuBackgroundView:(REMenu *)menu
  2222. {
  2223. CGFloat safeAreaBottom = 0;
  2224. CGFloat safeAreaTop = 0;
  2225. CGFloat statusBar = 0;
  2226. if (@available(iOS 11, *)) {
  2227. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top;
  2228. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  2229. }
  2230. if ([UIApplication sharedApplication].isStatusBarHidden) {
  2231. statusBar = 13;
  2232. }
  2233. CGFloat computeNavigationBarOffset = [menu computeNavigationBarOffset];
  2234. UIViewController *rootController = [[[[UIApplication sharedApplication]delegate] window] rootViewController];
  2235. CGRect globalPositionMenu = [menu.menuView convertRect:menu.menuView.bounds toView:rootController.view];
  2236. _reMenuBackgroundView.frame = CGRectMake(0, computeNavigationBarOffset, globalPositionMenu.size.width, rootController.view.frame.size.height);
  2237. [UIView animateWithDuration:0.2 animations:^{
  2238. CGFloat minimum = safeAreaBottom + self.tabBarController.tabBar.frame.size.height;
  2239. CGFloat y = rootController.view.frame.size.height - menu.menuView.frame.size.height - globalPositionMenu.origin.y + statusBar;
  2240. if (y>minimum) {
  2241. _reMenuBackgroundView.frame = CGRectMake(0, rootController.view.frame.size.height, globalPositionMenu.size.width, - y);
  2242. [self.tabBarController.view addSubview:_reMenuBackgroundView];
  2243. }
  2244. }];
  2245. }
  2246. - (void)createReMainMenu
  2247. {
  2248. NSString *ordinamento;
  2249. NSString *groupBy = _directoryGroupBy;
  2250. __block NSString *nuovoOrdinamento;
  2251. NSString *titoloNuovo, *titoloAttuale;
  2252. BOOL ascendente;
  2253. __block BOOL nuovoAscendente;
  2254. UIImage *image;
  2255. // ITEM SELECT ----------------------------------------------------------------------------------------------------
  2256. appDelegate.selezionaItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_", nil)subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"seleziona"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2257. if ([_sectionDataSource.allRecordsDataSource count] > 0) {
  2258. [self tableViewSelect:YES];
  2259. }
  2260. }];
  2261. // ITEM ORDER ----------------------------------------------------------------------------------------------------
  2262. ordinamento = _directoryOrder;
  2263. if ([ordinamento isEqualToString:@"fileName"]) {
  2264. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdeyByDate"] color:[NCBrandColor sharedInstance].brand];
  2265. titoloNuovo = NSLocalizedString(@"_order_by_date_", nil);
  2266. titoloAttuale = NSLocalizedString(@"_current_order_name_", nil);
  2267. nuovoOrdinamento = @"date";
  2268. }
  2269. if ([ordinamento isEqualToString:@"date"]) {
  2270. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrderByFileName"] color:[NCBrandColor sharedInstance].brand];
  2271. titoloNuovo = NSLocalizedString(@"_order_by_name_", nil);
  2272. titoloAttuale = NSLocalizedString(@"_current_order_date_", nil);
  2273. nuovoOrdinamento = @"fileName";
  2274. }
  2275. appDelegate.ordinaItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2276. [self orderTable:nuovoOrdinamento];
  2277. }];
  2278. // ITEM ASCENDING -----------------------------------------------------------------------------------------------------
  2279. ascendente = [CCUtility getAscendingSettings];
  2280. if (ascendente) {
  2281. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoDiscendente"] color:[NCBrandColor sharedInstance].brand];
  2282. titoloNuovo = NSLocalizedString(@"_sort_descending_", nil);
  2283. titoloAttuale = NSLocalizedString(@"_current_sort_ascending_", nil);
  2284. nuovoAscendente = false;
  2285. }
  2286. if (!ascendente) {
  2287. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoAscendente"] color:[NCBrandColor sharedInstance].brand];
  2288. titoloNuovo = NSLocalizedString(@"_sort_ascending_", nil);
  2289. titoloAttuale = NSLocalizedString(@"_current_sort_descending_", nil);
  2290. nuovoAscendente = true;
  2291. }
  2292. appDelegate.ascendenteItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2293. [self ascendingTable:nuovoAscendente];
  2294. }];
  2295. // ITEM ALPHABETIC -----------------------------------------------------------------------------------------------------
  2296. if ([groupBy isEqualToString:@"alphabetic"]) { titoloNuovo = NSLocalizedString(@"_group_alphabetic_yes_", nil); }
  2297. else { titoloNuovo = NSLocalizedString(@"_group_alphabetic_no_", nil); }
  2298. appDelegate.alphabeticItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByAlphabetic"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2299. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  2300. else [self tableGroupBy:@"alphabetic"];
  2301. }];
  2302. // ITEM TYPEFILE -------------------------------------------------------------------------------------------------------
  2303. if ([groupBy isEqualToString:@"typefile"]) { titoloNuovo = NSLocalizedString(@"_group_typefile_yes_", nil); }
  2304. else { titoloNuovo = NSLocalizedString(@"_group_typefile_no_", nil); }
  2305. appDelegate.typefileItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByTypeFile"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2306. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  2307. else [self tableGroupBy:@"typefile"];
  2308. }];
  2309. // ITEM DATE -------------------------------------------------------------------------------------------------------
  2310. if ([groupBy isEqualToString:@"date"]) { titoloNuovo = NSLocalizedString(@"_group_date_yes_", nil); }
  2311. else { titoloNuovo = NSLocalizedString(@"_group_date_no_", nil); }
  2312. appDelegate.dateItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByDate"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2313. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  2314. else [self tableGroupBy:@"date"];
  2315. }];
  2316. // ITEM DIRECTORY ON TOP ------------------------------------------------------------------------------------------------
  2317. if ([CCUtility getDirectoryOnTop]) { titoloNuovo = NSLocalizedString(@"_directory_on_top_yes_", nil); }
  2318. else { titoloNuovo = NSLocalizedString(@"_directory_on_top_no_", nil); }
  2319. appDelegate.directoryOnTopItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"menuDirectoryOnTop"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2320. if ([CCUtility getDirectoryOnTop])
  2321. [self directoryOnTop:NO];
  2322. else
  2323. [self directoryOnTop:YES];
  2324. }];
  2325. // REMENU --------------------------------------------------------------------------------------------------------------
  2326. appDelegate.reMainMenu = [[REMenu alloc] initWithItems:@[appDelegate.selezionaItem, appDelegate.ordinaItem, appDelegate.ascendenteItem, appDelegate.alphabeticItem, appDelegate.typefileItem, appDelegate.dateItem, appDelegate.directoryOnTopItem]];
  2327. appDelegate.reMainMenu.imageOffset = CGSizeMake(5, -1);
  2328. appDelegate.reMainMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2329. appDelegate.reMainMenu.imageOffset = CGSizeMake(0, 0);
  2330. appDelegate.reMainMenu.waitUntilAnimationIsComplete = NO;
  2331. appDelegate.reMainMenu.separatorHeight = 0.5;
  2332. appDelegate.reMainMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2333. appDelegate.reMainMenu.backgroundColor = [NCBrandColor sharedInstance].backgroundView;
  2334. appDelegate.reMainMenu.textColor = [UIColor blackColor];
  2335. appDelegate.reMainMenu.textAlignment = NSTextAlignmentLeft;
  2336. appDelegate.reMainMenu.textShadowColor = nil;
  2337. appDelegate.reMainMenu.textOffset = CGSizeMake(50, 0.0);
  2338. appDelegate.reMainMenu.font = [UIFont systemFontOfSize:14.0];
  2339. appDelegate.reMainMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2340. appDelegate.reMainMenu.highlightedSeparatorColor = nil;
  2341. appDelegate.reMainMenu.highlightedTextColor = [UIColor blackColor];
  2342. appDelegate.reMainMenu.highlightedTextShadowColor = nil;
  2343. appDelegate.reMainMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2344. appDelegate.reMainMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  2345. appDelegate.reMainMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2346. appDelegate.reMainMenu.subtitleTextShadowColor = nil;
  2347. appDelegate.reMainMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2348. appDelegate.reMainMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2349. appDelegate.reMainMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2350. appDelegate.reMainMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2351. appDelegate.reMainMenu.subtitleHighlightedTextShadowColor = nil;
  2352. appDelegate.reMainMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2353. appDelegate.reMainMenu.borderWidth = 0.3;
  2354. appDelegate.reMainMenu.borderColor = [UIColor lightGrayColor];
  2355. appDelegate.reMainMenu.animationDuration = 0.2;
  2356. appDelegate.reMainMenu.closeAnimationDuration = 0.2;
  2357. appDelegate.reMainMenu.bounce = NO;
  2358. [appDelegate.reMainMenu setClosePreparationBlock:^{
  2359. // Backgroun reMenu (Gesture)
  2360. [_reMenuBackgroundView removeFromSuperview];
  2361. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2362. }];
  2363. }
  2364. - (void)toggleReMainMenu
  2365. {
  2366. if (appDelegate.reMainMenu.isOpen) {
  2367. [appDelegate.reMainMenu close];
  2368. } else {
  2369. [self createReMainMenu];
  2370. [appDelegate.reMainMenu showFromNavigationController:self.navigationController];
  2371. // Backgroun reMenu & (Gesture)
  2372. [self createReMenuBackgroundView:appDelegate.reMainMenu];
  2373. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReMainMenu)];
  2374. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2375. }
  2376. }
  2377. - (void)createReSelectMenu
  2378. {
  2379. // ITEM DELETE ------------------------------------------------------------------------------------------------------
  2380. 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) {
  2381. [self deleteFile];
  2382. }];
  2383. // ITEM MOVE ------------------------------------------------------------------------------------------------------
  2384. 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) {
  2385. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2386. }];
  2387. // ITEM DOWNLOAD ----------------------------------------------------------------------------------------------------
  2388. 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) {
  2389. [self downloadSelectedFilesFolders];
  2390. }];
  2391. // ITEM SAVE IMAGE & VIDEO -------------------------------------------------------------------------------------------
  2392. 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) {
  2393. [self saveSelectedFiles];
  2394. }];
  2395. appDelegate.reSelectMenu = [[REMenu alloc] initWithItems:@[appDelegate.deleteItem,appDelegate.moveItem, appDelegate.downloadItem, appDelegate.saveItem]];
  2396. appDelegate.reSelectMenu.imageOffset = CGSizeMake(5, -1);
  2397. appDelegate.reSelectMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2398. appDelegate.reSelectMenu.imageOffset = CGSizeMake(0, 0);
  2399. appDelegate.reSelectMenu.waitUntilAnimationIsComplete = NO;
  2400. appDelegate.reSelectMenu.separatorHeight = 0.5;
  2401. appDelegate.reSelectMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2402. appDelegate.reSelectMenu.backgroundColor = [NCBrandColor sharedInstance].backgroundView;
  2403. appDelegate.reSelectMenu.textColor = [UIColor blackColor];
  2404. appDelegate.reSelectMenu.textAlignment = NSTextAlignmentLeft;
  2405. appDelegate.reSelectMenu.textShadowColor = nil;
  2406. appDelegate.reSelectMenu.textOffset = CGSizeMake(50, 0.0);
  2407. appDelegate.reSelectMenu.font = [UIFont systemFontOfSize:14.0];
  2408. appDelegate.reSelectMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2409. appDelegate.reSelectMenu.highlightedSeparatorColor = nil;
  2410. appDelegate.reSelectMenu.highlightedTextColor = [UIColor blackColor];
  2411. appDelegate.reSelectMenu.highlightedTextShadowColor = nil;
  2412. appDelegate.reSelectMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2413. appDelegate.reSelectMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1.000];
  2414. appDelegate.reSelectMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2415. appDelegate.reSelectMenu.subtitleTextShadowColor = nil;
  2416. appDelegate.reSelectMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2417. appDelegate.reSelectMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2418. appDelegate.reSelectMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2419. appDelegate.reSelectMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2420. appDelegate.reSelectMenu.subtitleHighlightedTextShadowColor = nil;
  2421. appDelegate.reSelectMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2422. appDelegate.reSelectMenu.borderWidth = 0.3;
  2423. appDelegate.reSelectMenu.borderColor = [UIColor lightGrayColor];
  2424. appDelegate.reSelectMenu.closeAnimationDuration = 0.2;
  2425. appDelegate.reSelectMenu.animationDuration = 0.2;
  2426. appDelegate.reSelectMenu.bounce = NO;
  2427. [appDelegate.reSelectMenu setClosePreparationBlock:^{
  2428. // Backgroun reMenu (Gesture)
  2429. [_reMenuBackgroundView removeFromSuperview];
  2430. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2431. }];
  2432. }
  2433. - (void)toggleReSelectMenu
  2434. {
  2435. if (appDelegate.reSelectMenu.isOpen) {
  2436. [appDelegate.reSelectMenu close];
  2437. } else {
  2438. [self createReSelectMenu];
  2439. [appDelegate.reSelectMenu showFromNavigationController:self.navigationController];
  2440. // Backgroun reMenu & (Gesture)
  2441. [self createReMenuBackgroundView:appDelegate.reSelectMenu];
  2442. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReSelectMenu)];
  2443. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2444. }
  2445. }
  2446. #pragma --------------------------------------------------------------------------------------------
  2447. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  2448. #pragma --------------------------------------------------------------------------------------------
  2449. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  2450. {
  2451. if (recognizer.state == UIGestureRecognizerStateBegan) {
  2452. UITableView *tableView = (UITableView*)self.view;
  2453. CGPoint touchPoint = [recognizer locationInView:self.view];
  2454. NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:touchPoint];
  2455. if ([self indexPathIsValid:indexPath])
  2456. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2457. else
  2458. _metadata = nil;
  2459. [self becomeFirstResponder];
  2460. UIMenuController *menuController = [UIMenuController sharedMenuController];
  2461. UIMenuItem *copyFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)];
  2462. UIMenuItem *copyFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)];
  2463. UIMenuItem *openinFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)];
  2464. UIMenuItem *pasteFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)];
  2465. UIMenuItem *pasteFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)];
  2466. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, nil]];
  2467. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:tableView];
  2468. [menuController setMenuVisible:YES animated:YES];
  2469. }
  2470. }
  2471. - (BOOL)canBecomeFirstResponder
  2472. {
  2473. return YES;
  2474. }
  2475. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  2476. {
  2477. // For copy file, copy files, Open in ... :
  2478. //
  2479. // NO Directory
  2480. // NO Error Passcode
  2481. // NO In Session mode (download/upload)
  2482. // NO Template
  2483. if (@selector(copyFile:) == action || @selector(openinFile:) == action) {
  2484. if (_isSelectedMode == NO && _metadata && !_metadata.directory && [_metadata.session length] == 0) return YES;
  2485. else return NO;
  2486. }
  2487. if (@selector(copyFiles:) == action) {
  2488. if (_isSelectedMode) {
  2489. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2490. for (tableMetadata *metadata in selectedMetadatas) {
  2491. if (!metadata.directory && metadata.session.length == 0)
  2492. return YES;
  2493. }
  2494. }
  2495. return NO;
  2496. }
  2497. if (@selector(pasteFile:) == action) {
  2498. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2499. NSArray *items = [pasteboard items];
  2500. if ([items count] == 1) {
  2501. // Value : (NSData) fileID
  2502. NSDictionary *dic = [items objectAtIndex:0];
  2503. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2504. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2505. if (fileID) {
  2506. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2507. if (metadata) {
  2508. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", metadata.account]];
  2509. if (account) {
  2510. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2511. if (directoryUser)
  2512. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]])
  2513. return YES;
  2514. }
  2515. }
  2516. }
  2517. }
  2518. return NO;
  2519. }
  2520. if (@selector(pasteFiles:) == action) {
  2521. BOOL isValid = NO;
  2522. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2523. NSArray *items = [pasteboard items];
  2524. if ([items count] <= 1) return NO;
  2525. for (NSDictionary *dic in items) {
  2526. // Value : (NSData) fileID
  2527. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2528. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2529. if (fileID) {
  2530. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2531. if (metadata) {
  2532. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", metadata.account]];
  2533. if (account) {
  2534. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2535. if (directoryUser) {
  2536. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]]) {
  2537. isValid = YES;
  2538. } else {
  2539. isValid = NO;
  2540. break;
  2541. }
  2542. } else {
  2543. isValid = NO;
  2544. break;
  2545. }
  2546. } else {
  2547. isValid = NO;
  2548. break;
  2549. }
  2550. } else {
  2551. isValid = NO;
  2552. break;
  2553. }
  2554. } else {
  2555. isValid = NO;
  2556. break;
  2557. }
  2558. }
  2559. return isValid;
  2560. }
  2561. return NO;
  2562. }
  2563. /************************************ COPY ************************************/
  2564. - (void)copyFile:(id)sender
  2565. {
  2566. // Remove all item
  2567. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2568. pasteboard.items = [[NSArray alloc] init];
  2569. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser,_metadata.fileID]]) {
  2570. [self copyFileToPasteboard:_metadata];
  2571. } else {
  2572. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2573. if (serverUrl)
  2574. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileName fileID:_metadata.fileID serverUrl:serverUrl selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2575. }
  2576. }
  2577. - (void)copyFiles:(id)sender
  2578. {
  2579. // Remove all item
  2580. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2581. pasteboard.items = [[NSArray alloc] init];
  2582. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2583. for (tableMetadata *metadata in selectedMetadatas) {
  2584. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadata.fileID]]) {
  2585. [self copyFileToPasteboard:metadata];
  2586. } else {
  2587. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2588. if (serverUrl)
  2589. [[CCNetworking sharedNetworking] downloadFile:metadata.fileName fileID:metadata.fileID serverUrl:serverUrl selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2590. }
  2591. }
  2592. [self tableViewSelect:NO];
  2593. }
  2594. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  2595. {
  2596. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2597. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  2598. // Value : (NSData) fileID
  2599. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata.fileID], k_metadataKeyedUnarchiver,nil];
  2600. [items addObject:item];
  2601. [pasteboard setItems:items];
  2602. }
  2603. /************************************ OPEN IN ... ******************************/
  2604. - (void)openinFile:(id)sender
  2605. {
  2606. [self openIn:_metadata];
  2607. }
  2608. /************************************ PASTE ************************************/
  2609. - (void)pasteFile:(id)sender
  2610. {
  2611. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2612. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2613. }
  2614. - (void)pasteFiles:(id)sender
  2615. {
  2616. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2617. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2618. }
  2619. - (void)uploadFilePasteArray:(NSArray *)items cryptated:(BOOL)cryptated
  2620. {
  2621. float timer = 0;
  2622. for (NSDictionary *dic in items) {
  2623. // Value : (NSData) fileID
  2624. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2625. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2626. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2627. if (metadata) {
  2628. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", metadata.account]];
  2629. if (account) {
  2630. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2631. if (directoryUser) {
  2632. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]]) {
  2633. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadata.fileNameView]];
  2634. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timer * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2635. [[CCNetworking sharedNetworking] uploadFile:metadata.fileNameView serverUrl:_serverUrl session:k_upload_session taskStatus:k_taskStatusResume selector:@"" selectorPost:@"" errorCode:0 delegate:nil];
  2636. });
  2637. timer += 0.1;
  2638. }
  2639. }
  2640. }
  2641. }
  2642. }
  2643. }
  2644. #pragma --------------------------------------------------------------------------------------------
  2645. #pragma mark ===== Lock Passcode =====
  2646. #pragma --------------------------------------------------------------------------------------------
  2647. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  2648. {
  2649. return _failedAttempts;
  2650. }
  2651. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  2652. {
  2653. return _lockUntilDate;
  2654. }
  2655. - (void)passcodeViewCloseButtonPressed:(id)sender
  2656. {
  2657. [self dismissViewControllerAnimated:YES completion:nil];
  2658. }
  2659. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  2660. {
  2661. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  2662. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  2663. _lockUntilDate = nil;
  2664. _failedAttempts = 0;
  2665. aResultHandler(YES);
  2666. } else aResultHandler(NO);
  2667. } else aResultHandler(YES);
  2668. }
  2669. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  2670. {
  2671. [aViewController dismissViewControllerAnimated:YES completion:nil];
  2672. switch (aViewController.type) {
  2673. case BKPasscodeViewControllerCheckPasscodeType: {
  2674. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  2675. // possiamo procedere alla prossima directory
  2676. [self performSegueDirectoryWithControlPasscode:false];
  2677. // avviamo la sessione Passcode Lock con now
  2678. appDelegate.sessionePasscodeLock = [NSDate date];
  2679. }
  2680. // disattivazione lock cartella
  2681. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  2682. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2683. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2684. if (![[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:NO]) {
  2685. [appDelegate messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2686. }
  2687. [self tableViewReloadData];
  2688. }
  2689. }
  2690. break;
  2691. default:
  2692. break;
  2693. }
  2694. }
  2695. - (void)comandoLockPassword
  2696. {
  2697. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2698. if (!serverUrl) return;
  2699. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2700. // se non è abilitato il Lock Passcode esci
  2701. if ([[CCUtility getBlockCode] length] == 0) {
  2702. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) preferredStyle:UIAlertControllerStyleAlert];
  2703. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  2704. [alertController addAction:okAction];
  2705. [self presentViewController:alertController animated:YES completion:nil];
  2706. return;
  2707. }
  2708. // se è richiesta la disattivazione si chiede la password
  2709. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, lockServerUrl]];
  2710. if (directory.lock) {
  2711. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2712. viewController.delegate = self;
  2713. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  2714. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2715. viewController.inputViewTitlePassword = YES;
  2716. if ([CCUtility getSimplyBlockCode]) {
  2717. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2718. viewController.passcodeInputView.maximumLength = 6;
  2719. } else {
  2720. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2721. viewController.passcodeInputView.maximumLength = 64;
  2722. }
  2723. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  2724. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2725. viewController.touchIDManager = touchIDManager;
  2726. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  2727. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2728. viewController.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
  2729. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2730. [self presentViewController:navigationController animated:YES completion:nil];
  2731. return;
  2732. }
  2733. // ---------------- ACTIVATE PASSWORD
  2734. if ([[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:YES]) {
  2735. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  2736. if ([self indexPathIsValid:indexPath])
  2737. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2738. } else {
  2739. [appDelegate messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2740. }
  2741. }
  2742. #pragma mark -
  2743. #pragma --------------------------------------------------------------------------------------------
  2744. #pragma mark ===== Swipe Tablet -> menu =====
  2745. #pragma --------------------------------------------------------------------------------------------
  2746. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell canSwipe:(MGSwipeDirection)direction
  2747. {
  2748. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2749. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2750. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  2751. return NO;
  2752. if (metadata == nil || metadata.sessionTaskIdentifier != k_taskIdentifierDone)
  2753. return NO;
  2754. else
  2755. return YES;
  2756. }
  2757. -(void)swipeTableCell:(nonnull MGSwipeTableCell *)cell didChangeSwipeState:(MGSwipeState)state gestureIsActive:(BOOL)gestureIsActive
  2758. {
  2759. }
  2760. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell tappedButtonAtIndex:(NSInteger)index direction:(MGSwipeDirection)direction fromExpansion:(BOOL)fromExpansion
  2761. {
  2762. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2763. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2764. if (direction == MGSwipeDirectionRightToLeft) {
  2765. // Delete
  2766. if (index == 0)
  2767. [self swipeDelete:indexPath];
  2768. // More
  2769. if (index == 1)
  2770. [self swipeMore:indexPath];
  2771. }
  2772. if (direction == MGSwipeDirectionLeftToRight) {
  2773. if (_metadata.favorite)
  2774. [self removeFavorite:_metadata];
  2775. else
  2776. [self addFavorite:_metadata];
  2777. }
  2778. return YES;
  2779. }
  2780. - (void)swipeDelete:(NSIndexPath *)indexPath
  2781. {
  2782. // Directory locked ?
  2783. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:[[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID] addFileName:_metadata.fileName];
  2784. if (!lockServerUrl) return;
  2785. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, lockServerUrl]];
  2786. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil) {
  2787. [appDelegate messageNotification:@"_error_" description:@"_folder_blocked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2788. return;
  2789. }
  2790. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  2791. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  2792. [self performSelector:@selector(deleteFile) withObject:nil];
  2793. }]];
  2794. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2795. [alertController dismissViewControllerAnimated:YES completion:nil];
  2796. }]];
  2797. alertController.popoverPresentationController.sourceView = self.view;
  2798. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  2799. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  2800. [alertController.view layoutIfNeeded];
  2801. [self presentViewController:alertController animated:YES completion:nil];
  2802. }
  2803. - (void)swipeMore:(NSIndexPath *)indexPath
  2804. {
  2805. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2806. if (!serverUrl) return;
  2807. NSString *titoloLock, *titleFavorite;
  2808. if (_metadata.favorite) {
  2809. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_remove_favorites_", nil)];
  2810. } else {
  2811. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_add_favorites_", nil)];
  2812. }
  2813. if (_metadata.directory) {
  2814. // calcolo lockServerUrl
  2815. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2816. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, lockServerUrl]];
  2817. if (directory.lock)
  2818. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_remove_passcode_", nil)];
  2819. else
  2820. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_protect_passcode_", nil)];
  2821. }
  2822. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", _metadata.fileID]];
  2823. // ******************************************* AHKActionSheet *******************************************
  2824. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.tabBarController.view title:nil];
  2825. actionSheet.animationDuration = 0.2;
  2826. actionSheet.buttonHeight = 50.0;
  2827. actionSheet.cancelButtonHeight = 50.0f;
  2828. actionSheet.separatorHeight = 5.0f;
  2829. actionSheet.automaticallyTintButtonImages = @(NO);
  2830. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].encrypted };
  2831. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  2832. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont boldSystemFontOfSize:17], NSForegroundColorAttributeName:[UIColor blackColor] };
  2833. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor darkGrayColor] };
  2834. actionSheet.separatorColor = [NCBrandColor sharedInstance].seperator;
  2835. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  2836. // ******************************************* DIRECTORY *******************************************
  2837. if (_metadata.directory) {
  2838. BOOL lockDirectory = NO;
  2839. NSString *dirServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2840. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:[NSString stringWithFormat:@"%@/%@", self.serverUrl, _metadata.fileName] account:appDelegate.activeAccount];
  2841. // Directory bloccata ?
  2842. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, dirServerUrl]];
  2843. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil) lockDirectory = YES;
  2844. [actionSheet addButtonWithTitle:_metadata.fileNameView
  2845. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder"] color:[NCBrandColor sharedInstance].brand]
  2846. backgroundColor:[NCBrandColor sharedInstance].tabBar
  2847. height:50.0
  2848. type:AHKActionSheetButtonTypeDisabled
  2849. handler:nil
  2850. ];
  2851. if (!lockDirectory && !isFolderEncrypted) {
  2852. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  2853. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand]
  2854. backgroundColor:[UIColor whiteColor]
  2855. height:50.0
  2856. type:AHKActionSheetButtonTypeDefault
  2857. handler:^(AHKActionSheet *as) {
  2858. [self openWindowShare:_metadata];
  2859. }];
  2860. }
  2861. if (!([_metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES) && !lockDirectory && !_metadata.e2eEncrypted) {
  2862. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  2863. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  2864. backgroundColor:[UIColor whiteColor]
  2865. height:50.0
  2866. type:AHKActionSheetButtonTypeDefault
  2867. handler:^(AHKActionSheet *as) {
  2868. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  2869. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  2870. textField.text = _metadata.fileNameView;
  2871. //textField.selectedTextRange = [textField textRangeFromPosition:textField.beginningOfDocument toPosition:textField.endOfDocument];
  2872. //textField.delegate = self;
  2873. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  2874. }];
  2875. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2876. NSLog(@"[LOG] Cancel action");
  2877. }];
  2878. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  2879. UITextField *fileName = alertController.textFields.firstObject;
  2880. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  2881. }];
  2882. okAction.enabled = NO;
  2883. [alertController addAction:cancelAction];
  2884. [alertController addAction:okAction];
  2885. [self presentViewController:alertController animated:YES completion:nil];
  2886. }];
  2887. }
  2888. if (!([_metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES) && !lockDirectory && !isFolderEncrypted) {
  2889. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  2890. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  2891. backgroundColor:[UIColor whiteColor]
  2892. height:50.0
  2893. type:AHKActionSheetButtonTypeDefault
  2894. handler:^(AHKActionSheet *as) {
  2895. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  2896. }];
  2897. }
  2898. if (!([_metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES) && !isFolderEncrypted) {
  2899. [actionSheet addButtonWithTitle:NSLocalizedString(@"_folder_automatic_upload_", nil)
  2900. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderphotocamera"] color:[NCBrandColor sharedInstance].brand]
  2901. backgroundColor:[UIColor whiteColor]
  2902. height:50.0
  2903. type:AHKActionSheetButtonTypeDefault
  2904. handler:^(AHKActionSheet *as) {
  2905. // Settings new folder Automatatic upload
  2906. [[NCManageDatabase sharedInstance] setAccountAutoUploadFileName:_metadata.fileName];
  2907. [[NCManageDatabase sharedInstance] setAccountAutoUploadDirectory:serverUrl activeUrl:appDelegate.activeUrl];
  2908. // Clear data (old) Auto Upload
  2909. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:_autoUploadDirectory directoryID:nil];
  2910. if (appDelegate.activeAccount.length > 0 && appDelegate.activePhotos)
  2911. [appDelegate.activePhotos reloadDatasourceForced];
  2912. [self readFolder:serverUrl];
  2913. NSLog(@"[LOG] Update Folder Photo");
  2914. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:appDelegate.activeUrl];
  2915. if ([autoUploadPath length] > 0) {
  2916. [[CCSynchronize sharedSynchronize] readFileForFolder:_metadata.fileName serverUrl:serverUrl selector:selectorReadFileFolder];
  2917. }
  2918. }];
  2919. }
  2920. if (!([_metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES)) {
  2921. [actionSheet addButtonWithTitle:titoloLock
  2922. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"settingsPasscodeYES"] color:[NCBrandColor sharedInstance].brand]
  2923. backgroundColor:[UIColor whiteColor]
  2924. height:50.0
  2925. type:AHKActionSheetButtonTypeDefault
  2926. handler:^(AHKActionSheet *as) {
  2927. [self performSelector:@selector(comandoLockPassword) withObject:nil];
  2928. }];
  2929. }
  2930. if ([CCUtility isEndToEndEnabled:appDelegate.activeAccount] && !_metadata.e2eEncrypted && !([_metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES)) {
  2931. [actionSheet addButtonWithTitle:NSLocalizedString(@"_e2e_set_folder_encrypted_", nil)
  2932. image:[UIImage imageNamed:@"encrypted_empty"]
  2933. backgroundColor:[UIColor whiteColor]
  2934. height:50.0
  2935. type:AHKActionSheetButtonTypeEncrypted
  2936. handler:^(AHKActionSheet *as) {
  2937. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  2938. if ([appDelegate.endToEndInterface markEndToEndFolderEncrypted:appDelegate.activeUrl fileID:_metadata.fileID serverUrl:[NSString stringWithFormat:@"%@/%@", self.serverUrl, _metadata.fileName]]) {
  2939. dispatch_async(dispatch_get_main_queue(), ^{
  2940. [self readFolder:self.serverUrl];
  2941. });
  2942. }
  2943. });
  2944. }];
  2945. }
  2946. if ([CCUtility isEndToEndEnabled:appDelegate.activeAccount] && _metadata.e2eEncrypted) {
  2947. [actionSheet addButtonWithTitle:NSLocalizedString(@"_e2e_remove_folder_encrypted_", nil)
  2948. image:[UIImage imageNamed:@"encrypted_empty"]
  2949. backgroundColor:[UIColor whiteColor]
  2950. height:50.0
  2951. type:AHKActionSheetButtonTypeEncrypted
  2952. handler:^(AHKActionSheet *as) {
  2953. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  2954. if ([appDelegate.endToEndInterface deletemarkEndToEndFolderEncrypted:appDelegate.activeUrl fileID:_metadata.fileID serverUrl:[NSString stringWithFormat:@"%@/%@", self.serverUrl, _metadata.fileName]]) {
  2955. dispatch_async(dispatch_get_main_queue(), ^{
  2956. [self readFolder:self.serverUrl];
  2957. });
  2958. }
  2959. });
  2960. }];
  2961. }
  2962. [actionSheet show];
  2963. }
  2964. // ******************************************* FILE *******************************************
  2965. if (!_metadata.directory) {
  2966. UIImage *iconHeader;
  2967. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:self.serverUrl account:appDelegate.activeAccount];
  2968. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  2969. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, _metadata.fileID]])
  2970. iconHeader = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, _metadata.fileID]];
  2971. else
  2972. iconHeader = [UIImage imageNamed:_metadata.iconName];
  2973. [actionSheet addButtonWithTitle: _metadata.fileNameView
  2974. image: iconHeader
  2975. backgroundColor: [NCBrandColor sharedInstance].tabBar
  2976. height: 50.0
  2977. type: AHKActionSheetButtonTypeDisabled
  2978. handler: nil
  2979. ];
  2980. if (!isFolderEncrypted) {
  2981. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  2982. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"]color:[NCBrandColor sharedInstance].brand]
  2983. backgroundColor:[UIColor whiteColor]
  2984. height: 50.0
  2985. type:AHKActionSheetButtonTypeDefault
  2986. handler:^(AHKActionSheet *as) {
  2987. [self openWindowShare:_metadata];
  2988. }];
  2989. }
  2990. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil)
  2991. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetOpenIn"] color:[NCBrandColor sharedInstance].brand]
  2992. backgroundColor:[UIColor whiteColor]
  2993. height: 50.0
  2994. type:AHKActionSheetButtonTypeDefault
  2995. handler:^(AHKActionSheet *as) {
  2996. [self performSelector:@selector(openIn:) withObject:_metadata];
  2997. }];
  2998. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  2999. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  3000. backgroundColor:[UIColor whiteColor]
  3001. height: 50.0
  3002. type:AHKActionSheetButtonTypeDefault
  3003. handler:^(AHKActionSheet *as) {
  3004. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  3005. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  3006. textField.text = _metadata.fileNameView;
  3007. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  3008. }];
  3009. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  3010. NSLog(@"[LOG] Cancel action");
  3011. }];
  3012. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  3013. UITextField *fileName = alertController.textFields.firstObject;
  3014. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  3015. }];
  3016. okAction.enabled = NO;
  3017. [alertController addAction:cancelAction];
  3018. [alertController addAction:okAction];
  3019. [self presentViewController:alertController animated:YES completion:nil];
  3020. }];
  3021. if (!isFolderEncrypted) {
  3022. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3023. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  3024. backgroundColor:[UIColor whiteColor]
  3025. height: 50.0
  3026. type:AHKActionSheetButtonTypeDefault
  3027. handler:^(AHKActionSheet *as) {
  3028. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3029. }];
  3030. }
  3031. if (localFile || [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, _metadata.fileID]]) {
  3032. [actionSheet addButtonWithTitle:NSLocalizedString(@"_remove_local_file_", nil)
  3033. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRemoveLocal"] color:[NCBrandColor sharedInstance].brand]
  3034. backgroundColor:[UIColor whiteColor]
  3035. height: 50.0
  3036. type:AHKActionSheetButtonTypeDefault
  3037. handler:^(AHKActionSheet *as) {
  3038. [self performSelector:@selector(removeLocalFile:) withObject:_metadata];
  3039. }];
  3040. }
  3041. [actionSheet show];
  3042. }
  3043. }
  3044. #pragma --------------------------------------------------------------------------------------------
  3045. #pragma mark - ==== Datasource ====
  3046. #pragma --------------------------------------------------------------------------------------------
  3047. - (void)clearDateReadDataSource:(NSNotification *)notification
  3048. {
  3049. _dateReadDataSource = Nil;
  3050. [self reloadDatasource];
  3051. }
  3052. - (void)reloadDatasource
  3053. {
  3054. [self reloadDatasource:_serverUrl];
  3055. }
  3056. - (void)reloadDatasource:(NSString *)serverUrl
  3057. {
  3058. // test
  3059. if (appDelegate.activeAccount.length == 0 || serverUrl.length == 0 || serverUrl == nil)
  3060. return;
  3061. // Search Mode
  3062. if (_isSearchMode) {
  3063. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:_searchResultMetadatas listProgressMetadata:nil e2eEncryptions:nil groupByField:_directoryGroupBy activeAccount:appDelegate.activeAccount];
  3064. [self tableViewReloadData];
  3065. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  3066. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  3067. _noFilesSearchDescription = @"";
  3068. }
  3069. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  3070. _noFilesSearchTitle = @"";
  3071. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  3072. }
  3073. [self.tableView reloadEmptyDataSet];
  3074. return;
  3075. }
  3076. // Reload -> Self se non siamo nella dir appropriata cercala e se è in memoria reindirizza il reload
  3077. if ([serverUrl isEqualToString:_serverUrl] == NO || _serverUrl == nil) {
  3078. CCMain *main = [appDelegate.listMainVC objectForKey:serverUrl];
  3079. if (main) {
  3080. [main reloadDatasource];
  3081. } else {
  3082. [self tableViewReloadData];
  3083. [appDelegate.activeTransfers reloadDatasource];
  3084. }
  3085. return;
  3086. }
  3087. [appDelegate.activeTransfers reloadDatasource];
  3088. // Settaggio variabili per le ottimizzazioni
  3089. _directoryGroupBy = [CCUtility getGroupBySettings];
  3090. _directoryOrder = [CCUtility getOrderSettings];
  3091. // Remove optimization for encrypted directory
  3092. if ([CCUtility isFolderEncrypted:self.serverUrl account:appDelegate.activeAccount])
  3093. _dateReadDataSource = nil;
  3094. // current directoryID
  3095. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  3096. // Controllo data lettura Data Source
  3097. tableDirectory *tableDirectory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, serverUrl]];
  3098. // Get MetadataFolder
  3099. _metadataFolder = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND fileID = %@", appDelegate.activeAccount, tableDirectory.fileID]];
  3100. NSDate *dateDateRecordDirectory = tableDirectory.dateReadDirectory;
  3101. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  3102. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  3103. _dateReadDataSource = [NSDate date];
  3104. // Data Source
  3105. NSString *sorted = _directoryOrder;
  3106. if ([sorted isEqualToString:@"fileName"])
  3107. sorted = @"fileName";
  3108. if (directoryID) {
  3109. NSArray *recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND status = %i", appDelegate.activeAccount, directoryID, k_metadataStatusNormal] sorted:sorted ascending:[CCUtility getAscendingSettings]];
  3110. NSArray *recordsTableE2eEncryption = [[NCManageDatabase sharedInstance] getE2eEncryptionsWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, serverUrl]];
  3111. _sectionDataSource = [CCSectionDataSourceMetadata new];
  3112. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil e2eEncryptions:recordsTableE2eEncryption groupByField:_directoryGroupBy activeAccount:appDelegate.activeAccount];
  3113. // get auto upload folder
  3114. _autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  3115. _autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:appDelegate.activeUrl];
  3116. }
  3117. } else {
  3118. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  3119. }
  3120. [self tableViewReloadData];
  3121. }
  3122. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  3123. {
  3124. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  3125. if (selectedRows.count > 0) {
  3126. for (NSIndexPath *selectionIndex in selectedRows) {
  3127. NSString *fileID = [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  3128. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3129. [metadatas addObject:metadata];
  3130. }
  3131. }
  3132. return metadatas;
  3133. }
  3134. - (tableMetadata *)getMetadataFromSectionDataSource:(NSIndexPath *)indexPath
  3135. {
  3136. NSInteger section = indexPath.section + 1;
  3137. NSInteger row = indexPath.row + 1;
  3138. NSInteger totSections = [_sectionDataSource.sections count] ;
  3139. if ((totSections < section) || (section > totSections)) {
  3140. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [0] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section]);
  3141. return nil;
  3142. }
  3143. id valueSection = [_sectionDataSource.sections objectAtIndex:indexPath.section];
  3144. NSArray *fileIDs = [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3145. if (fileIDs) {
  3146. NSInteger totRows =[fileIDs count] ;
  3147. if ((totRows < row) || (row > totRows)) {
  3148. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [1] : error row, totRows = %lu - row = %lu", (long)totRows, (long)row]);
  3149. return nil;
  3150. }
  3151. } else {
  3152. NSLog(@"[LOG] DEBUG [2] : fileIDs is NIL");
  3153. return nil;
  3154. }
  3155. NSString *fileID = [fileIDs objectAtIndex:indexPath.row];
  3156. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3157. return metadata;
  3158. }
  3159. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  3160. {
  3161. NSInteger totSections =[_sectionDataSource.sections count] ;
  3162. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  3163. return nil;
  3164. }
  3165. id valueSection = [_sectionDataSource.sections objectAtIndex:section];
  3166. return [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3167. }
  3168. #pragma --------------------------------------------------------------------------------------------
  3169. #pragma mark - ==== Table ====
  3170. #pragma --------------------------------------------------------------------------------------------
  3171. - (void)tableViewSelect:(BOOL)edit
  3172. {
  3173. // chiudiamo eventuali swipe aperti
  3174. if (edit)
  3175. [self.tableView setEditing:NO animated:NO];
  3176. [self.tableView setAllowsMultipleSelectionDuringEditing:edit];
  3177. [self.tableView setEditing:edit animated:YES];
  3178. _isSelectedMode = edit;
  3179. if (edit)
  3180. [self setUINavigationBarSelected];
  3181. else
  3182. [self setUINavigationBarDefault];
  3183. [_selectedFileIDsMetadatas removeAllObjects];
  3184. [self setTitle];
  3185. }
  3186. - (void)tableViewReloadData
  3187. {
  3188. // store selected cells before relod
  3189. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  3190. //store swipeOffset before relod
  3191. [_statusSwipeCell removeAllObjects];
  3192. for (MGSwipeTableCell *cell in self.tableView.visibleCells) {
  3193. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  3194. [_statusSwipeCell setObject:[NSNumber numberWithDouble:cell.swipeOffset] forKey:indexPath];
  3195. }
  3196. // reload table view
  3197. [self.tableView reloadData];
  3198. // selected cells stored
  3199. for (NSIndexPath *path in indexPaths)
  3200. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  3201. [self setTableViewFooter];
  3202. if (self.tableView.editing)
  3203. [self setTitle];
  3204. }
  3205. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  3206. {
  3207. if (tableView.editing == 1) {
  3208. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3209. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  3210. return NO;
  3211. if (metadata == nil || metadata.sessionTaskIdentifier != k_taskIdentifierDone)
  3212. return NO;
  3213. else
  3214. return YES;
  3215. } else {
  3216. [_selectedFileIDsMetadatas removeAllObjects];
  3217. }
  3218. return YES;
  3219. }
  3220. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  3221. {
  3222. return 60;
  3223. }
  3224. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  3225. {
  3226. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  3227. }
  3228. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  3229. {
  3230. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  3231. }
  3232. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  3233. {
  3234. NSArray *sections = [_sectionDataSource.sectionArrayRow allKeys];
  3235. NSString *sectionTitle = [sections objectAtIndex:section];
  3236. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  3237. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  3238. if ([_directoryGroupBy isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  3239. return 20.f;
  3240. }
  3241. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  3242. {
  3243. float shift;
  3244. UIVisualEffectView *visualEffectView;
  3245. NSString *titleSection;
  3246. if (![self indexPathIsValid:[NSIndexPath indexPathForRow:0 inSection:section]])
  3247. return nil;
  3248. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]])
  3249. titleSection = [_sectionDataSource.sections objectAtIndex:section];
  3250. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]])
  3251. titleSection = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:section]];
  3252. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  3253. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  3254. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  3255. else titleSection = NSLocalizedString(titleSection,nil);
  3256. // Format title
  3257. NSString *currentDevice = [CCUtility currentDevice];
  3258. if ([currentDevice rangeOfString:@"iPad3"].location != NSNotFound) {
  3259. visualEffectView = [[UIVisualEffectView alloc] init];
  3260. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.3];
  3261. } else {
  3262. UIVisualEffect *blurEffect;
  3263. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  3264. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  3265. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.2];
  3266. }
  3267. if ([_directoryGroupBy isEqualToString:@"alphabetic"]) {
  3268. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  3269. shift = - 35;
  3270. else
  3271. shift = - 20;
  3272. } else shift = - 10;
  3273. // Title
  3274. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  3275. titleLabel.backgroundColor = [UIColor clearColor];
  3276. titleLabel.textColor = [UIColor blackColor];
  3277. titleLabel.font = [UIFont systemFontOfSize:12];
  3278. titleLabel.textAlignment = NSTextAlignmentLeft;
  3279. titleLabel.text = titleSection;
  3280. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3281. [visualEffectView.contentView addSubview:titleLabel];
  3282. // Elements
  3283. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  3284. elementLabel.backgroundColor = [UIColor clearColor];
  3285. elementLabel.textColor = [UIColor blackColor];;
  3286. elementLabel.font = [UIFont systemFontOfSize:12];
  3287. elementLabel.textAlignment = NSTextAlignmentRight;
  3288. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3289. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  3290. NSUInteger rowsCount = [metadatas count];
  3291. if (rowsCount == 0) return nil;
  3292. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  3293. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  3294. [visualEffectView.contentView addSubview:elementLabel];
  3295. return visualEffectView;
  3296. }
  3297. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  3298. {
  3299. return [_sectionDataSource.sections indexOfObject:title];
  3300. }
  3301. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  3302. {
  3303. if ([_directoryGroupBy isEqualToString:@"alphabetic"])
  3304. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  3305. else
  3306. return nil;
  3307. }
  3308. /*
  3309. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  3310. {
  3311. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  3312. }
  3313. }
  3314. */
  3315. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  3316. {
  3317. NSString *typeCell;
  3318. NSString *dataFile;
  3319. NSString *lunghezzaFile;
  3320. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3321. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  3322. return [tableView dequeueReusableCellWithIdentifier:@"CellMain"];
  3323. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  3324. if (!serverUrl)
  3325. return [tableView dequeueReusableCellWithIdentifier:@"CellMain"];
  3326. if ([metadata.session isEqualToString:@""] || metadata.session == nil) typeCell = @"CellMain";
  3327. else typeCell = @"CellMainTransfer";
  3328. CCCellMainTransfer *cell = (CCCellMainTransfer *)[tableView dequeueReusableCellWithIdentifier:typeCell forIndexPath:indexPath];
  3329. // variable base
  3330. cell.delegate = self;
  3331. cell.indexPath = indexPath;
  3332. // separator
  3333. cell.separatorInset = UIEdgeInsetsMake(0.f, 60.f, 0.f, 0.f);
  3334. // change color selection
  3335. UIView *selectionColor = [[UIView alloc] init];
  3336. selectionColor.backgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  3337. cell.selectedBackgroundView = selectionColor;
  3338. if ([typeCell isEqualToString:@"CellMain"]) cell.backgroundColor = [UIColor whiteColor];
  3339. if ([typeCell isEqualToString:@"CellMainTransfer"]) cell.backgroundColor = [NCBrandColor sharedInstance].transferBackground;
  3340. // ----------------------------------------------------------------------------------------------------------
  3341. // DEFAULT
  3342. // ----------------------------------------------------------------------------------------------------------
  3343. cell.file.image = nil;
  3344. cell.status.image = nil;
  3345. cell.favorite.image = nil;
  3346. cell.shared.image = nil;
  3347. cell.local.image = nil;
  3348. cell.labelTitle.enabled = YES;
  3349. cell.labelTitle.text = @"";
  3350. cell.labelInfoFile.enabled = YES;
  3351. cell.labelInfoFile.text = @"";
  3352. cell.progressView.progress = 0.0;
  3353. cell.progressView.hidden = YES;
  3354. cell.cancelTaskButton.hidden = YES;
  3355. cell.reloadTaskButton.hidden = YES;
  3356. cell.stopTaskButton.hidden = YES;
  3357. cell.labelTitle.textColor = [UIColor blackColor];
  3358. // ----------------------------------------------------------------------------------------------------------
  3359. // File Name & Folder
  3360. // ----------------------------------------------------------------------------------------------------------
  3361. // nome del file
  3362. cell.labelTitle.text = metadata.fileNameView;
  3363. // è una directory
  3364. if (metadata.directory) {
  3365. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  3366. cell.labelInfoFile.text = [CCUtility dateDiff:metadata.date];
  3367. lunghezzaFile = @" ";
  3368. // ----------------------------------------------------------------------------------------------------------
  3369. // Favorite Folder
  3370. // ----------------------------------------------------------------------------------------------------------
  3371. if (metadata.favorite) {
  3372. cell.favorite.image = [UIImage imageNamed:@"favorite"];
  3373. }
  3374. } else {
  3375. // File
  3376. dataFile = [CCUtility dateDiff:metadata.date];
  3377. lunghezzaFile = [CCUtility transformedSize:metadata.size];
  3378. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  3379. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  3380. [dateFormatter setDateStyle:NSDateFormatterShortStyle];
  3381. [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
  3382. if (localFile && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadata.fileID]])
  3383. cell.local.image = [UIImage imageNamed:@"local"];
  3384. else
  3385. cell.local.image = nil;
  3386. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ %@", dataFile, lunghezzaFile];
  3387. cell.accessoryType = UITableViewCellAccessoryNone;
  3388. }
  3389. // ----------------------------------------------------------------------------------------------------------
  3390. // File Image View
  3391. // ----------------------------------------------------------------------------------------------------------
  3392. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3393. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, metadata.fileID]]) {
  3394. cell.file.image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, metadata.fileID]];
  3395. } else {
  3396. if (metadata.directory) {
  3397. if (metadata.e2eEncrypted)
  3398. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderEncrypted"] color:[NCBrandColor sharedInstance].brand];
  3399. else if ([metadata.fileName isEqualToString:_autoUploadFileName] && [self.serverUrl isEqualToString:_autoUploadDirectory])
  3400. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderphotocamera"] color:[NCBrandColor sharedInstance].brand];
  3401. else
  3402. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder"] color:[NCBrandColor sharedInstance].brand];
  3403. } else {
  3404. cell.file.image = [UIImage imageNamed:metadata.iconName];
  3405. }
  3406. if (metadata.thumbnailExists && _metadataFolder.e2eEncrypted == NO)
  3407. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  3408. }
  3409. // ----------------------------------------------------------------------------------------------------------
  3410. // Image Status Lock Passcode
  3411. // ----------------------------------------------------------------------------------------------------------
  3412. // Directory con passcode lock attivato
  3413. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName];
  3414. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, lockServerUrl]];
  3415. if (metadata.directory && (directory.lock && [[CCUtility getBlockCode] length]))
  3416. cell.status.image = [UIImage imageNamed:@"passcode"];
  3417. // ----------------------------------------------------------------------------------------------------------
  3418. // E2E Image Status Encrypted
  3419. // ----------------------------------------------------------------------------------------------------------
  3420. if (_metadataFolder.e2eEncrypted && !metadata.directory) {
  3421. tableE2eEncryption *tableE2eEncryption = [[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND fileNameIdentifier = %@", appDelegate.activeAccount, metadata.fileName]];
  3422. if (tableE2eEncryption)
  3423. cell.status.image = [UIImage imageNamed:@"encrypted"];
  3424. }
  3425. // ----------------------------------------------------------------------------------------------------------
  3426. // Favorite
  3427. // ----------------------------------------------------------------------------------------------------------
  3428. if (metadata.favorite) {
  3429. cell.favorite.image = [UIImage imageNamed:@"favorite"];
  3430. }
  3431. // ----------------------------------------------------------------------------------------------------------
  3432. // Share
  3433. // ----------------------------------------------------------------------------------------------------------
  3434. NSString *shareLink = [appDelegate.sharesLink objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3435. NSString *shareUserAndGroup = [appDelegate.sharesUserAndGroup objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3436. BOOL isShare = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_shared].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_shared].location == NSNotFound);
  3437. BOOL isMounted = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_mounted].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_mounted].location == NSNotFound);
  3438. // Aggiungiamo il Tap per le shared
  3439. if (isShare || [shareLink length] > 0 || [shareUserAndGroup length] > 0 || isMounted) {
  3440. // Shared with you
  3441. if (isShare) {
  3442. if (metadata.directory) {
  3443. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3444. cell.accessoryType = UITableViewCellAccessoryNone;
  3445. }
  3446. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3447. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3448. [tap setNumberOfTapsRequired:1];
  3449. cell.shared.userInteractionEnabled = YES;
  3450. [cell.shared addGestureRecognizer:tap];
  3451. }
  3452. // Mounted with you
  3453. if (isMounted) {
  3454. if (metadata.directory) {
  3455. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_external"] color:[NCBrandColor sharedInstance].brand];
  3456. cell.accessoryType = UITableViewCellAccessoryNone;
  3457. }
  3458. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareMounted"] color:[NCBrandColor sharedInstance].brand];
  3459. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3460. [tap setNumberOfTapsRequired:1];
  3461. cell.shared.userInteractionEnabled = YES;
  3462. [cell.shared addGestureRecognizer:tap];
  3463. }
  3464. // You share
  3465. if ([shareLink length] > 0 || [shareUserAndGroup length] > 0) {
  3466. if (metadata.directory) {
  3467. if ([shareLink length] > 0)
  3468. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_public"] color:[NCBrandColor sharedInstance].brand];
  3469. if ([shareUserAndGroup length] > 0)
  3470. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3471. cell.shared.userInteractionEnabled = NO;
  3472. } else {
  3473. if ([shareLink length] > 0)
  3474. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareLink"] color:[NCBrandColor sharedInstance].brand];
  3475. if ([shareUserAndGroup length] > 0)
  3476. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3477. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  3478. [tap setNumberOfTapsRequired:1];
  3479. cell.shared.userInteractionEnabled = YES;
  3480. [cell.shared addGestureRecognizer:tap];
  3481. }
  3482. }
  3483. } else {
  3484. cell.shared.userInteractionEnabled = NO;
  3485. }
  3486. // ----------------------------------------------------------------------------------------------------------
  3487. // downloadFile
  3488. // ----------------------------------------------------------------------------------------------------------
  3489. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  3490. cell.status.image = [UIImage imageNamed:@"statusdownload"];
  3491. // sessionTaskIdentifier : RELOAD + STOP
  3492. if (metadata.sessionTaskIdentifier != k_taskIdentifierDone) {
  3493. [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3494. cell.cancelTaskButton.hidden = NO;
  3495. [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3496. cell.reloadTaskButton.hidden = NO;
  3497. }
  3498. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3499. float progress = [[appDelegate.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3500. if (progress > 0) {
  3501. cell.progressView.progressTintColor = [UIColor blackColor];
  3502. cell.progressView.progress = progress;
  3503. cell.progressView.hidden = NO;
  3504. }
  3505. // ----------------------------------------------------------------------------------------------------------
  3506. // downloadFile Error
  3507. // ----------------------------------------------------------------------------------------------------------
  3508. if (metadata.sessionTaskIdentifier == k_taskIdentifierError) {
  3509. cell.status.image = [UIImage imageNamed:@"statuserror"];
  3510. if ([metadata.sessionError length] == 0) {
  3511. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_downloaded_",nil)];
  3512. } else {
  3513. cell.labelInfoFile.text = metadata.sessionError;
  3514. }
  3515. }
  3516. }
  3517. // ----------------------------------------------------------------------------------------------------------
  3518. // uploadFile
  3519. // ----------------------------------------------------------------------------------------------------------
  3520. if ([metadata.session length] > 0 && [metadata.session rangeOfString:@"upload"].location != NSNotFound) {
  3521. cell.status.image = [UIImage imageNamed:@"statusupload"];
  3522. [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"removetask"] forState:UIControlStateNormal];
  3523. cell.cancelTaskButton.hidden = NO;
  3524. if (metadata.sessionTaskIdentifier == k_taskIdentifierStop) {
  3525. [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3526. cell.status.image = [UIImage imageNamed:@"statusstop"];
  3527. cell.reloadTaskButton.hidden = NO;
  3528. cell.stopTaskButton.hidden = YES;
  3529. } else {
  3530. [cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3531. cell.stopTaskButton.hidden = NO;
  3532. cell.reloadTaskButton.hidden = YES;
  3533. }
  3534. // se non c'è una preview in bianconero metti l'immagine di default
  3535. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, metadata.fileID]] == NO)
  3536. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"uploaddisable"] color:[NCBrandColor sharedInstance].brand];
  3537. cell.labelTitle.enabled = NO;
  3538. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3539. float progress = [[appDelegate.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3540. if (progress > 0) {
  3541. cell.progressView.progressTintColor = [UIColor blackColor];
  3542. cell.progressView.progress = progress;
  3543. cell.progressView.hidden = NO;
  3544. }
  3545. // ----------------------------------------------------------------------------------------------------------
  3546. // uploadFileError
  3547. // ----------------------------------------------------------------------------------------------------------
  3548. if (metadata.sessionTaskIdentifier == k_taskIdentifierError) {
  3549. cell.labelTitle.enabled = NO;
  3550. cell.status.image = [UIImage imageNamed:@"statuserror"];
  3551. if ([metadata.sessionError length] == 0) {
  3552. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_uploaded_",nil)];
  3553. } else {
  3554. cell.labelInfoFile.text = metadata.sessionError;
  3555. }
  3556. }
  3557. }
  3558. [cell.reloadTaskButton addTarget:self action:@selector(reloadTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3559. [cell.cancelTaskButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3560. [cell.stopTaskButton addTarget:self action:@selector(stopTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3561. // ======== MGSwipe ========
  3562. if (metadata.favorite)
  3563. 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]]];
  3564. else
  3565. 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]]];
  3566. cell.leftExpansion.buttonIndex = 0;
  3567. cell.leftExpansion.fillOnTrigger = NO;
  3568. //centerIconOverText
  3569. MGSwipeButton *favoriteButton = (MGSwipeButton *)[cell.leftButtons objectAtIndex:0];
  3570. [favoriteButton centerIconOverText];
  3571. //Right
  3572. 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]]];
  3573. cell.rightSwipeSettings.transition = MGSwipeTransitionBorder;
  3574. //centerIconOverText
  3575. MGSwipeButton *deleteButton = (MGSwipeButton *)[cell.rightButtons objectAtIndex:0];
  3576. MGSwipeButton *moreButton = (MGSwipeButton *)[cell.rightButtons objectAtIndex:1];
  3577. [deleteButton centerIconOverText];
  3578. [moreButton centerIconOverText];
  3579. //restore swipeOffset after relod
  3580. CGFloat swipeOffset = [[_statusSwipeCell objectForKey:indexPath] doubleValue];
  3581. if (swipeOffset < 0) {
  3582. [cell showSwipe:MGSwipeDirectionRightToLeft animated:NO];
  3583. [_statusSwipeCell removeObjectForKey:indexPath];
  3584. } else if (swipeOffset > 0) {
  3585. [cell showSwipe:MGSwipeDirectionLeftToRight animated:NO];
  3586. [_statusSwipeCell removeObjectForKey:indexPath];
  3587. }
  3588. return cell;
  3589. }
  3590. - (void)setTableViewFooter
  3591. {
  3592. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3593. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3594. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3595. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3596. UIFont *appFont = [UIFont systemFontOfSize:12];
  3597. footerLabel.font = appFont;
  3598. footerLabel.textColor = [UIColor grayColor];
  3599. footerLabel.backgroundColor = [UIColor clearColor];
  3600. footerLabel.textAlignment = NSTextAlignmentCenter;
  3601. NSString *folders;
  3602. NSString *files;
  3603. NSString *footerText;
  3604. if (_sectionDataSource.directories > 1) {
  3605. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  3606. } else if (_sectionDataSource.directories == 1){
  3607. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  3608. } else {
  3609. folders = @"";
  3610. }
  3611. if (_sectionDataSource.files > 1) {
  3612. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3613. } else if (_sectionDataSource.files == 1){
  3614. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3615. } else {
  3616. files = @"";
  3617. }
  3618. if ([folders isEqualToString:@""]) {
  3619. footerText = files;
  3620. } else if ([files isEqualToString:@""]) {
  3621. footerText = folders;
  3622. } else {
  3623. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  3624. }
  3625. footerLabel.text = footerText;
  3626. [footerView addSubview:footerLabel];
  3627. [self.tableView setTableFooterView:footerView];
  3628. }
  3629. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  3630. {
  3631. UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
  3632. // settiamo il record file.
  3633. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3634. if (!_metadata)
  3635. return;
  3636. // se non può essere selezionata deseleziona
  3637. if ([cell isEditing] == NO)
  3638. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  3639. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  3640. if (self.tableView.editing) {
  3641. [_selectedFileIDsMetadatas setObject:_metadata forKey:_metadata.fileID];
  3642. [self setTitle];
  3643. return;
  3644. }
  3645. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3646. if (!serverUrl) return;
  3647. // se è in corso una sessione
  3648. if ([_metadata.session length] > 0) return;
  3649. // file
  3650. if (_metadata.directory == NO) {
  3651. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  3652. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, _metadata.fileID]]) {
  3653. [self downloadFileSuccessFailure:_metadata.fileName fileID:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:@"" errorMessage:@"" errorCode:0];
  3654. } else {
  3655. if ([CCUtility isFolderEncrypted:self.serverUrl account:appDelegate.activeAccount] && ![CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  3656. [appDelegate messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  3657. } else {
  3658. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileName fileID:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  3659. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  3660. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  3661. }
  3662. }
  3663. }
  3664. if (_metadata.directory) [self performSegueDirectoryWithControlPasscode:true];
  3665. }
  3666. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  3667. {
  3668. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3669. [_selectedFileIDsMetadatas removeObjectForKey:metadata.fileID];
  3670. [self setTitle];
  3671. }
  3672. - (BOOL)indexPathIsValid:(NSIndexPath *)indexPath
  3673. {
  3674. if (!indexPath)
  3675. return NO;
  3676. NSInteger section = indexPath.section;
  3677. NSInteger row = indexPath.row;
  3678. NSInteger lastSectionIndex = [self numberOfSectionsInTableView:self.tableView] - 1;
  3679. if (section > lastSectionIndex || lastSectionIndex < 0)
  3680. return NO;
  3681. NSInteger rowCount = [self.tableView numberOfRowsInSection:indexPath.section] - 1;
  3682. if (rowCount < 0)
  3683. return NO;
  3684. return row <= rowCount;
  3685. }
  3686. #pragma --------------------------------------------------------------------------------------------
  3687. #pragma mark ===== Navigation ====
  3688. #pragma --------------------------------------------------------------------------------------------
  3689. - (BOOL)shouldPerformSegue
  3690. {
  3691. // if background return
  3692. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return NO;
  3693. if (self.view.window == NO)
  3694. return NO;
  3695. // Collapsed ma siamo già in detail esci
  3696. if (self.splitViewController.isCollapsed)
  3697. if (_detailViewController.isViewLoaded && _detailViewController.view.window) return NO;
  3698. return YES;
  3699. }
  3700. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  3701. {
  3702. id viewController = segue.destinationViewController;
  3703. NSMutableArray *allRecordsDataSourceImagesVideos = [NSMutableArray new];
  3704. tableMetadata *metadata;
  3705. if ([viewController isKindOfClass:[UINavigationController class]]) {
  3706. UINavigationController *nav = viewController;
  3707. _detailViewController = (CCDetail *)nav.topViewController;
  3708. } else {
  3709. _detailViewController = segue.destinationViewController;
  3710. }
  3711. if ([sender isKindOfClass:[tableMetadata class]]) {
  3712. metadata = sender;
  3713. [allRecordsDataSourceImagesVideos addObject:sender];
  3714. } else {
  3715. metadata = _metadata;
  3716. for (NSString *fileID in _sectionDataSource.allEtag) {
  3717. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3718. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video] || [metadata.typeFile isEqualToString: k_metadataTypeFile_audio])
  3719. [allRecordsDataSourceImagesVideos addObject:metadata];
  3720. }
  3721. }
  3722. _detailViewController.metadataDetail = metadata;
  3723. _detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  3724. _detailViewController.dateFilterQuery = nil;
  3725. [_detailViewController setTitle:metadata.fileName];
  3726. }
  3727. // can i go to next viewcontroller
  3728. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode
  3729. {
  3730. NSString *nomeDir;
  3731. if(self.tableView.editing == NO) {
  3732. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3733. if (!serverUrl) return;
  3734. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  3735. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, lockServerUrl]];
  3736. // 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
  3737. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil && controlPasscode) {
  3738. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  3739. viewController.delegate = self;
  3740. viewController.fromType = CCBKPasscodeFromLockDirectory;
  3741. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  3742. viewController.inputViewTitlePassword = YES;
  3743. if ([CCUtility getSimplyBlockCode]) {
  3744. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  3745. viewController.passcodeInputView.maximumLength = 6;
  3746. } else {
  3747. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  3748. viewController.passcodeInputView.maximumLength = 64;
  3749. }
  3750. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  3751. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  3752. viewController.touchIDManager = touchIDManager;
  3753. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  3754. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  3755. viewController.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
  3756. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  3757. [self presentViewController:navController animated:YES completion:nil];
  3758. return;
  3759. }
  3760. nomeDir = _metadata.fileName;
  3761. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:serverUrl addFileName:nomeDir];
  3762. CCMain *viewController = [appDelegate.listMainVC objectForKey:serverUrlPush];
  3763. if (!viewController) {
  3764. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMainVC"];
  3765. viewController.serverUrl = serverUrlPush;
  3766. viewController.titleMain = _metadata.fileName;
  3767. viewController.textBackButton = _titleMain;
  3768. // save self
  3769. [appDelegate.listMainVC setObject:viewController forKey:serverUrlPush];
  3770. [self.navigationController pushViewController:viewController animated:YES];
  3771. } else {
  3772. if (viewController.isViewLoaded) {
  3773. // Fix : Application tried to present modally an active controller
  3774. if ([self.navigationController isBeingPresented]) {
  3775. // being presented
  3776. } else if ([self.navigationController isMovingToParentViewController]) {
  3777. // being pushed
  3778. } else {
  3779. [self.navigationController pushViewController:viewController animated:YES];
  3780. }
  3781. }
  3782. }
  3783. }
  3784. }
  3785. @end