11/*
2- * Copyright (c) 2020 Proton Technologies AG
2+ * Copyright (c) 2021 Proton Technologies AG
33 *
44 * This file is part of ProtonVPN.
55 *
1818 */
1919
2020using System . Collections . Generic ;
21- using System . Linq ;
2221using ProtonVPN . Core . Servers . Models ;
2322using ProtonVPN . Core . Servers . Specs ;
24- using ProtonVPN . Core . Settings ;
2523
2624namespace ProtonVPN . Core . Servers
2725{
2826 public class ServerCandidates
2927 {
3028 private readonly ServerManager _serverManager ;
31- private readonly IUserStorage _userStorage ;
3229
33- public ServerCandidates ( ServerManager serverManager , IUserStorage userStorage , IReadOnlyCollection < Server > items )
30+ public ServerCandidates ( ServerManager serverManager , IReadOnlyCollection < Server > items )
3431 {
3532 _serverManager = serverManager ;
36- _userStorage = userStorage ;
3733 Items = items ;
3834 }
3935
4036 public IReadOnlyCollection < Server > Items { get ; }
4137
42- public Server ServerByEntryIp ( string ip )
38+ public Server ServerByEntryIpAndLabel ( string entryIp , string label )
4339 {
44- if ( string . IsNullOrEmpty ( ip ) )
40+ if ( string . IsNullOrEmpty ( entryIp ) )
41+ {
4542 return Server . Empty ( ) ;
43+ }
4644
47- var maxTier = _userStorage . User ( ) . MaxTier ;
48- var servers = Items . Where ( l => l . Servers . Any ( p => p . EntryIp == ip ) ) ;
49- var server = FirstByUserTier ( servers , maxTier ) ;
50- if ( server != null )
51- return WithExitIp ( server , ip ) ;
52-
53- servers = _serverManager . GetServers ( new ServerByEntryIp ( ip ) ) ;
54- server = FirstByUserTier ( servers , maxTier ) ;
55- return WithExitIp ( server ?? Server . Empty ( ) , ip ) ;
56- }
57-
58- private Server FirstByUserTier ( IEnumerable < Server > servers , sbyte maxTier )
59- {
60- return servers
61- . OrderByDescending ( s => s . Tier <= maxTier ? s . Tier : - 1 )
62- . FirstOrDefault ( ) ;
63- }
64-
65- private Server WithExitIp ( Server server , string entryIp )
66- {
67- var result = server . Clone ( ) ;
45+ IReadOnlyCollection < Server > servers = Items == null || Items . Count == 0
46+ ? _serverManager . GetServers ( new ServerByEntryIp ( entryIp ) )
47+ : Items ;
6848
69- var physical = server . Servers . FirstOrDefault ( p => p . EntryIp == entryIp ) ;
70- if ( physical != null )
49+ foreach ( Server server in servers )
7150 {
72- result . ExitIp = physical . ExitIp ;
51+ foreach ( PhysicalServer physicalServer in server . Servers )
52+ {
53+ if ( entryIp == physicalServer . EntryIp && ( string . IsNullOrEmpty ( label ) || label == physicalServer . Label ) )
54+ {
55+ Server clone = server . Clone ( ) ;
56+ clone . ExitIp = physicalServer . ExitIp ;
57+ return clone ;
58+ }
59+ }
7360 }
7461
75- return result ;
62+ return Server . Empty ( ) ;
7663 }
7764 }
78- }
65+ }
0 commit comments