CCMain.m 225 KB

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