CCMain.m 209 KB

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