CCMain.m 206 KB

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