CCMain.m 231 KB

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