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