CCMain.m 211 KB

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