CCMain.m 209 KB

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