CCMain.m 208 KB

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