CCMain.m 213 KB

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