CCMain.m 226 KB

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