CCMain.m 232 KB

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