CCMain.m 234 KB

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