CCMain.m 211 KB

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