CCMain.m 206 KB

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