CCMain.m 214 KB

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