CCMain.m 228 KB

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