CCMain.m 232 KB

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