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