CCMain.m 225 KB

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