CCMain.m 229 KB

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