CCMain.m 232 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273
  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)cancelAllTask:(id)sender
  1689. {
  1690. }
  1691. - (void)cancelTaskButton:(tableMetadata *)metadata reloadTable:(BOOL)reloadTable
  1692. {
  1693. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1694. __block NSURLSessionTask *findTask;
  1695. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1696. NSString *fileID = metadata.fileID;
  1697. // DOWNLOAD
  1698. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  1699. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1700. for (NSURLSessionTask *task in downloadTasks)
  1701. if (task.taskIdentifier == sessionTaskIdentifier) {
  1702. findTask = task;
  1703. [appDelegate.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  1704. [task cancel];
  1705. }
  1706. if (!findTask) {
  1707. [appDelegate.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  1708. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1709. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1710. }
  1711. }];
  1712. }
  1713. // UPLOAD
  1714. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1715. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1716. for (NSURLSessionUploadTask *task in uploadTasks)
  1717. if (task.taskIdentifier == sessionTaskIdentifier) {
  1718. findTask = task;
  1719. [appDelegate.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  1720. [task cancel];
  1721. }
  1722. if (!findTask) {
  1723. [appDelegate.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  1724. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1725. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1726. }
  1727. }];
  1728. }
  1729. }
  1730. - (void)stopTaskButton:(id)sender withEvent:(UIEvent *)event
  1731. {
  1732. UITouch * touch = [[event allTouches] anyObject];
  1733. CGPoint location = [touch locationInView:self.tableView];
  1734. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1735. if ([self indexPathIsValid:indexPath]) {
  1736. tableMetadata *metadataSection = [self getMetadataFromSectionDataSource:indexPath];
  1737. if (metadataSection) {
  1738. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadataSection.fileID]];
  1739. if (metadata)
  1740. [self stopTaskButton:metadata];
  1741. }
  1742. }
  1743. }
  1744. - (void)stopTaskButton:(tableMetadata *)metadata
  1745. {
  1746. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1747. __block NSURLSessionTask *findTask;
  1748. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1749. NSString *fileID = metadata.fileID;
  1750. // UPLOAD
  1751. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1752. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1753. for (NSURLSessionUploadTask *task in uploadTasks)
  1754. if (task.taskIdentifier == sessionTaskIdentifier) {
  1755. [appDelegate.listChangeTask setObject:@"stopUpload" forKey:fileID];
  1756. findTask = task;
  1757. [task cancel];
  1758. }
  1759. if (!findTask) {
  1760. [appDelegate.listChangeTask setObject:@"stopUpload" forKey:fileID];
  1761. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1762. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1763. }
  1764. }];
  1765. }
  1766. }
  1767. #pragma --------------------------------------------------------------------------------------------
  1768. #pragma mark ===== Shared =====
  1769. #pragma --------------------------------------------------------------------------------------------
  1770. - (void)readSharedSuccess:(CCMetadataNet *)metadataNet items:(NSDictionary *)items openWindow:(BOOL)openWindow
  1771. {
  1772. [_hud hideHud];
  1773. // Check Active Account
  1774. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1775. return;
  1776. NSArray *result = [[NCManageDatabase sharedInstance] updateShare:items activeUrl:appDelegate.activeUrl];
  1777. if (result) {
  1778. appDelegate.sharesLink = result[0];
  1779. appDelegate.sharesUserAndGroup = result[1];
  1780. }
  1781. // Notify Shares View
  1782. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"SharesReloadDatasource" object:nil userInfo:nil];
  1783. if (openWindow) {
  1784. if (_shareOC) {
  1785. [_shareOC reloadData];
  1786. } else {
  1787. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadataNet.fileID]];
  1788. // Apriamo la view
  1789. _shareOC = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareOC"];
  1790. _shareOC.delegate = self;
  1791. _shareOC.metadata = metadata;
  1792. _shareOC.serverUrl = metadataNet.serverUrl;
  1793. _shareOC.shareLink = [appDelegate.sharesLink objectForKey:metadata.fileID];
  1794. _shareOC.shareUserAndGroup = [appDelegate.sharesUserAndGroup objectForKey:metadata.fileID];
  1795. [_shareOC setModalPresentationStyle:UIModalPresentationFormSheet];
  1796. [self presentViewController:_shareOC animated:YES completion:nil];
  1797. }
  1798. }
  1799. [self tableViewReloadData];
  1800. }
  1801. - (void)shareFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1802. {
  1803. [_hud hideHud];
  1804. // Check Active Account
  1805. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1806. return;
  1807. // Unauthorized
  1808. if (errorCode == kOCErrorServerUnauthorized)
  1809. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  1810. else
  1811. [appDelegate messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1812. if (_shareOC)
  1813. [_shareOC reloadData];
  1814. [self tableViewReloadData];
  1815. }
  1816. - (void)share:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password
  1817. {
  1818. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1819. metadataNet.action = actionShare;
  1820. metadataNet.fileID = metadata.fileID;
  1821. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:appDelegate.activeUrl];
  1822. metadataNet.fileNameView = metadata.fileNameView;
  1823. metadataNet.password = password;
  1824. metadataNet.selector = selectorShare;
  1825. metadataNet.serverUrl = serverUrl;
  1826. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1827. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1828. }
  1829. - (void)unShareSuccess:(CCMetadataNet *)metadataNet
  1830. {
  1831. [_hud hideHud];
  1832. // Check Active Account
  1833. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1834. return;
  1835. // rimuoviamo la condivisione da db
  1836. NSArray *result = [[NCManageDatabase sharedInstance] unShare:metadataNet.share fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl sharesLink:appDelegate.sharesLink sharesUserAndGroup:appDelegate.sharesUserAndGroup];
  1837. if (result) {
  1838. appDelegate.sharesLink = result[0];
  1839. appDelegate.sharesUserAndGroup = result[1];
  1840. }
  1841. if (_shareOC)
  1842. [_shareOC reloadData];
  1843. [self tableViewReloadData];
  1844. }
  1845. - (void)unShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl
  1846. {
  1847. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1848. metadataNet.action = actionUnShare;
  1849. metadataNet.fileID = metadata.fileID;
  1850. metadataNet.fileName = metadata.fileName;
  1851. metadataNet.fileNameView = metadata.fileNameView;
  1852. metadataNet.selector = selectorUnshare;
  1853. metadataNet.serverUrl = serverUrl;
  1854. metadataNet.share = share;
  1855. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1856. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1857. }
  1858. - (void)updateShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password expirationTime:(NSString *)expirationTime permission:(NSInteger)permission
  1859. {
  1860. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1861. metadataNet.action = actionUpdateShare;
  1862. metadataNet.fileID = metadata.fileID;
  1863. metadataNet.expirationTime = expirationTime;
  1864. metadataNet.password = password;
  1865. metadataNet.selector = selectorUpdateShare;
  1866. metadataNet.serverUrl = serverUrl;
  1867. metadataNet.share = share;
  1868. metadataNet.sharePermission = permission;
  1869. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1870. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1871. }
  1872. - (void)getUserAndGroupSuccess:(CCMetadataNet *)metadataNet items:(NSArray *)items
  1873. {
  1874. [_hud hideHud];
  1875. // Check Active Account
  1876. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1877. return;
  1878. if (_shareOC)
  1879. [_shareOC reloadUserAndGroup:items];
  1880. }
  1881. - (void)getUserAndGroupFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1882. {
  1883. [_hud hideHud];
  1884. // Check Active Account
  1885. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1886. return;
  1887. // Unauthorized
  1888. if (errorCode == kOCErrorServerUnauthorized)
  1889. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  1890. else
  1891. [appDelegate messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1892. }
  1893. - (void)getUserAndGroup:(NSString *)find
  1894. {
  1895. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1896. metadataNet.action = actionGetUserAndGroup;
  1897. metadataNet.optionAny = find;
  1898. metadataNet.selector = selectorGetUserAndGroup;
  1899. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1900. [_hud visibleIndeterminateHud];
  1901. }
  1902. - (void)shareUserAndGroup:(NSString *)user shareeType:(NSInteger)shareeType permission:(NSInteger)permission metadata:(tableMetadata *)metadata directoryID:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  1903. {
  1904. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1905. metadataNet.action = actionShareWith;
  1906. metadataNet.fileID = metadata.fileID;
  1907. metadataNet.directoryID = directoryID;
  1908. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:appDelegate.activeUrl];
  1909. metadataNet.fileNameView = metadata.fileNameView;
  1910. metadataNet.serverUrl = serverUrl;
  1911. metadataNet.selector = selectorShare;
  1912. metadataNet.share = user;
  1913. metadataNet.shareeType = shareeType;
  1914. metadataNet.sharePermission = permission;
  1915. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1916. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1917. }
  1918. - (void)openWindowShare:(tableMetadata *)metadata
  1919. {
  1920. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1921. if (!serverUrl) return;
  1922. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1923. metadataNet.action = actionReadShareServer;
  1924. metadataNet.fileID = metadata.fileID;
  1925. metadataNet.fileName = metadata.fileName;
  1926. metadataNet.fileNameView = metadata.fileNameView;
  1927. metadataNet.selector = selectorOpenWindowShare;
  1928. metadataNet.serverUrl = serverUrl;
  1929. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1930. [_hud visibleIndeterminateHud];
  1931. }
  1932. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  1933. {
  1934. CGPoint location = [tapGesture locationInView:self.tableView];
  1935. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1936. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1937. if (metadata)
  1938. [self openWindowShare:metadata];
  1939. }
  1940. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  1941. {
  1942. CGPoint location = [tapGesture locationInView:self.tableView];
  1943. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1944. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1945. if (metadata) {
  1946. CCShareInfoCMOC *vc = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareInfoCMOC"];
  1947. vc.metadata = metadata;
  1948. [vc setModalPresentationStyle:UIModalPresentationFormSheet];
  1949. [self presentViewController:vc animated:YES completion:nil];
  1950. }
  1951. }
  1952. #pragma --------------------------------------------------------------------------------------------
  1953. #pragma mark ===== Favorite =====
  1954. #pragma --------------------------------------------------------------------------------------------
  1955. - (void)settingFavoriteSuccessFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1956. {
  1957. // Check Active Account
  1958. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1959. return;
  1960. if (errorCode == 0) {
  1961. _dateReadDataSource = nil;
  1962. [[NCManageDatabase sharedInstance] setMetadataFavoriteWithFileID:metadataNet.fileID favorite:[metadataNet.optionAny boolValue]];
  1963. if (_isSearchMode)
  1964. [self readFolder:metadataNet.serverUrl];
  1965. else
  1966. [self reloadDatasource:metadataNet.serverUrl];
  1967. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadataNet.fileID]];
  1968. if (metadata.directory && metadata.favorite) {
  1969. NSString *dir = [CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:metadata.fileName];
  1970. [appDelegate.activeFavorites addFavoriteFolder:dir];
  1971. }
  1972. } else {
  1973. if (errorCode == kOCErrorServerUnauthorized)
  1974. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  1975. NSLog(@"[LOG] Setting Favorite failure error %d, %@", (int)errorCode, message);
  1976. }
  1977. }
  1978. - (void)addFavorite:(tableMetadata *)metadata
  1979. {
  1980. if (metadata.directory) {
  1981. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  1982. } else {
  1983. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1984. if (serverUrl) {
  1985. metadata.session = k_download_session;
  1986. metadata.sessionError = @"";
  1987. metadata.sessionSelector = selectorAddFavorite;
  1988. metadata.sessionSelectorPost = @"";
  1989. metadata.status = k_metadataStatusWaitDownload;
  1990. // Add Metadata for Download
  1991. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1992. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  1993. }
  1994. }
  1995. }
  1996. - (void)removeFavorite:(tableMetadata *)metadata
  1997. {
  1998. [[CCActions sharedInstance] settingFavorite:metadata favorite:NO delegate:self];
  1999. }
  2000. #pragma --------------------------------------------------------------------------------------------
  2001. #pragma mark ===== Open in... =====
  2002. #pragma --------------------------------------------------------------------------------------------
  2003. - (void)openIn:(tableMetadata *)metadata
  2004. {
  2005. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2006. if (!serverUrl) return;
  2007. metadata.session = k_download_session;
  2008. metadata.sessionError = @"";
  2009. metadata.sessionSelector = selectorOpenIn;
  2010. metadata.sessionSelectorPost = @"";
  2011. metadata.status = k_metadataStatusWaitDownload;
  2012. // Add Metadata for Download
  2013. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  2014. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  2015. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2016. if ([self indexPathIsValid:indexPath])
  2017. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2018. }
  2019. #pragma --------------------------------------------------------------------------------------------
  2020. #pragma mark ===== Remove Local File =====
  2021. #pragma --------------------------------------------------------------------------------------------
  2022. - (void)removeLocalFile:(tableMetadata *)metadata
  2023. {
  2024. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2025. if (!serverUrl) return;
  2026. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  2027. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadata.fileID] error:nil];
  2028. [self reloadDatasource:serverUrl];
  2029. }
  2030. #pragma --------------------------------------------------------------------------------------------
  2031. #pragma mark ===== Order Table & GroupBy & DirectoryOnTop =====
  2032. #pragma --------------------------------------------------------------------------------------------
  2033. - (void)orderTable:(NSString *)order
  2034. {
  2035. [CCUtility setOrderSettings:order];
  2036. // Clear data-read of DataSource
  2037. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2038. }
  2039. - (void)ascendingTable:(BOOL)ascending
  2040. {
  2041. [CCUtility setAscendingSettings:ascending];
  2042. // Clear data-read of DataSource
  2043. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2044. }
  2045. - (void)directoryOnTop:(BOOL)directoryOnTop
  2046. {
  2047. [CCUtility setDirectoryOnTop:directoryOnTop];
  2048. // Clear data-read of DataSource
  2049. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2050. }
  2051. - (void)tableGroupBy:(NSString *)groupBy
  2052. {
  2053. [CCUtility setGroupBySettings:groupBy];
  2054. // Clear data-read of DataSource
  2055. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2056. }
  2057. #pragma --------------------------------------------------------------------------------------------
  2058. #pragma mark ==== Menu LOGO ====
  2059. #pragma --------------------------------------------------------------------------------------------
  2060. - (void)menuLogo:(UIGestureRecognizer *)theGestureRecognizer
  2061. {
  2062. if (appDelegate.reSelectMenu.isOpen || appDelegate.reMainMenu.isOpen)
  2063. return;
  2064. // Brand
  2065. if ([NCBrandOptions sharedInstance].disable_multiaccount)
  2066. return;
  2067. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  2068. NSMutableArray *menuArray = [NSMutableArray new];
  2069. for (NSString *account in listAccount) {
  2070. CCMenuItem *item = [[CCMenuItem alloc] init];
  2071. item.title = [account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  2072. item.argument = account;
  2073. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ ", account]];
  2074. NSString *directoryUser = [CCUtility getDirectoryActiveUser:tableAccount.user activeUrl:tableAccount.url];
  2075. UIImage *avatar = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/avatar.png", directoryUser]];
  2076. if (avatar) {
  2077. avatar = [CCGraphics scaleImage:avatar toSize:CGSizeMake(25, 25) isAspectRation:YES];
  2078. CCAvatar *avatarImageView = [[CCAvatar alloc] initWithImage:avatar borderColor:[UIColor lightGrayColor] borderWidth:0.5];
  2079. CGSize imageSize = avatarImageView.bounds.size;
  2080. UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
  2081. CGContextRef context = UIGraphicsGetCurrentContext();
  2082. [avatarImageView.layer renderInContext:context];
  2083. avatar = UIGraphicsGetImageFromCurrentImageContext();
  2084. UIGraphicsEndImageContext();
  2085. } else {
  2086. avatar = [UIImage imageNamed:@"menuLogoUser"];
  2087. }
  2088. item.image = avatar;
  2089. item.target = self;
  2090. if ([account isEqualToString:appDelegate.activeAccount]) {
  2091. item.action = nil;
  2092. [menuArray insertObject:item atIndex:0];
  2093. } else {
  2094. item.action = @selector(changeDefaultAccount:);
  2095. [menuArray addObject:item];
  2096. }
  2097. }
  2098. // Add + new account
  2099. CCMenuItem *item = [[CCMenuItem alloc] init];
  2100. item.title = NSLocalizedString(@"_add_account_", nil);
  2101. item.argument = @"";
  2102. item.image = [UIImage imageNamed:@"add"];
  2103. item.target = self;
  2104. item.action = @selector(addNewAccount:);
  2105. [menuArray addObject:item];
  2106. OptionalConfiguration options;
  2107. Color textColor, backgroundColor;
  2108. textColor.R = 0;
  2109. textColor.G = 0;
  2110. textColor.B = 0;
  2111. backgroundColor.R = 1;
  2112. backgroundColor.G = 1;
  2113. backgroundColor.B = 1;
  2114. options.arrowSize = 9;
  2115. options.marginXSpacing = 7;
  2116. options.marginYSpacing = 10;
  2117. options.intervalSpacing = 20;
  2118. options.menuCornerRadius = 6.5;
  2119. options.maskToBackground = NO;
  2120. options.shadowOfMenu = YES;
  2121. options.hasSeperatorLine = YES;
  2122. options.seperatorLineHasInsets = YES;
  2123. options.textColor = textColor;
  2124. options.menuBackgroundColor = backgroundColor;
  2125. CGRect rect = self.view.frame;
  2126. CGFloat locationY = [theGestureRecognizer locationInView: self.navigationController.navigationBar].y;
  2127. CGFloat safeAreaTop = 0;
  2128. CGFloat offsetY = 35;
  2129. if (@available(iOS 11, *)) {
  2130. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top / 2;
  2131. }
  2132. rect.origin.y = locationY + safeAreaTop + offsetY;
  2133. rect.size.height = rect.size.height - locationY - safeAreaTop - offsetY;
  2134. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  2135. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  2136. }
  2137. - (void)changeDefaultAccount:(CCMenuItem *)sender
  2138. {
  2139. 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];
  2140. if (transferInprogress > 0) {
  2141. [JDStatusBarNotification showWithStatus:NSLocalizedString(@"_transfers_in_queue_", nil) dismissAfter:k_dismissAfterSecond styleName:JDStatusBarStyleDefault];
  2142. return;
  2143. }
  2144. [appDelegate.netQueue cancelAllOperations];
  2145. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2146. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:[sender argument]];
  2147. if (tableAccount) {
  2148. [appDelegate settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activeUserID:tableAccount.userID activePassword:tableAccount.password];
  2149. // go to home sweet home
  2150. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initializeMain" object:nil];
  2151. }
  2152. });
  2153. }
  2154. - (void)addNewAccount:(CCMenuItem *)sender
  2155. {
  2156. 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];
  2157. if (transferInprogress > 0) {
  2158. [JDStatusBarNotification showWithStatus:NSLocalizedString(@"_transfers_in_queue_", nil) dismissAfter:k_dismissAfterSecond styleName:JDStatusBarStyleDefault];
  2159. return;
  2160. }
  2161. [appDelegate.netQueue cancelAllOperations];
  2162. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2163. [appDelegate openLoginView:self loginType:loginAdd];
  2164. });
  2165. }
  2166. #pragma --------------------------------------------------------------------------------------------
  2167. #pragma mark ==== ReMenu ====
  2168. #pragma --------------------------------------------------------------------------------------------
  2169. - (void)createReMenuBackgroundView:(REMenu *)menu
  2170. {
  2171. CGFloat safeAreaBottom = 0;
  2172. CGFloat safeAreaTop = 0;
  2173. CGFloat statusBar = 0;
  2174. if (@available(iOS 11, *)) {
  2175. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top;
  2176. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  2177. }
  2178. if ([UIApplication sharedApplication].isStatusBarHidden) {
  2179. statusBar = 13;
  2180. }
  2181. CGFloat computeNavigationBarOffset = [menu computeNavigationBarOffset];
  2182. UIViewController *rootController = [[[[UIApplication sharedApplication]delegate] window] rootViewController];
  2183. CGRect globalPositionMenu = [menu.menuView convertRect:menu.menuView.bounds toView:rootController.view];
  2184. _reMenuBackgroundView.frame = CGRectMake(0, computeNavigationBarOffset, globalPositionMenu.size.width, rootController.view.frame.size.height);
  2185. [UIView animateWithDuration:0.2 animations:^{
  2186. CGFloat minimum = safeAreaBottom + self.tabBarController.tabBar.frame.size.height;
  2187. CGFloat y = rootController.view.frame.size.height - menu.menuView.frame.size.height - globalPositionMenu.origin.y + statusBar;
  2188. if (y>minimum) {
  2189. _reMenuBackgroundView.frame = CGRectMake(0, rootController.view.frame.size.height, globalPositionMenu.size.width, - y);
  2190. [self.tabBarController.view addSubview:_reMenuBackgroundView];
  2191. }
  2192. }];
  2193. }
  2194. - (void)createReMainMenu
  2195. {
  2196. NSString *ordinamento;
  2197. NSString *groupBy = _directoryGroupBy;
  2198. __block NSString *nuovoOrdinamento;
  2199. NSString *titoloNuovo, *titoloAttuale;
  2200. BOOL ascendente;
  2201. __block BOOL nuovoAscendente;
  2202. UIImage *image;
  2203. // ITEM SELECT ----------------------------------------------------------------------------------------------------
  2204. appDelegate.selezionaItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_", nil)subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"select"] color:[NCBrandColor sharedInstance].brandElement] highlightedImage:nil action:^(REMenuItem *item) {
  2205. if ([_sectionDataSource.allRecordsDataSource count] > 0) {
  2206. [self tableViewSelect:YES];
  2207. }
  2208. }];
  2209. // ITEM ORDER ----------------------------------------------------------------------------------------------------
  2210. ordinamento = _directoryOrder;
  2211. if ([ordinamento isEqualToString:@"fileName"]) {
  2212. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdeyByDate"] color:[NCBrandColor sharedInstance].brandElement];
  2213. titoloNuovo = NSLocalizedString(@"_order_by_date_", nil);
  2214. titoloAttuale = NSLocalizedString(@"_current_order_name_", nil);
  2215. nuovoOrdinamento = @"date";
  2216. }
  2217. if ([ordinamento isEqualToString:@"date"]) {
  2218. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrderByFileName"] color:[NCBrandColor sharedInstance].brandElement];
  2219. titoloNuovo = NSLocalizedString(@"_order_by_name_", nil);
  2220. titoloAttuale = NSLocalizedString(@"_current_order_date_", nil);
  2221. nuovoOrdinamento = @"fileName";
  2222. }
  2223. appDelegate.ordinaItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2224. [self orderTable:nuovoOrdinamento];
  2225. }];
  2226. // ITEM ASCENDING -----------------------------------------------------------------------------------------------------
  2227. ascendente = [CCUtility getAscendingSettings];
  2228. if (ascendente) {
  2229. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoDiscendente"] color:[NCBrandColor sharedInstance].brandElement];
  2230. titoloNuovo = NSLocalizedString(@"_sort_descending_", nil);
  2231. titoloAttuale = NSLocalizedString(@"_current_sort_ascending_", nil);
  2232. nuovoAscendente = false;
  2233. }
  2234. if (!ascendente) {
  2235. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoAscendente"] color:[NCBrandColor sharedInstance].brandElement];
  2236. titoloNuovo = NSLocalizedString(@"_sort_ascending_", nil);
  2237. titoloAttuale = NSLocalizedString(@"_current_sort_descending_", nil);
  2238. nuovoAscendente = true;
  2239. }
  2240. appDelegate.ascendenteItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2241. [self ascendingTable:nuovoAscendente];
  2242. }];
  2243. // ITEM ALPHABETIC -----------------------------------------------------------------------------------------------------
  2244. if ([groupBy isEqualToString:@"alphabetic"]) { titoloNuovo = NSLocalizedString(@"_group_alphabetic_yes_", nil); }
  2245. else { titoloNuovo = NSLocalizedString(@"_group_alphabetic_no_", nil); }
  2246. appDelegate.alphabeticItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByAlphabetic"] color:[NCBrandColor sharedInstance].brandElement] highlightedImage:nil action:^(REMenuItem *item) {
  2247. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  2248. else [self tableGroupBy:@"alphabetic"];
  2249. }];
  2250. // ITEM TYPEFILE -------------------------------------------------------------------------------------------------------
  2251. if ([groupBy isEqualToString:@"typefile"]) { titoloNuovo = NSLocalizedString(@"_group_typefile_yes_", nil); }
  2252. else { titoloNuovo = NSLocalizedString(@"_group_typefile_no_", nil); }
  2253. appDelegate.typefileItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"file"] color:[NCBrandColor sharedInstance].brandElement] highlightedImage:nil action:^(REMenuItem *item) {
  2254. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  2255. else [self tableGroupBy:@"typefile"];
  2256. }];
  2257. // ITEM DATE -------------------------------------------------------------------------------------------------------
  2258. if ([groupBy isEqualToString:@"date"]) { titoloNuovo = NSLocalizedString(@"_group_date_yes_", nil); }
  2259. else { titoloNuovo = NSLocalizedString(@"_group_date_no_", nil); }
  2260. appDelegate.dateItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByDate"] color:[NCBrandColor sharedInstance].brandElement] highlightedImage:nil action:^(REMenuItem *item) {
  2261. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  2262. else [self tableGroupBy:@"date"];
  2263. }];
  2264. // ITEM DIRECTORY ON TOP ------------------------------------------------------------------------------------------------
  2265. if ([CCUtility getDirectoryOnTop]) { titoloNuovo = NSLocalizedString(@"_directory_on_top_yes_", nil); }
  2266. else { titoloNuovo = NSLocalizedString(@"_directory_on_top_no_", nil); }
  2267. appDelegate.directoryOnTopItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder"] color:[NCBrandColor sharedInstance].brandElement] highlightedImage:nil action:^(REMenuItem *item) {
  2268. if ([CCUtility getDirectoryOnTop])
  2269. [self directoryOnTop:NO];
  2270. else
  2271. [self directoryOnTop:YES];
  2272. }];
  2273. // REMENU --------------------------------------------------------------------------------------------------------------
  2274. appDelegate.reMainMenu = [[REMenu alloc] initWithItems:@[appDelegate.selezionaItem, appDelegate.ordinaItem, appDelegate.ascendenteItem, appDelegate.alphabeticItem, appDelegate.typefileItem, appDelegate.dateItem, appDelegate.directoryOnTopItem]];
  2275. appDelegate.reMainMenu.imageOffset = CGSizeMake(5, -1);
  2276. appDelegate.reMainMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2277. appDelegate.reMainMenu.imageOffset = CGSizeMake(0, 0);
  2278. appDelegate.reMainMenu.waitUntilAnimationIsComplete = NO;
  2279. appDelegate.reMainMenu.separatorHeight = 0.5;
  2280. appDelegate.reMainMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2281. appDelegate.reMainMenu.backgroundColor = [NCBrandColor sharedInstance].backgroundView;
  2282. appDelegate.reMainMenu.textColor = [UIColor blackColor];
  2283. appDelegate.reMainMenu.textAlignment = NSTextAlignmentLeft;
  2284. appDelegate.reMainMenu.textShadowColor = nil;
  2285. appDelegate.reMainMenu.textOffset = CGSizeMake(50, 0.0);
  2286. appDelegate.reMainMenu.font = [UIFont systemFontOfSize:14.0];
  2287. appDelegate.reMainMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2288. appDelegate.reMainMenu.highlightedSeparatorColor = nil;
  2289. appDelegate.reMainMenu.highlightedTextColor = [UIColor blackColor];
  2290. appDelegate.reMainMenu.highlightedTextShadowColor = nil;
  2291. appDelegate.reMainMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2292. appDelegate.reMainMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  2293. appDelegate.reMainMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2294. appDelegate.reMainMenu.subtitleTextShadowColor = nil;
  2295. appDelegate.reMainMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2296. appDelegate.reMainMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2297. appDelegate.reMainMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2298. appDelegate.reMainMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2299. appDelegate.reMainMenu.subtitleHighlightedTextShadowColor = nil;
  2300. appDelegate.reMainMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2301. appDelegate.reMainMenu.borderWidth = 0.3;
  2302. appDelegate.reMainMenu.borderColor = [UIColor lightGrayColor];
  2303. appDelegate.reMainMenu.animationDuration = 0.2;
  2304. appDelegate.reMainMenu.closeAnimationDuration = 0.2;
  2305. appDelegate.reMainMenu.bounce = NO;
  2306. __weak typeof(self) weakSelf = self;
  2307. [appDelegate.reMainMenu setClosePreparationBlock:^{
  2308. // Backgroun reMenu (Gesture)
  2309. [weakSelf.reMenuBackgroundView removeFromSuperview];
  2310. [weakSelf.reMenuBackgroundView removeGestureRecognizer:weakSelf.singleFingerTap];
  2311. }];
  2312. }
  2313. - (void)toggleReMainMenu
  2314. {
  2315. if (appDelegate.reMainMenu.isOpen) {
  2316. [appDelegate.reMainMenu close];
  2317. } else {
  2318. [self createReMainMenu];
  2319. [appDelegate.reMainMenu showFromNavigationController:self.navigationController];
  2320. // Backgroun reMenu & (Gesture)
  2321. [self createReMenuBackgroundView:appDelegate.reMainMenu];
  2322. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReMainMenu)];
  2323. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2324. }
  2325. }
  2326. - (void)createReSelectMenu
  2327. {
  2328. // ITEM DELETE ------------------------------------------------------------------------------------------------------
  2329. 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) {
  2330. [self deleteFile];
  2331. }];
  2332. // ITEM MOVE ------------------------------------------------------------------------------------------------------
  2333. 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) {
  2334. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2335. }];
  2336. // ITEM DOWNLOAD ----------------------------------------------------------------------------------------------------
  2337. 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) {
  2338. [self downloadSelectedFilesFolders];
  2339. }];
  2340. // ITEM SAVE IMAGE & VIDEO -------------------------------------------------------------------------------------------
  2341. 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) {
  2342. [self saveSelectedFiles];
  2343. }];
  2344. // E2EE
  2345. if (_metadataFolder.e2eEncrypted) {
  2346. appDelegate.reSelectMenu = [[REMenu alloc] initWithItems:@[appDelegate.deleteItem,appDelegate.downloadItem, appDelegate.saveItem]];
  2347. } else {
  2348. appDelegate.reSelectMenu = [[REMenu alloc] initWithItems:@[appDelegate.deleteItem,appDelegate.moveItem, appDelegate.downloadItem, appDelegate.saveItem]];
  2349. }
  2350. appDelegate.reSelectMenu.imageOffset = CGSizeMake(5, -1);
  2351. appDelegate.reSelectMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2352. appDelegate.reSelectMenu.imageOffset = CGSizeMake(0, 0);
  2353. appDelegate.reSelectMenu.waitUntilAnimationIsComplete = NO;
  2354. appDelegate.reSelectMenu.separatorHeight = 0.5;
  2355. appDelegate.reSelectMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2356. appDelegate.reSelectMenu.backgroundColor = [NCBrandColor sharedInstance].backgroundView;
  2357. appDelegate.reSelectMenu.textColor = [UIColor blackColor];
  2358. appDelegate.reSelectMenu.textAlignment = NSTextAlignmentLeft;
  2359. appDelegate.reSelectMenu.textShadowColor = nil;
  2360. appDelegate.reSelectMenu.textOffset = CGSizeMake(50, 0.0);
  2361. appDelegate.reSelectMenu.font = [UIFont systemFontOfSize:14.0];
  2362. appDelegate.reSelectMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2363. appDelegate.reSelectMenu.highlightedSeparatorColor = nil;
  2364. appDelegate.reSelectMenu.highlightedTextColor = [UIColor blackColor];
  2365. appDelegate.reSelectMenu.highlightedTextShadowColor = nil;
  2366. appDelegate.reSelectMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2367. appDelegate.reSelectMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1.000];
  2368. appDelegate.reSelectMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2369. appDelegate.reSelectMenu.subtitleTextShadowColor = nil;
  2370. appDelegate.reSelectMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2371. appDelegate.reSelectMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2372. appDelegate.reSelectMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2373. appDelegate.reSelectMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2374. appDelegate.reSelectMenu.subtitleHighlightedTextShadowColor = nil;
  2375. appDelegate.reSelectMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2376. appDelegate.reSelectMenu.borderWidth = 0.3;
  2377. appDelegate.reSelectMenu.borderColor = [UIColor lightGrayColor];
  2378. appDelegate.reSelectMenu.closeAnimationDuration = 0.2;
  2379. appDelegate.reSelectMenu.animationDuration = 0.2;
  2380. appDelegate.reSelectMenu.bounce = NO;
  2381. __weak typeof(self) weakSelf = self;
  2382. [appDelegate.reSelectMenu setClosePreparationBlock:^{
  2383. // Backgroun reMenu (Gesture)
  2384. [weakSelf.reMenuBackgroundView removeFromSuperview];
  2385. [weakSelf.reMenuBackgroundView removeGestureRecognizer:weakSelf.singleFingerTap];
  2386. }];
  2387. }
  2388. - (void)toggleReSelectMenu
  2389. {
  2390. if (appDelegate.reSelectMenu.isOpen) {
  2391. [appDelegate.reSelectMenu close];
  2392. } else {
  2393. [self createReSelectMenu];
  2394. [appDelegate.reSelectMenu showFromNavigationController:self.navigationController];
  2395. // Backgroun reMenu & (Gesture)
  2396. [self createReMenuBackgroundView:appDelegate.reSelectMenu];
  2397. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReSelectMenu)];
  2398. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2399. }
  2400. }
  2401. #pragma --------------------------------------------------------------------------------------------
  2402. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  2403. #pragma --------------------------------------------------------------------------------------------
  2404. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  2405. {
  2406. if (recognizer.state == UIGestureRecognizerStateBegan) {
  2407. CGPoint touchPoint = [recognizer locationInView:self.tableView];
  2408. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touchPoint];
  2409. if ([self indexPathIsValid:indexPath])
  2410. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2411. else
  2412. _metadata = nil;
  2413. [self becomeFirstResponder];
  2414. UIMenuController *menuController = [UIMenuController sharedMenuController];
  2415. UIMenuItem *copyFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)];
  2416. UIMenuItem *copyFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)];
  2417. UIMenuItem *openinFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)];
  2418. UIMenuItem *pasteFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)];
  2419. UIMenuItem *pasteFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)];
  2420. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, nil]];
  2421. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:self.tableView];
  2422. [menuController setMenuVisible:YES animated:YES];
  2423. }
  2424. }
  2425. - (BOOL)canBecomeFirstResponder
  2426. {
  2427. return YES;
  2428. }
  2429. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  2430. {
  2431. // For copy file, copy files, Open in ... :
  2432. //
  2433. // NO Directory
  2434. // NO Error Passcode
  2435. // NO In Session mode (download/upload)
  2436. // NO Template
  2437. if (@selector(copyFile:) == action || @selector(openinFile:) == action) {
  2438. if (_isSelectedMode == NO && _metadata && !_metadata.directory && _metadata.status == k_metadataStatusNormal) return YES;
  2439. else return NO;
  2440. }
  2441. if (@selector(copyFiles:) == action) {
  2442. if (_isSelectedMode) {
  2443. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2444. for (tableMetadata *metadata in selectedMetadatas) {
  2445. if (!metadata.directory && metadata.status == k_metadataStatusNormal)
  2446. return YES;
  2447. }
  2448. }
  2449. return NO;
  2450. }
  2451. if (@selector(pasteFile:) == action) {
  2452. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2453. NSArray *items = [pasteboard items];
  2454. if ([items count] == 1) {
  2455. // Value : (NSData) fileID
  2456. NSDictionary *dic = [items objectAtIndex:0];
  2457. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2458. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2459. if (fileID) {
  2460. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  2461. if (metadata) {
  2462. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", metadata.account]];
  2463. if (account) {
  2464. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2465. if (directoryUser)
  2466. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]])
  2467. return YES;
  2468. }
  2469. }
  2470. }
  2471. }
  2472. return NO;
  2473. }
  2474. if (@selector(pasteFiles:) == action) {
  2475. BOOL isValid = NO;
  2476. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2477. NSArray *items = [pasteboard items];
  2478. if ([items count] <= 1) return NO;
  2479. for (NSDictionary *dic in items) {
  2480. // Value : (NSData) fileID
  2481. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2482. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2483. if (fileID) {
  2484. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  2485. if (metadata) {
  2486. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", metadata.account]];
  2487. if (account) {
  2488. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2489. if (directoryUser) {
  2490. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]]) {
  2491. isValid = YES;
  2492. } else {
  2493. isValid = NO;
  2494. break;
  2495. }
  2496. } else {
  2497. isValid = NO;
  2498. break;
  2499. }
  2500. } else {
  2501. isValid = NO;
  2502. break;
  2503. }
  2504. } else {
  2505. isValid = NO;
  2506. break;
  2507. }
  2508. } else {
  2509. isValid = NO;
  2510. break;
  2511. }
  2512. }
  2513. return isValid;
  2514. }
  2515. return NO;
  2516. }
  2517. /************************************ COPY ************************************/
  2518. - (void)copyFile:(id)sender
  2519. {
  2520. // Remove all item
  2521. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2522. pasteboard.items = [[NSArray alloc] init];
  2523. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser,_metadata.fileID]]) {
  2524. [self copyFileToPasteboard:_metadata];
  2525. } else {
  2526. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2527. if (serverUrl) {
  2528. _metadata.session = k_download_session;
  2529. _metadata.sessionError = @"";
  2530. _metadata.sessionSelector = selectorLoadCopy;
  2531. _metadata.sessionSelectorPost = @"";
  2532. _metadata.status = k_metadataStatusWaitDownload;
  2533. // Add Metadata for Download
  2534. (void)[[NCManageDatabase sharedInstance] addMetadata:_metadata];
  2535. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  2536. }
  2537. }
  2538. }
  2539. - (void)copyFiles:(id)sender
  2540. {
  2541. // Remove all item
  2542. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2543. pasteboard.items = [[NSArray alloc] init];
  2544. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2545. for (tableMetadata *metadata in selectedMetadatas) {
  2546. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadata.fileID]]) {
  2547. [self copyFileToPasteboard:metadata];
  2548. } else {
  2549. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2550. if (serverUrl) {
  2551. metadata.session = k_download_session;
  2552. metadata.sessionError = @"";
  2553. metadata.sessionSelector = selectorLoadCopy;
  2554. metadata.sessionSelectorPost = @"";
  2555. metadata.status = k_metadataStatusWaitDownload;
  2556. // Add Metadata for Download
  2557. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  2558. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  2559. }
  2560. }
  2561. }
  2562. [self tableViewSelect:NO];
  2563. }
  2564. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  2565. {
  2566. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2567. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  2568. // Value : (NSData) fileID
  2569. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata.fileID], k_metadataKeyedUnarchiver,nil];
  2570. [items addObject:item];
  2571. [pasteboard setItems:items];
  2572. }
  2573. /************************************ OPEN IN ... ******************************/
  2574. - (void)openinFile:(id)sender
  2575. {
  2576. [self openIn:_metadata];
  2577. }
  2578. /************************************ PASTE ************************************/
  2579. - (void)pasteFile:(id)sender
  2580. {
  2581. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2582. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2583. }
  2584. - (void)pasteFiles:(id)sender
  2585. {
  2586. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2587. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2588. }
  2589. - (void)uploadFilePasteArray:(NSArray *)items cryptated:(BOOL)cryptated
  2590. {
  2591. float timer = 0;
  2592. for (NSDictionary *dic in items) {
  2593. // Value : (NSData) fileID
  2594. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2595. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2596. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  2597. if (metadata) {
  2598. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", metadata.account]];
  2599. if (account) {
  2600. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2601. if (directoryUser) {
  2602. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]]) {
  2603. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadata.fileNameView]];
  2604. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timer * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2605. tableMetadata *metadataForUpload = [tableMetadata new];
  2606. metadataForUpload.account = appDelegate.activeAccount;
  2607. metadataForUpload.date = [NSDate new];
  2608. metadataForUpload.directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:self.serverUrl];
  2609. metadataForUpload.fileID = [metadataForUpload.directoryID stringByAppendingString:metadata.fileName];
  2610. metadataForUpload.fileName = metadata.fileName;
  2611. metadataForUpload.fileNameView = metadata.fileNameView;
  2612. metadataForUpload.path = appDelegate.directoryUser;
  2613. metadataForUpload.session = k_upload_session;
  2614. metadataForUpload.sessionSelector = selectorUploadFile;
  2615. metadataForUpload.status = k_metadataStatusWaitUpload;
  2616. // Add Medtadata for upload
  2617. (void)[[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  2618. });
  2619. timer += 0.1;
  2620. }
  2621. }
  2622. }
  2623. }
  2624. }
  2625. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  2626. [self reloadDatasource];
  2627. }
  2628. #pragma --------------------------------------------------------------------------------------------
  2629. #pragma mark ===== Lock Passcode =====
  2630. #pragma --------------------------------------------------------------------------------------------
  2631. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  2632. {
  2633. return _failedAttempts;
  2634. }
  2635. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  2636. {
  2637. return _lockUntilDate;
  2638. }
  2639. - (void)passcodeViewCloseButtonPressed:(id)sender
  2640. {
  2641. [self dismissViewControllerAnimated:YES completion:nil];
  2642. }
  2643. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  2644. {
  2645. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  2646. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  2647. _lockUntilDate = nil;
  2648. _failedAttempts = 0;
  2649. aResultHandler(YES);
  2650. } else aResultHandler(NO);
  2651. } else aResultHandler(YES);
  2652. }
  2653. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  2654. {
  2655. [aViewController dismissViewControllerAnimated:YES completion:nil];
  2656. switch (aViewController.type) {
  2657. case BKPasscodeViewControllerCheckPasscodeType: {
  2658. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  2659. // possiamo procedere alla prossima directory
  2660. [self performSegueDirectoryWithControlPasscode:false];
  2661. // avviamo la sessione Passcode Lock con now
  2662. appDelegate.sessionePasscodeLock = [NSDate date];
  2663. }
  2664. // disattivazione lock cartella
  2665. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  2666. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2667. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2668. if (![[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:NO]) {
  2669. [appDelegate messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  2670. }
  2671. [self tableViewReloadData];
  2672. }
  2673. }
  2674. break;
  2675. default:
  2676. break;
  2677. }
  2678. }
  2679. - (void)comandoLockPassword
  2680. {
  2681. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2682. if (!serverUrl) return;
  2683. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2684. // se non è abilitato il Lock Passcode esci
  2685. if ([[CCUtility getBlockCode] length] == 0) {
  2686. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) preferredStyle:UIAlertControllerStyleAlert];
  2687. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  2688. [alertController addAction:okAction];
  2689. [self presentViewController:alertController animated:YES completion:nil];
  2690. return;
  2691. }
  2692. // se è richiesta la disattivazione si chiede la password
  2693. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  2694. if (directory.lock) {
  2695. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2696. viewController.delegate = self;
  2697. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  2698. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2699. viewController.inputViewTitlePassword = YES;
  2700. if ([CCUtility getSimplyBlockCode]) {
  2701. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2702. viewController.passcodeInputView.maximumLength = 6;
  2703. } else {
  2704. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2705. viewController.passcodeInputView.maximumLength = 64;
  2706. }
  2707. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  2708. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2709. viewController.touchIDManager = touchIDManager;
  2710. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  2711. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2712. viewController.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
  2713. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2714. [self presentViewController:navigationController animated:YES completion:nil];
  2715. return;
  2716. }
  2717. // ---------------- ACTIVATE PASSWORD
  2718. if ([[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:YES]) {
  2719. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  2720. if ([self indexPathIsValid:indexPath])
  2721. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2722. } else {
  2723. [appDelegate messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  2724. }
  2725. }
  2726. #pragma mark -
  2727. #pragma --------------------------------------------------------------------------------------------
  2728. #pragma mark ===== menu action : Favorite, More, Delete [swipe] =====
  2729. #pragma --------------------------------------------------------------------------------------------
  2730. - (BOOL)canOpenMenuAction:(tableMetadata *)metadata
  2731. {
  2732. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  2733. return NO;
  2734. if (metadata == nil || metadata.status != k_metadataStatusNormal)
  2735. return NO;
  2736. // E2EE
  2737. if (_metadataFolder.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount] == NO)
  2738. return NO;
  2739. return YES;
  2740. }
  2741. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell canSwipe:(MGSwipeDirection)direction
  2742. {
  2743. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2744. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2745. return [self canOpenMenuAction:metadata];
  2746. }
  2747. -(void)swipeTableCell:(nonnull MGSwipeTableCell *)cell didChangeSwipeState:(MGSwipeState)state gestureIsActive:(BOOL)gestureIsActive
  2748. {
  2749. }
  2750. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell tappedButtonAtIndex:(NSInteger)index direction:(MGSwipeDirection)direction fromExpansion:(BOOL)fromExpansion
  2751. {
  2752. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2753. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2754. if (direction == MGSwipeDirectionRightToLeft) {
  2755. [self actionDelete:indexPath];
  2756. }
  2757. if (direction == MGSwipeDirectionLeftToRight) {
  2758. if (_metadata.favorite)
  2759. [self removeFavorite:_metadata];
  2760. else
  2761. [self addFavorite:_metadata];
  2762. }
  2763. return YES;
  2764. }
  2765. - (void)actionDelete:(NSIndexPath *)indexPath
  2766. {
  2767. // Directory locked ?
  2768. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:[[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID] addFileName:_metadata.fileName];
  2769. if (!lockServerUrl) return;
  2770. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  2771. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", _metadata.fileID]];
  2772. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil) {
  2773. [appDelegate messageNotification:@"_error_" description:@"_folder_blocked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  2774. return;
  2775. }
  2776. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  2777. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  2778. [self performSelector:@selector(deleteFile) withObject:nil];
  2779. }]];
  2780. if (localFile || [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, _metadata.fileID]]) {
  2781. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_remove_local_file_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  2782. [self performSelector:@selector(removeLocalFile:) withObject:_metadata];
  2783. }]];
  2784. }
  2785. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2786. [alertController dismissViewControllerAnimated:YES completion:nil];
  2787. }]];
  2788. alertController.popoverPresentationController.sourceView = self.view;
  2789. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  2790. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  2791. [alertController.view layoutIfNeeded];
  2792. [self presentViewController:alertController animated:YES completion:nil];
  2793. }
  2794. - (void)actionMore:(UITapGestureRecognizer *)gestureRecognizer
  2795. {
  2796. CGPoint touch = [gestureRecognizer locationInView:self.tableView];
  2797. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touch];
  2798. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2799. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2800. if (!serverUrl) return;
  2801. NSString *titoloLock, *titleFavorite;
  2802. if (_metadata.favorite) {
  2803. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_remove_favorites_", nil)];
  2804. } else {
  2805. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_add_favorites_", nil)];
  2806. }
  2807. if (_metadata.directory) {
  2808. // calcolo lockServerUrl
  2809. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2810. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  2811. if (directory.lock)
  2812. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_remove_passcode_", nil)];
  2813. else
  2814. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_protect_passcode_", nil)];
  2815. }
  2816. // ******************************************* AHKActionSheet *******************************************
  2817. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.tabBarController.view title:nil];
  2818. actionSheet.animationDuration = 0.2;
  2819. actionSheet.buttonHeight = 50.0;
  2820. actionSheet.cancelButtonHeight = 50.0f;
  2821. actionSheet.separatorHeight = 5.0f;
  2822. actionSheet.automaticallyTintButtonImages = @(NO);
  2823. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].encrypted };
  2824. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  2825. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont boldSystemFontOfSize:17], NSForegroundColorAttributeName:[UIColor blackColor] };
  2826. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor darkGrayColor] };
  2827. actionSheet.separatorColor = [NCBrandColor sharedInstance].seperator;
  2828. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  2829. // ******************************************* DIRECTORY *******************************************
  2830. if (_metadata.directory) {
  2831. BOOL lockDirectory = NO;
  2832. NSString *dirServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2833. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:[NSString stringWithFormat:@"%@/%@", self.serverUrl, _metadata.fileName] account:appDelegate.activeAccount];
  2834. // Directory bloccata ?
  2835. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, dirServerUrl]];
  2836. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil) lockDirectory = YES;
  2837. [actionSheet addButtonWithTitle:_metadata.fileNameView
  2838. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder"] color:[NCBrandColor sharedInstance].brandElement]
  2839. backgroundColor:[NCBrandColor sharedInstance].tabBar
  2840. height:50.0
  2841. type:AHKActionSheetButtonTypeDisabled
  2842. handler:nil
  2843. ];
  2844. [actionSheet addButtonWithTitle: titleFavorite
  2845. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] color:[NCBrandColor sharedInstance].brandElement]
  2846. backgroundColor: [NCBrandColor sharedInstance].backgroundView
  2847. height: 50.0
  2848. type: AHKActionSheetButtonTypeDefault
  2849. handler: ^(AHKActionSheet *as) {
  2850. if (_metadata.favorite) [self removeFavorite:_metadata];
  2851. else [self addFavorite:_metadata];
  2852. }];
  2853. if (!lockDirectory && !isFolderEncrypted) {
  2854. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  2855. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"share"] color:[NCBrandColor sharedInstance].brandElement]
  2856. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2857. height:50.0
  2858. type:AHKActionSheetButtonTypeDefault
  2859. handler:^(AHKActionSheet *as) {
  2860. [self openWindowShare:_metadata];
  2861. }];
  2862. }
  2863. if (!([_metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES) && !lockDirectory && !_metadata.e2eEncrypted) {
  2864. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  2865. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"rename"] color:[NCBrandColor sharedInstance].brandElement]
  2866. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2867. height:50.0
  2868. type:AHKActionSheetButtonTypeDefault
  2869. handler:^(AHKActionSheet *as) {
  2870. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  2871. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  2872. textField.text = _metadata.fileNameView;
  2873. //textField.selectedTextRange = [textField textRangeFromPosition:textField.beginningOfDocument toPosition:textField.endOfDocument];
  2874. //textField.delegate = self;
  2875. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  2876. }];
  2877. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2878. NSLog(@"[LOG] Cancel action");
  2879. }];
  2880. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  2881. UITextField *fileName = alertController.textFields.firstObject;
  2882. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  2883. }];
  2884. okAction.enabled = NO;
  2885. [alertController addAction:cancelAction];
  2886. [alertController addAction:okAction];
  2887. [self presentViewController:alertController animated:YES completion:nil];
  2888. }];
  2889. }
  2890. if (!([_metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES) && !lockDirectory && !isFolderEncrypted) {
  2891. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  2892. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"move"] color:[NCBrandColor sharedInstance].brandElement]
  2893. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2894. height:50.0
  2895. type:AHKActionSheetButtonTypeDefault
  2896. handler:^(AHKActionSheet *as) {
  2897. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  2898. }];
  2899. }
  2900. [actionSheet addButtonWithTitle:NSLocalizedString(@"_delete_", nil)
  2901. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"delete"] color:[NCBrandColor sharedInstance].brandElement]
  2902. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2903. height:50.0
  2904. type:AHKActionSheetButtonTypeDefault
  2905. handler:^(AHKActionSheet *as) {
  2906. [self actionDelete:indexPath];
  2907. }];
  2908. if (!([_metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES)) {
  2909. [actionSheet addButtonWithTitle:NSLocalizedString(@"_folder_automatic_upload_", nil)
  2910. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderPhotos"] color:[NCBrandColor sharedInstance].brandElement]
  2911. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2912. height:50.0
  2913. type:AHKActionSheetButtonTypeDefault
  2914. handler:^(AHKActionSheet *as) {
  2915. // Settings new folder Automatatic upload
  2916. [[NCManageDatabase sharedInstance] setAccountAutoUploadFileName:_metadata.fileName];
  2917. [[NCManageDatabase sharedInstance] setAccountAutoUploadDirectory:serverUrl activeUrl:appDelegate.activeUrl];
  2918. // Clear data (old) Auto Upload
  2919. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:_autoUploadDirectory directoryID:nil];
  2920. [self readFolder:serverUrl];
  2921. }];
  2922. }
  2923. if (!([_metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES)) {
  2924. [actionSheet addButtonWithTitle:titoloLock
  2925. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"settingsPasscodeYES"] color:[NCBrandColor sharedInstance].brandElement]
  2926. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2927. height:50.0
  2928. type:AHKActionSheetButtonTypeDefault
  2929. handler:^(AHKActionSheet *as) {
  2930. [self performSelector:@selector(comandoLockPassword) withObject:nil];
  2931. }];
  2932. }
  2933. if (!_metadata.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  2934. [actionSheet addButtonWithTitle:NSLocalizedString(@"_e2e_set_folder_encrypted_", nil)
  2935. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"lock"] color:[NCBrandColor sharedInstance].encrypted]
  2936. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2937. height:50.0
  2938. type:AHKActionSheetButtonTypeEncrypted
  2939. handler:^(AHKActionSheet *as) {
  2940. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  2941. 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]];
  2942. dispatch_async(dispatch_get_main_queue(), ^{
  2943. if (error) {
  2944. [appDelegate messageNotification:@"_e2e_error_mark_folder_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  2945. } else {
  2946. [[NCManageDatabase sharedInstance] deleteE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, [NSString stringWithFormat:@"%@/%@", self.serverUrl, _metadata.fileName]]];
  2947. [self readFolder:self.serverUrl];
  2948. }
  2949. });
  2950. });
  2951. }];
  2952. }
  2953. if (_metadata.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  2954. [actionSheet addButtonWithTitle:NSLocalizedString(@"_e2e_remove_folder_encrypted_", nil)
  2955. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"lock"] color:[NCBrandColor sharedInstance].encrypted]
  2956. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2957. height:50.0
  2958. type:AHKActionSheetButtonTypeEncrypted
  2959. handler:^(AHKActionSheet *as) {
  2960. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  2961. 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]];
  2962. dispatch_async(dispatch_get_main_queue(), ^{
  2963. if (error) {
  2964. [appDelegate messageNotification:@"_e2e_error_delete_mark_folder_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  2965. } else {
  2966. [[NCManageDatabase sharedInstance] deleteE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, [NSString stringWithFormat:@"%@/%@", self.serverUrl, _metadata.fileName]]];
  2967. [self readFolder:self.serverUrl];
  2968. }
  2969. });
  2970. });
  2971. }];
  2972. }
  2973. [actionSheet show];
  2974. }
  2975. // ******************************************* FILE *******************************************
  2976. if (!_metadata.directory) {
  2977. UIImage *iconHeader;
  2978. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  2979. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, _metadata.fileID]])
  2980. iconHeader = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, _metadata.fileID]];
  2981. else
  2982. iconHeader = [UIImage imageNamed:_metadata.iconName];
  2983. [actionSheet addButtonWithTitle: _metadata.fileNameView
  2984. image: iconHeader
  2985. backgroundColor: [NCBrandColor sharedInstance].tabBar
  2986. height: 50.0
  2987. type: AHKActionSheetButtonTypeDisabled
  2988. handler: nil
  2989. ];
  2990. [actionSheet addButtonWithTitle: titleFavorite
  2991. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] color:[NCBrandColor sharedInstance].brandElement]
  2992. backgroundColor: [NCBrandColor sharedInstance].backgroundView
  2993. height: 50.0
  2994. type: AHKActionSheetButtonTypeDefault
  2995. handler: ^(AHKActionSheet *as) {
  2996. if (_metadata.favorite) [self removeFavorite:_metadata];
  2997. else [self addFavorite:_metadata];
  2998. }];
  2999. if (!_metadataFolder.e2eEncrypted) {
  3000. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3001. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"share"]color:[NCBrandColor sharedInstance].brandElement]
  3002. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  3003. height: 50.0
  3004. type:AHKActionSheetButtonTypeDefault
  3005. handler:^(AHKActionSheet *as) {
  3006. [self openWindowShare:_metadata];
  3007. }];
  3008. }
  3009. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil)
  3010. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"openFile"] color:[NCBrandColor sharedInstance].brandElement]
  3011. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  3012. height: 50.0
  3013. type:AHKActionSheetButtonTypeDefault
  3014. handler:^(AHKActionSheet *as) {
  3015. [self performSelector:@selector(openIn:) withObject:_metadata];
  3016. }];
  3017. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3018. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"rename"] color:[NCBrandColor sharedInstance].brandElement]
  3019. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  3020. height: 50.0
  3021. type:AHKActionSheetButtonTypeDefault
  3022. handler:^(AHKActionSheet *as) {
  3023. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  3024. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  3025. textField.text = _metadata.fileNameView;
  3026. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  3027. }];
  3028. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  3029. NSLog(@"[LOG] Cancel action");
  3030. }];
  3031. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  3032. UITextField *fileName = alertController.textFields.firstObject;
  3033. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  3034. }];
  3035. okAction.enabled = NO;
  3036. [alertController addAction:cancelAction];
  3037. [alertController addAction:okAction];
  3038. [self presentViewController:alertController animated:YES completion:nil];
  3039. }];
  3040. if (!_metadataFolder.e2eEncrypted) {
  3041. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3042. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"move"] color:[NCBrandColor sharedInstance].brandElement]
  3043. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  3044. height:50.0
  3045. type:AHKActionSheetButtonTypeDefault
  3046. handler:^(AHKActionSheet *as) {
  3047. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3048. }];
  3049. }
  3050. [actionSheet addButtonWithTitle:NSLocalizedString(@"_delete_", nil)
  3051. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"delete"] color:[NCBrandColor sharedInstance].brandElement]
  3052. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  3053. height:50.0
  3054. type:AHKActionSheetButtonTypeDefault
  3055. handler:^(AHKActionSheet *as) {
  3056. [self actionDelete:indexPath];
  3057. }];
  3058. [actionSheet show];
  3059. }
  3060. }
  3061. #pragma --------------------------------------------------------------------------------------------
  3062. #pragma mark - ==== Datasource ====
  3063. #pragma --------------------------------------------------------------------------------------------
  3064. - (void)clearDateReadDataSource:(NSNotification *)notification
  3065. {
  3066. _dateReadDataSource = Nil;
  3067. [self reloadDatasource];
  3068. }
  3069. - (void)reloadDatasource
  3070. {
  3071. [self reloadDatasource:_serverUrl];
  3072. }
  3073. - (void)reloadDatasource:(NSString *)serverUrl
  3074. {
  3075. // test
  3076. if (appDelegate.activeAccount.length == 0 || serverUrl.length == 0 || serverUrl == nil)
  3077. return;
  3078. // Search Mode
  3079. if (_isSearchMode) {
  3080. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:_searchResultMetadatas listProgressMetadata:nil groupByField:_directoryGroupBy activeAccount:appDelegate.activeAccount];
  3081. [self tableViewReloadData];
  3082. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  3083. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  3084. _noFilesSearchDescription = @"";
  3085. }
  3086. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  3087. _noFilesSearchTitle = @"";
  3088. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  3089. }
  3090. [self.tableView reloadEmptyDataSet];
  3091. return;
  3092. }
  3093. // Reload -> Self se non siamo nella dir appropriata cercala e se è in memoria reindirizza il reload
  3094. if ([serverUrl isEqualToString:_serverUrl] == NO || _serverUrl == nil) {
  3095. CCMain *main = [appDelegate.listMainVC objectForKey:serverUrl];
  3096. if (main) {
  3097. [main reloadDatasource];
  3098. } else {
  3099. [self tableViewReloadData];
  3100. [appDelegate.activeTransfers reloadDatasource];
  3101. }
  3102. return;
  3103. }
  3104. [appDelegate.activeTransfers reloadDatasource];
  3105. // Settaggio variabili per le ottimizzazioni
  3106. _directoryGroupBy = [CCUtility getGroupBySettings];
  3107. _directoryOrder = [CCUtility getOrderSettings];
  3108. // Remove optimization for encrypted directory
  3109. if (_metadataFolder.e2eEncrypted)
  3110. _dateReadDataSource = nil;
  3111. // current directoryID
  3112. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  3113. // Controllo data lettura Data Source
  3114. tableDirectory *tableDirectory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, serverUrl]];
  3115. // Get MetadataFolder
  3116. if (![serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]])
  3117. _metadataFolder = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND fileID == %@", appDelegate.activeAccount, tableDirectory.fileID]];
  3118. NSDate *dateDateRecordDirectory = tableDirectory.dateReadDirectory;
  3119. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  3120. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  3121. _dateReadDataSource = [NSDate date];
  3122. // Data Source
  3123. NSString *sorted = _directoryOrder;
  3124. if ([sorted isEqualToString:@"fileName"])
  3125. sorted = @"fileName";
  3126. if (directoryID) {
  3127. NSArray *recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND directoryID == %@ AND status != %i", appDelegate.activeAccount, directoryID, k_metadataStatusHide] sorted:sorted ascending:[CCUtility getAscendingSettings]];
  3128. _sectionDataSource = [CCSectionDataSourceMetadata new];
  3129. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:_directoryGroupBy activeAccount:appDelegate.activeAccount];
  3130. // get auto upload folder
  3131. _autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  3132. _autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:appDelegate.activeUrl];
  3133. }
  3134. } else {
  3135. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  3136. }
  3137. [self tableViewReloadData];
  3138. }
  3139. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  3140. {
  3141. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  3142. if (selectedRows.count > 0) {
  3143. for (NSIndexPath *selectionIndex in selectedRows) {
  3144. NSString *fileID = [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  3145. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3146. [metadatas addObject:metadata];
  3147. }
  3148. }
  3149. return metadatas;
  3150. }
  3151. - (tableMetadata *)getMetadataFromSectionDataSource:(NSIndexPath *)indexPath
  3152. {
  3153. NSInteger section = indexPath.section + 1;
  3154. NSInteger row = indexPath.row + 1;
  3155. NSInteger totSections = [_sectionDataSource.sections count] ;
  3156. if ((totSections < section) || (section > totSections)) {
  3157. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [0] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section]);
  3158. return nil;
  3159. }
  3160. id valueSection = [_sectionDataSource.sections objectAtIndex:indexPath.section];
  3161. NSArray *fileIDs = [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3162. if (fileIDs) {
  3163. NSInteger totRows =[fileIDs count] ;
  3164. if ((totRows < row) || (row > totRows)) {
  3165. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [1] : error row, totRows = %lu - row = %lu", (long)totRows, (long)row]);
  3166. return nil;
  3167. }
  3168. } else {
  3169. NSLog(@"[LOG] DEBUG [2] : fileIDs is NIL");
  3170. return nil;
  3171. }
  3172. NSString *fileID = [fileIDs objectAtIndex:indexPath.row];
  3173. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3174. return metadata;
  3175. }
  3176. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  3177. {
  3178. NSInteger totSections =[_sectionDataSource.sections count] ;
  3179. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  3180. return nil;
  3181. }
  3182. id valueSection = [_sectionDataSource.sections objectAtIndex:section];
  3183. return [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3184. }
  3185. #pragma --------------------------------------------------------------------------------------------
  3186. #pragma mark - ==== Table ====
  3187. #pragma --------------------------------------------------------------------------------------------
  3188. - (void)tableViewSelect:(BOOL)edit
  3189. {
  3190. // chiudiamo eventuali swipe aperti
  3191. if (edit)
  3192. [self.tableView setEditing:NO animated:NO];
  3193. [self.tableView setAllowsMultipleSelectionDuringEditing:edit];
  3194. [self.tableView setEditing:edit animated:YES];
  3195. _isSelectedMode = edit;
  3196. if (edit)
  3197. [self setUINavigationBarSelected];
  3198. else
  3199. [self setUINavigationBarDefault];
  3200. [_selectedFileIDsMetadatas removeAllObjects];
  3201. [self setTitle];
  3202. }
  3203. - (void)tableViewReloadData
  3204. {
  3205. // store selected cells before relod
  3206. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  3207. //store swipeOffset before relod
  3208. [_statusSwipeCell removeAllObjects];
  3209. for (MGSwipeTableCell *cell in self.tableView.visibleCells) {
  3210. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  3211. if (cell != nil && indexPath != nil)
  3212. [_statusSwipeCell setObject:[NSNumber numberWithDouble:cell.swipeOffset] forKey:indexPath];
  3213. }
  3214. // reload table view
  3215. [self.tableView reloadData];
  3216. // selected cells stored
  3217. for (NSIndexPath *path in indexPaths)
  3218. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  3219. [self setTableViewFooter];
  3220. if (self.tableView.editing)
  3221. [self setTitle];
  3222. }
  3223. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  3224. {
  3225. if (tableView.editing == 1) {
  3226. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3227. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  3228. return NO;
  3229. if (metadata == nil || metadata.status != k_metadataStatusNormal)
  3230. return NO;
  3231. else
  3232. return YES;
  3233. } else {
  3234. [_selectedFileIDsMetadatas removeAllObjects];
  3235. }
  3236. return YES;
  3237. }
  3238. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  3239. {
  3240. return 60;
  3241. }
  3242. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  3243. {
  3244. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  3245. }
  3246. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  3247. {
  3248. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  3249. }
  3250. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  3251. {
  3252. NSArray *sections = [_sectionDataSource.sectionArrayRow allKeys];
  3253. NSString *sectionTitle = [sections objectAtIndex:section];
  3254. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  3255. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  3256. if ([_directoryGroupBy isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  3257. return 20.f;
  3258. }
  3259. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  3260. {
  3261. float shift;
  3262. UIVisualEffectView *visualEffectView;
  3263. NSString *titleSection;
  3264. if (![self indexPathIsValid:[NSIndexPath indexPathForRow:0 inSection:section]])
  3265. return nil;
  3266. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]])
  3267. titleSection = [_sectionDataSource.sections objectAtIndex:section];
  3268. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]])
  3269. titleSection = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:section]];
  3270. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  3271. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  3272. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  3273. else titleSection = NSLocalizedString(titleSection,nil);
  3274. // Format title
  3275. NSString *currentDevice = [CCUtility currentDevice];
  3276. if ([currentDevice rangeOfString:@"iPad3"].location != NSNotFound) {
  3277. visualEffectView = [[UIVisualEffectView alloc] init];
  3278. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.3];
  3279. } else {
  3280. UIVisualEffect *blurEffect;
  3281. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  3282. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  3283. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.2];
  3284. }
  3285. if ([_directoryGroupBy isEqualToString:@"alphabetic"]) {
  3286. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  3287. shift = - 35;
  3288. else
  3289. shift = - 20;
  3290. } else shift = - 10;
  3291. // Title
  3292. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  3293. titleLabel.backgroundColor = [UIColor clearColor];
  3294. titleLabel.textColor = [UIColor blackColor];
  3295. titleLabel.font = [UIFont systemFontOfSize:12];
  3296. titleLabel.textAlignment = NSTextAlignmentLeft;
  3297. titleLabel.text = titleSection;
  3298. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3299. [visualEffectView.contentView addSubview:titleLabel];
  3300. // Elements
  3301. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  3302. elementLabel.backgroundColor = [UIColor clearColor];
  3303. elementLabel.textColor = [UIColor blackColor];;
  3304. elementLabel.font = [UIFont systemFontOfSize:12];
  3305. elementLabel.textAlignment = NSTextAlignmentRight;
  3306. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3307. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  3308. NSUInteger rowsCount = [metadatas count];
  3309. if (rowsCount == 0) return nil;
  3310. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  3311. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  3312. [visualEffectView.contentView addSubview:elementLabel];
  3313. return visualEffectView;
  3314. }
  3315. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  3316. {
  3317. return [_sectionDataSource.sections indexOfObject:title];
  3318. }
  3319. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  3320. {
  3321. if ([_directoryGroupBy isEqualToString:@"alphabetic"])
  3322. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  3323. else
  3324. return nil;
  3325. }
  3326. /*
  3327. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  3328. {
  3329. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  3330. }
  3331. }
  3332. */
  3333. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  3334. {
  3335. NSString *typeCell;
  3336. NSString *dataFile;
  3337. NSString *lunghezzaFile;
  3338. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3339. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  3340. return [tableView dequeueReusableCellWithIdentifier:@"CellMain"];
  3341. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  3342. if (!serverUrl)
  3343. return [tableView dequeueReusableCellWithIdentifier:@"CellMain"];
  3344. if (metadata.status == k_metadataStatusNormal) typeCell = @"CellMain";
  3345. else typeCell = @"CellMainTransfer";
  3346. CCCellMainTransfer *cell = (CCCellMainTransfer *)[tableView dequeueReusableCellWithIdentifier:typeCell forIndexPath:indexPath];
  3347. // variable base
  3348. cell.delegate = self;
  3349. cell.indexPath = indexPath;
  3350. // separator
  3351. cell.separatorInset = UIEdgeInsetsMake(0.f, 60.f, 0.f, 0.f);
  3352. // change color selection
  3353. UIView *selectionColor = [[UIView alloc] init];
  3354. selectionColor.backgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  3355. cell.selectedBackgroundView = selectionColor;
  3356. // for checkmark color in editing mode
  3357. cell.tintColor = [NCBrandColor sharedInstance].brandElement;
  3358. if ([typeCell isEqualToString:@"CellMain"]) cell.backgroundColor = [NCBrandColor sharedInstance].backgroundView;
  3359. if ([typeCell isEqualToString:@"CellMainTransfer"]) cell.backgroundColor = [NCBrandColor sharedInstance].transferBackground;
  3360. // ----------------------------------------------------------------------------------------------------------
  3361. // DEFAULT
  3362. // ----------------------------------------------------------------------------------------------------------
  3363. cell.file.image = nil;
  3364. cell.status.image = nil;
  3365. cell.favorite.image = nil;
  3366. cell.shared.image = nil;
  3367. cell.local.image = nil;
  3368. cell.imageTitleSegue = nil;
  3369. cell.labelTitle.enabled = YES;
  3370. cell.labelTitle.text = @"";
  3371. cell.labelInfoFile.enabled = YES;
  3372. cell.labelInfoFile.text = @"";
  3373. cell.progressView.progress = 0.0;
  3374. cell.progressView.hidden = YES;
  3375. cell.cancelTaskButton.hidden = YES;
  3376. cell.reloadTaskButton.hidden = YES;
  3377. cell.stopTaskButton.hidden = YES;
  3378. cell.labelTitle.textColor = [UIColor blackColor];
  3379. // ----------------------------------------------------------------------------------------------------------
  3380. // File Name & Folder
  3381. // ----------------------------------------------------------------------------------------------------------
  3382. // nome del file
  3383. cell.labelTitle.text = metadata.fileNameView;
  3384. // è una directory
  3385. if (metadata.directory) {
  3386. // cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  3387. cell.accessoryType = UITableViewCellAccessoryNone;
  3388. cell.labelInfoFile.text = [CCUtility dateDiff:metadata.date];
  3389. lunghezzaFile = @" ";
  3390. // ----------------------------------------------------------------------------------------------------------
  3391. // Favorite Folder
  3392. // ----------------------------------------------------------------------------------------------------------
  3393. if (metadata.favorite) {
  3394. cell.favorite.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] color:[NCBrandColor sharedInstance].yellowFavorite];
  3395. }
  3396. } else {
  3397. // File
  3398. dataFile = [CCUtility dateDiff:metadata.date];
  3399. lunghezzaFile = [CCUtility transformedSize:metadata.size];
  3400. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  3401. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  3402. [dateFormatter setDateStyle:NSDateFormatterShortStyle];
  3403. [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
  3404. if (localFile && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadata.fileID]])
  3405. cell.local.image = [UIImage imageNamed:@"local"];
  3406. else
  3407. cell.local.image = nil;
  3408. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ %@", dataFile, lunghezzaFile];
  3409. cell.accessoryType = UITableViewCellAccessoryNone;
  3410. }
  3411. // ----------------------------------------------------------------------------------------------------------
  3412. // File Image View
  3413. // ----------------------------------------------------------------------------------------------------------
  3414. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3415. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, metadata.fileID]]) {
  3416. cell.file.image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, metadata.fileID]];
  3417. } else {
  3418. if (metadata.directory) {
  3419. if (metadata.e2eEncrypted) {
  3420. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderEncrypted"] color:[NCBrandColor sharedInstance].brandElement];
  3421. cell.imageTitleSegue = [UIImage imageNamed:@"lock"];
  3422. } else if ([metadata.fileName isEqualToString:_autoUploadFileName] && [self.serverUrl isEqualToString:_autoUploadDirectory]) {
  3423. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderPhotos"] color:[NCBrandColor sharedInstance].brandElement];
  3424. cell.imageTitleSegue = [UIImage imageNamed:@"photos"];
  3425. } else
  3426. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder"] color:[NCBrandColor sharedInstance].brandElement];
  3427. } else {
  3428. cell.file.image = [UIImage imageNamed:metadata.iconName];
  3429. }
  3430. if (metadata.thumbnailExists && _metadataFolder.e2eEncrypted == NO)
  3431. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  3432. }
  3433. // ----------------------------------------------------------------------------------------------------------
  3434. // Image Status Lock Passcode
  3435. // ----------------------------------------------------------------------------------------------------------
  3436. // Directory con passcode lock attivato
  3437. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName];
  3438. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  3439. if (metadata.directory && (directory.lock && [[CCUtility getBlockCode] length]))
  3440. cell.status.image = [UIImage imageNamed:@"passcode"];
  3441. // ----------------------------------------------------------------------------------------------------------
  3442. // E2EE Image Status Encrypted
  3443. // ----------------------------------------------------------------------------------------------------------
  3444. if (_metadataFolder.e2eEncrypted && !metadata.directory) {
  3445. tableE2eEncryption *tableE2eEncryption = [[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND fileNameIdentifier == %@", appDelegate.activeAccount, metadata.fileName]];
  3446. if (tableE2eEncryption)
  3447. cell.status.image = [UIImage imageNamed:@"encrypted"];
  3448. }
  3449. // ----------------------------------------------------------------------------------------------------------
  3450. // Favorite
  3451. // ----------------------------------------------------------------------------------------------------------
  3452. if (metadata.favorite) {
  3453. cell.favorite.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] color:[NCBrandColor sharedInstance].yellowFavorite];
  3454. }
  3455. // ----------------------------------------------------------------------------------------------------------
  3456. // Share
  3457. // ----------------------------------------------------------------------------------------------------------
  3458. NSString *shareLink = [appDelegate.sharesLink objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3459. NSString *shareUserAndGroup = [appDelegate.sharesUserAndGroup objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3460. BOOL isShare = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_shared].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_shared].location == NSNotFound);
  3461. BOOL isMounted = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_mounted].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_mounted].location == NSNotFound);
  3462. // Aggiungiamo il Tap per le shared
  3463. if (isShare || [shareLink length] > 0 || [shareUserAndGroup length] > 0 || isMounted) {
  3464. // Shared with you
  3465. if (isShare) {
  3466. if (metadata.directory) {
  3467. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brandElement];
  3468. cell.imageTitleSegue = [UIImage imageNamed:@"share"];
  3469. cell.accessoryType = UITableViewCellAccessoryNone;
  3470. }
  3471. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"share"] color:[NCBrandColor sharedInstance].gray];
  3472. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3473. [tap setNumberOfTapsRequired:1];
  3474. cell.shared.userInteractionEnabled = YES;
  3475. [cell.shared addGestureRecognizer:tap];
  3476. }
  3477. // Mounted with you
  3478. if (isMounted) {
  3479. if (metadata.directory) {
  3480. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_external"] color:[NCBrandColor sharedInstance].brandElement];
  3481. cell.imageTitleSegue = [UIImage imageNamed:@"shareMounted"];
  3482. cell.accessoryType = UITableViewCellAccessoryNone;
  3483. }
  3484. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareMounted"] color:[NCBrandColor sharedInstance].gray];
  3485. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3486. [tap setNumberOfTapsRequired:1];
  3487. cell.shared.userInteractionEnabled = YES;
  3488. [cell.shared addGestureRecognizer:tap];
  3489. }
  3490. // You share
  3491. if ([shareLink length] > 0 || [shareUserAndGroup length] > 0) {
  3492. if (metadata.directory) {
  3493. if ([shareUserAndGroup length] > 0) {
  3494. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brandElement];
  3495. cell.imageTitleSegue = [UIImage imageNamed:@"share"];
  3496. } if ([shareLink length] > 0) {
  3497. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_public"] color:[NCBrandColor sharedInstance].brandElement];
  3498. cell.imageTitleSegue = [UIImage imageNamed:@"sharebylink"];
  3499. }
  3500. cell.shared.userInteractionEnabled = NO;
  3501. } else {
  3502. if ([shareLink length] > 0) {
  3503. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"sharebylink"] color:[NCBrandColor sharedInstance].gray];
  3504. } if ([shareUserAndGroup length] > 0) {
  3505. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"share"] color:[NCBrandColor sharedInstance].gray];
  3506. }
  3507. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  3508. [tap setNumberOfTapsRequired:1];
  3509. cell.shared.userInteractionEnabled = YES;
  3510. [cell.shared addGestureRecognizer:tap];
  3511. }
  3512. }
  3513. } else {
  3514. cell.shared.userInteractionEnabled = NO;
  3515. }
  3516. // ----------------------------------------------------------------------------------------------------------
  3517. // downloadFile
  3518. // ----------------------------------------------------------------------------------------------------------
  3519. if (metadata.status == k_metadataStatusWaitDownload || metadata.status == k_metadataStatusInDownload || metadata.status == k_metadataStatusDownloading || metadata.status == k_metadataStatusDownloadError) {
  3520. cell.status.image = [UIImage imageNamed:@"statusdownload"];
  3521. [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3522. cell.cancelTaskButton.hidden = NO;
  3523. [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3524. cell.reloadTaskButton.hidden = NO;
  3525. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3526. float progress = [[appDelegate.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3527. if (progress > 0) {
  3528. cell.progressView.progressTintColor = [UIColor blackColor];
  3529. cell.progressView.progress = progress;
  3530. cell.progressView.hidden = NO;
  3531. }
  3532. }
  3533. // ----------------------------------------------------------------------------------------------------------
  3534. // downloadFile Error
  3535. // ----------------------------------------------------------------------------------------------------------
  3536. if (metadata.status == k_metadataStatusDownloadError) {
  3537. cell.status.image = [UIImage imageNamed:@"statuserror"];
  3538. if ([metadata.sessionError length] == 0) {
  3539. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_downloaded_",nil)];
  3540. } else {
  3541. cell.labelInfoFile.text = metadata.sessionError;
  3542. }
  3543. }
  3544. // ----------------------------------------------------------------------------------------------------------
  3545. // uploadFile
  3546. // ----------------------------------------------------------------------------------------------------------
  3547. if (metadata.status == k_metadataStatusWaitUpload || metadata.status == k_metadataStatusInUpload || metadata.status == k_metadataStatusUploading || metadata.status == k_metadataStatusUploadError) {
  3548. cell.status.image = [UIImage imageNamed:@"statusupload"];
  3549. [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"removetask"] forState:UIControlStateNormal];
  3550. cell.cancelTaskButton.hidden = NO;
  3551. if (metadata.sessionTaskIdentifier == k_taskIdentifierStop) {
  3552. [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3553. cell.status.image = [UIImage imageNamed:@"statusstop"];
  3554. cell.reloadTaskButton.hidden = NO;
  3555. cell.stopTaskButton.hidden = YES;
  3556. } else {
  3557. [cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3558. cell.stopTaskButton.hidden = NO;
  3559. cell.reloadTaskButton.hidden = YES;
  3560. }
  3561. // se non c'è una preview in bianconero metti l'immagine di default
  3562. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, metadata.fileID]] == NO)
  3563. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"uploadCloud"] color:[NCBrandColor sharedInstance].brandElement];
  3564. cell.labelTitle.enabled = NO;
  3565. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3566. float progress = [[appDelegate.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3567. if (progress > 0) {
  3568. cell.progressView.progressTintColor = [UIColor blackColor];
  3569. cell.progressView.progress = progress;
  3570. cell.progressView.hidden = NO;
  3571. }
  3572. }
  3573. // ----------------------------------------------------------------------------------------------------------
  3574. // uploadFileError
  3575. // ----------------------------------------------------------------------------------------------------------
  3576. if (metadata.status == k_metadataStatusUploadError) {
  3577. cell.labelTitle.enabled = NO;
  3578. cell.status.image = [UIImage imageNamed:@"statuserror"];
  3579. if ([metadata.sessionError length] == 0) {
  3580. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_uploaded_",nil)];
  3581. } else {
  3582. cell.labelInfoFile.text = metadata.sessionError;
  3583. }
  3584. }
  3585. [cell.reloadTaskButton addTarget:self action:@selector(reloadTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3586. [cell.cancelTaskButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3587. [cell.stopTaskButton addTarget:self action:@selector(stopTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3588. UILongPressGestureRecognizer *cancelLongGesture = [UILongPressGestureRecognizer new];
  3589. [cancelLongGesture addTarget:self action:@selector(cancelAllTask:)];
  3590. [cell.cancelTaskButton addGestureRecognizer:cancelLongGesture];
  3591. // ----------------------------------------------------------------------------------------------------------
  3592. // swipe
  3593. // ----------------------------------------------------------------------------------------------------------
  3594. // LEFT
  3595. cell.leftButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] color:[UIColor whiteColor]] backgroundColor:[NCBrandColor sharedInstance].yellowFavorite padding:25]];
  3596. cell.leftExpansion.buttonIndex = 0;
  3597. cell.leftExpansion.fillOnTrigger = NO;
  3598. //centerIconOverText
  3599. MGSwipeButton *favoriteButton = (MGSwipeButton *)[cell.leftButtons objectAtIndex:0];
  3600. [favoriteButton centerIconOverText];
  3601. // RIGHT
  3602. cell.rightButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"delete"] color:[UIColor whiteColor]] backgroundColor:[UIColor redColor] padding:25]];
  3603. cell.rightExpansion.buttonIndex = 0;
  3604. cell.rightExpansion.fillOnTrigger = NO;
  3605. //centerIconOverText
  3606. MGSwipeButton *deleteButton = (MGSwipeButton *)[cell.rightButtons objectAtIndex:0];
  3607. [deleteButton centerIconOverText];
  3608. //restore swipeOffset after relod
  3609. CGFloat swipeOffset = [[_statusSwipeCell objectForKey:indexPath] doubleValue];
  3610. if (swipeOffset < 0) {
  3611. [cell showSwipe:MGSwipeDirectionRightToLeft animated:NO];
  3612. [_statusSwipeCell removeObjectForKey:indexPath];
  3613. } else if (swipeOffset > 0) {
  3614. [cell showSwipe:MGSwipeDirectionLeftToRight animated:NO];
  3615. [_statusSwipeCell removeObjectForKey:indexPath];
  3616. }
  3617. // ----------------------------------------------------------------------------------------------------------
  3618. // more
  3619. // ----------------------------------------------------------------------------------------------------------
  3620. cell.more.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"more"] color:[NCBrandColor sharedInstance].gray];
  3621. if ([self canOpenMenuAction:metadata]) {
  3622. UITapGestureRecognizer *tapMore = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionMore:)];
  3623. [tapMore setNumberOfTapsRequired:1];
  3624. cell.more.userInteractionEnabled = YES;
  3625. [cell.more addGestureRecognizer:tapMore];
  3626. }
  3627. return cell;
  3628. }
  3629. - (void)setTableViewFooter
  3630. {
  3631. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3632. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3633. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3634. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3635. UIFont *appFont = [UIFont systemFontOfSize:12];
  3636. footerLabel.font = appFont;
  3637. footerLabel.textColor = [UIColor grayColor];
  3638. footerLabel.backgroundColor = [UIColor clearColor];
  3639. footerLabel.textAlignment = NSTextAlignmentCenter;
  3640. NSString *folders;
  3641. NSString *files;
  3642. NSString *footerText;
  3643. if (_sectionDataSource.directories > 1) {
  3644. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  3645. } else if (_sectionDataSource.directories == 1){
  3646. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  3647. } else {
  3648. folders = @"";
  3649. }
  3650. if (_sectionDataSource.files > 1) {
  3651. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3652. } else if (_sectionDataSource.files == 1){
  3653. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3654. } else {
  3655. files = @"";
  3656. }
  3657. if ([folders isEqualToString:@""]) {
  3658. footerText = files;
  3659. } else if ([files isEqualToString:@""]) {
  3660. footerText = folders;
  3661. } else {
  3662. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  3663. }
  3664. footerLabel.text = footerText;
  3665. [footerView addSubview:footerLabel];
  3666. [self.tableView setTableFooterView:footerView];
  3667. }
  3668. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  3669. {
  3670. CCCellMain *cell = [tableView cellForRowAtIndexPath:indexPath];
  3671. // settiamo il record file.
  3672. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3673. if (!_metadata)
  3674. return;
  3675. // se non può essere selezionata deseleziona
  3676. if ([cell isEditing] == NO)
  3677. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  3678. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  3679. if (self.tableView.editing) {
  3680. [_selectedFileIDsMetadatas setObject:_metadata forKey:_metadata.fileID];
  3681. [self setTitle];
  3682. return;
  3683. }
  3684. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3685. if (!serverUrl) return;
  3686. // se è in corso una sessione
  3687. if (_metadata.status != k_metadataStatusNormal)
  3688. return;
  3689. // file
  3690. if (_metadata.directory == NO) {
  3691. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  3692. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, _metadata.fileID]]) {
  3693. [self downloadFileSuccessFailure:_metadata.fileName fileID:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:@"" errorMessage:@"" errorCode:0];
  3694. } else {
  3695. if (_metadataFolder.e2eEncrypted && ![CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  3696. [appDelegate messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  3697. } else {
  3698. _metadata.session = k_download_session;
  3699. _metadata.sessionError = @"";
  3700. _metadata.sessionSelector = selectorLoadFileView;
  3701. _metadata.sessionSelectorPost = @"";
  3702. _metadata.status = k_metadataStatusWaitDownload;
  3703. // Add Metadata for Download
  3704. (void)[[NCManageDatabase sharedInstance] addMetadata:_metadata];
  3705. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  3706. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  3707. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  3708. }
  3709. }
  3710. }
  3711. if (_metadata.directory) {
  3712. imageTitleSegue = cell.imageTitleSegue;
  3713. [self performSegueDirectoryWithControlPasscode:true];
  3714. }
  3715. }
  3716. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  3717. {
  3718. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3719. [_selectedFileIDsMetadatas removeObjectForKey:metadata.fileID];
  3720. [self setTitle];
  3721. }
  3722. - (BOOL)indexPathIsValid:(NSIndexPath *)indexPath
  3723. {
  3724. if (!indexPath)
  3725. return NO;
  3726. NSInteger section = indexPath.section;
  3727. NSInteger row = indexPath.row;
  3728. NSInteger lastSectionIndex = [self numberOfSectionsInTableView:self.tableView] - 1;
  3729. if (section > lastSectionIndex || lastSectionIndex < 0)
  3730. return NO;
  3731. NSInteger rowCount = [self.tableView numberOfRowsInSection:indexPath.section] - 1;
  3732. if (rowCount < 0)
  3733. return NO;
  3734. return row <= rowCount;
  3735. }
  3736. #pragma --------------------------------------------------------------------------------------------
  3737. #pragma mark ===== Navigation ====
  3738. #pragma --------------------------------------------------------------------------------------------
  3739. - (BOOL)shouldPerformSegue
  3740. {
  3741. // if background return
  3742. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return NO;
  3743. if (self.view.window == NO)
  3744. return NO;
  3745. // Collapsed ma siamo già in detail esci
  3746. if (self.splitViewController.isCollapsed)
  3747. if (_detailViewController.isViewLoaded && _detailViewController.view.window) return NO;
  3748. return YES;
  3749. }
  3750. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  3751. {
  3752. id viewController = segue.destinationViewController;
  3753. NSMutableArray *allRecordsDataSourceImagesVideos = [NSMutableArray new];
  3754. tableMetadata *metadata;
  3755. if ([viewController isKindOfClass:[UINavigationController class]]) {
  3756. UINavigationController *nav = viewController;
  3757. _detailViewController = (CCDetail *)nav.topViewController;
  3758. } else {
  3759. _detailViewController = segue.destinationViewController;
  3760. }
  3761. if ([sender isKindOfClass:[tableMetadata class]]) {
  3762. metadata = sender;
  3763. [allRecordsDataSourceImagesVideos addObject:sender];
  3764. } else {
  3765. metadata = _metadata;
  3766. for (NSString *fileID in _sectionDataSource.allEtag) {
  3767. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3768. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video] || [metadata.typeFile isEqualToString: k_metadataTypeFile_audio])
  3769. [allRecordsDataSourceImagesVideos addObject:metadata];
  3770. }
  3771. }
  3772. _detailViewController.metadataDetail = metadata;
  3773. _detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  3774. _detailViewController.dateFilterQuery = nil;
  3775. [_detailViewController setTitle:metadata.fileNameView];
  3776. }
  3777. // can i go to next viewcontroller
  3778. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode
  3779. {
  3780. NSString *nomeDir;
  3781. if (self.tableView.editing == NO) {
  3782. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3783. if (!serverUrl) return;
  3784. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  3785. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  3786. // 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
  3787. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil && controlPasscode) {
  3788. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  3789. viewController.delegate = self;
  3790. viewController.fromType = CCBKPasscodeFromLockDirectory;
  3791. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  3792. viewController.inputViewTitlePassword = YES;
  3793. if ([CCUtility getSimplyBlockCode]) {
  3794. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  3795. viewController.passcodeInputView.maximumLength = 6;
  3796. } else {
  3797. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  3798. viewController.passcodeInputView.maximumLength = 64;
  3799. }
  3800. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  3801. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  3802. viewController.touchIDManager = touchIDManager;
  3803. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  3804. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  3805. viewController.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
  3806. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  3807. [self presentViewController:navController animated:YES completion:nil];
  3808. return;
  3809. }
  3810. // E2EE Check enable
  3811. if (_metadata.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount] == NO) {
  3812. [appDelegate messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  3813. return;
  3814. }
  3815. nomeDir = _metadata.fileName;
  3816. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:serverUrl addFileName:nomeDir];
  3817. CCMain *viewController = [appDelegate.listMainVC objectForKey:serverUrlPush];
  3818. if (!viewController) {
  3819. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMain"];
  3820. viewController.serverUrl = serverUrlPush;
  3821. viewController.titleMain = _metadata.fileName;
  3822. viewController.textBackButton = _titleMain;
  3823. viewController.imageTitle = imageTitleSegue;
  3824. // save self
  3825. [appDelegate.listMainVC setObject:viewController forKey:serverUrlPush];
  3826. [self.navigationController pushViewController:viewController animated:YES];
  3827. } else {
  3828. if (viewController.isViewLoaded) {
  3829. // Icon Title
  3830. viewController.imageTitle = imageTitleSegue;
  3831. // Fix : Application tried to present modally an active controller
  3832. if ([self.navigationController isBeingPresented]) {
  3833. // being presented
  3834. } else if ([self.navigationController isMovingToParentViewController]) {
  3835. // being pushed
  3836. } else {
  3837. [self.navigationController pushViewController:viewController animated:YES];
  3838. }
  3839. }
  3840. }
  3841. }
  3842. }
  3843. @end