﻿// Decompiled with JetBrains decompiler
// Type: InvokedServer.Networking.UPnPService
// Assembly: HQ, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: C53BC0E5-A85B-41E9-8105-FC74ED122A9A
// Assembly location: C:\Users\ian\Downloads\Telegram Desktop\fein\HQ.exe

using Open.Nat;
using System;
using System.Collections.Generic;
using System.Threading;


namespace InvokedServer.Networking
{
	public class UPnPService
	{
		private readonly Dictionary<int, Mapping> _mappings = new Dictionary<int, Mapping>();
		private NatDevice _device;
		private NatDiscoverer _discoverer;

		public UPnPService() => this._discoverer = new NatDiscoverer();

		public async void CreatePortMapAsync(int port)
		{
			try
			{
				this._device = await this._discoverer.DiscoverDeviceAsync(PortMapper.Upnp, new CancellationTokenSource(10000));
				Mapping mapping = new Mapping(Protocol.Tcp, port, port);
				await this._device.CreatePortMapAsync(mapping);
				if (this._mappings.ContainsKey(mapping.PrivatePort))
					this._mappings[mapping.PrivatePort] = mapping;
				else
					this._mappings.Add(mapping.PrivatePort, mapping);
				mapping = (Mapping)null;
			}
			catch (Exception ex) when (ex is MappingException || ex is NatDeviceNotFoundException)
			{
			}
		}

		public async void DeletePortMapAsync(int port)
		{
			Mapping mapping;
			if (!this._mappings.TryGetValue(port, out mapping))
			{
				mapping = (Mapping)null;
			}
			else
			{
				try
				{
					await this._device.DeletePortMapAsync(mapping);
					this._mappings.Remove(mapping.PrivatePort);
					mapping = (Mapping)null;
				}
				catch (Exception ex) when (ex is MappingException || ex is NatDeviceNotFoundException)
				{
					mapping = (Mapping)null;
				}
			}
		}
	}
}