CCMain.m 229 KB

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