CCMain.m 224 KB

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