Skip to content

Support shortened URLs and straight to settings #86

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
5 changes: 3 additions & 2 deletions BrowserSelect/Browser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -233,12 +233,13 @@ private static List<Browser> find(RegistryKey hklm)
icon = icon2String(IconExtractor.fromFile(exec))
});
}
catch (NullReferenceException)
catch (NullReferenceException ex)
{
System.Diagnostics.Debug.WriteLine(ex);
} // incomplete registry record for browser, ignore it
catch (Exception ex)
{
// todo: log errors
System.Diagnostics.Debug.WriteLine(ex);
}
}
return browsers;
Expand Down
31 changes: 28 additions & 3 deletions BrowserSelect/BrowserSelect.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>BrowserSelect</RootNamespace>
<AssemblyName>BrowserSelect</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
Expand All @@ -21,6 +22,7 @@
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
Expand All @@ -30,16 +32,21 @@
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup>
<ApplicationIcon>bs.ico</ApplicationIcon>
</PropertyGroup>
<ItemGroup>
<Reference Include="Newtonsoft.Json, Version=11.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.11.0.2\lib\net40\Newtonsoft.Json.dll</HintPath>
<Reference Include="Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.13.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.ValueTuple, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.ValueTuple.4.5.0\lib\net47\System.ValueTuple.dll</HintPath>
</Reference>
<Reference Include="System.Web" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
Expand Down Expand Up @@ -70,6 +77,18 @@
<Compile Include="Form1.Designer.cs">
<DependentUpon>Form1.cs</DependentUpon>
</Compile>
<Compile Include="frm_settings_urlexpander.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="frm_settings_urlexpander.Designer.cs">
<DependentUpon>frm_settings_urlexpander.cs</DependentUpon>
</Compile>
<Compile Include="frm_SplashScreen.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="frm_SplashScreen.Designer.cs">
<DependentUpon>frm_SplashScreen.cs</DependentUpon>
</Compile>
<Compile Include="frm_About.cs">
<SubType>Form</SubType>
</Compile>
Expand Down Expand Up @@ -110,6 +129,12 @@
<EmbeddedResource Include="Form1.resx">
<DependentUpon>Form1.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="frm_settings_urlexpander.resx">
<DependentUpon>frm_settings_urlexpander.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="frm_SplashScreen.resx">
<DependentUpon>frm_SplashScreen.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="frm_About.resx">
<DependentUpon>frm_About.cs</DependentUpon>
</EmbeddedResource>
Expand Down
13 changes: 9 additions & 4 deletions BrowserSelect/Form1.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,15 +50,18 @@ public void updateBrowsers()
}

private void Form1_Load(object sender, EventArgs e)
{
{
this.AutoSize = true;
this.AutoSizeMode = AutoSizeMode.GrowAndShrink;
this.KeyPreview = true;
this.Text = Program.url;
// set the form icon from .exe file icon
this.Icon = IconExtractor.fromFile(Application.ExecutablePath);
// create a wildcard rule for this domain (always button)
_alwaysRule = generate_rule(Program.url);
if (Program.url != "")
{
_alwaysRule = generate_rule(Program.url);
this.Text = Program.url;
}
// check for new version
if (Settings.Default.last_version != "nope")
{
Expand Down Expand Up @@ -161,7 +164,9 @@ e.g. sealake.vic.au or something.fun.ir
x = parts[count - 2]; //second-level
y = parts[count - 3]; //third-level
}
catch (IndexOutOfRangeException) { } // in case domain did not have 3 parts.. (e.g. localhost, google.com)
catch (IndexOutOfRangeException ex) {
Debug.WriteLine(ex);
} // in case domain did not have 3 parts.. (e.g. localhost, google.com)

// creating the patterns
var rule_tld = String.Format("*.{0}.{1}", x, tld);
Expand Down
176 changes: 171 additions & 5 deletions BrowserSelect/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,30 @@
using System.Threading.Tasks;
using System.Windows.Forms;
using BrowserSelect.Properties;
using System.Web;
using System.Net;
using System.Threading;

namespace BrowserSelect
{
static class Program
{
public static string url = "http://google.com/";
public static string url = "";
public static HttpWebRequest webRequestThread = null;
public static bool uriExpanderThreadStop = false;
public static (string name, string domain)[] defaultUriExpander = new(string name, string domain)[]
{
("Outlook safe links", "safelinks.protection.outlook.com")//,
//("Test1", "test.com"),
//("Test2", "test2.com")
};

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{

// fix #28
LeaveDotsAndSlashesEscaped();
// to prevent loss of settings when on update
Expand All @@ -43,13 +53,45 @@ static void Main(string[] args)
var uc = new UpdateChecker();
Task.Factory.StartNew(() => uc.check());
}
//load URL Shortners
string[] defultUrlShortners = new string[] {
"adf.ly",
"bit.do",
"bit.ly",
"goo.gl",
"ht.ly",
"is.gd",
"ity.im",
"lnk.co",
"ow.ly",
"q.gs",
"rb.gy",
"rotf.lol",
"t.co",
"tiny.one",
"tinyurl.com"
};
if (Settings.Default.URLShortners == null)
{
StringCollection url_shortners = new StringCollection();
url_shortners.AddRange(defultUrlShortners);
Settings.Default.URLShortners = url_shortners;
Settings.Default.Save();
}

Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);

//checking if a url is being opened or app is ran from start menu (without arguments)
if (args.Length > 0)
{
//check to see if auto select rules match
url = args[0];
//add http:// to url if it is missing a protocol
var uri = new UriBuilder(url).Uri;
uri = UriExpander(uri);
if (Settings.Default.ExpandUrl != null && Settings.Default.ExpandUrl != "Never")
uri = UriFollowRedirects(uri);
url = uri.AbsoluteUri;

foreach (var sr in Settings.Default.AutoBrowser.Cast<string>()
Expand Down Expand Up @@ -81,9 +123,12 @@ static void Main(string[] args)
}

// display main form
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
//Application.EnableVisualStyles();
//Application.SetCompatibleTextRenderingDefault(false);
if (url == "" && (Boolean)Settings.Default.LaunchToSettings)
Application.Run(new frm_settings());
else
Application.Run(new Form1());
}

// from : http://stackoverflow.com/a/250400/1461004
Expand Down Expand Up @@ -207,5 +252,126 @@ private static void LeaveDotsAndSlashesEscaped()

setUpdatableFlagsMethod.Invoke(uriParser, new object[] { 0 });
}

private static Uri UriExpander(Uri uri)
{
List<string> enabled_url_expanders = new List<string>();
if (Settings.Default.URLProcessors != null)
{
foreach ((string name, string domain) in defaultUriExpander)
{
if (Settings.Default.URLProcessors.Contains(name))
{
enabled_url_expanders.Add(domain);
}
}
}

System.Diagnostics.Debug.WriteLine("URLExpander: " + uri.Host);
if (uri.Host.EndsWith("safelinks.protection.outlook.com") &&
enabled_url_expanders.Contains("safelinks.protection.outlook.com"))
{
var queryDict = HttpUtility.ParseQueryString(uri.Query);
if (queryDict != null && queryDict.Get("url") != null)
{
uri = new UriBuilder(HttpUtility.UrlDecode(queryDict.Get("url"))).Uri;
}
}

return uri;
}
private static Uri UriFollowRedirects(Uri uri, int num_redirects = 0)
{
int max_redirects = 20;
if (num_redirects >= max_redirects)
{
return uri;
}
System.Diagnostics.Debug.WriteLine("Url " + num_redirects + " " + uri.Host);
StringCollection url_shortners = Settings.Default.URLShortners;
Form SplashScreen = null;
if (!Program.uriExpanderThreadStop &&
(url_shortners.Contains(uri.Host) || Settings.Default.ExpandUrl == "Follow all redirects"))
{
//Thread.Sleep(2000);
if (num_redirects == 0)
{
SplashScreen = new frm_SplashScreen();
var splashThread = new Thread(new ThreadStart(() => Application.Run(SplashScreen)));
splashThread.Start();
}
HttpWebResponse response = MyWebRequest(uri);
if (response != null)
{
if ((int)response.StatusCode > 299 && (int)response.StatusCode < 400)
{
uri = UriFollowRedirects(new UriBuilder(response.Headers["Location"]).Uri, (num_redirects + 1));
}
else
{
uri = response.ResponseUri;
}
}
}

if (num_redirects == 0)
{
if (SplashScreen != null && !SplashScreen.Disposing && !SplashScreen.IsDisposed)
try
{
Program.uriExpanderThreadStop = true;
SplashScreen.Invoke(new Action(() => SplashScreen.Close()));
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
}
}
return uri;
}

private static HttpWebResponse MyWebRequest(Uri uri)
{
//Support TLS1.2 - updated .Net framework - no longer needed
//ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | (SecurityProtocolType)768 | (SecurityProtocolType)3072 | SecurityProtocolType.Ssl3; //SecurityProtocolType.Tls12;
var webRequest = (HttpWebRequest)WebRequest.Create(uri.AbsoluteUri);
// Set timeout - needs to be high enough for HTTP request to succeed on slow network connections,
// but fast enough not to slow down BrowserSelect startup too much.
// 2 seconds seems about right
webRequest.Timeout = 2000;
//webRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv: 85.0) Gecko/20100101 Firefox/85.0";
webRequest.AllowAutoRedirect = false;
HttpWebResponse response = null;
try
{
var ar = webRequest.BeginGetResponse(null, null);
Program.webRequestThread = webRequest;
ThreadPool.RegisterWaitForSingleObject(ar.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), webRequest, webRequest.Timeout, true);
response = (HttpWebResponse)webRequest.EndGetResponse(ar);
response.Close();
}
catch (WebException ex)
{
// We are mostly catch up webRequest.Abort() or webRequest errors here (e.g. untrusted certificates)
// No action required.
System.Diagnostics.Debug.WriteLine(ex);
}

return response;
}

// Abort the request if the timer fires.
private static void TimeoutCallback(object state, bool timedOut)
{
if (timedOut)
{
HttpWebRequest request = state as HttpWebRequest;
if (request != null)
{
System.Diagnostics.Debug.WriteLine("Timed out, aborting HTTP request...");
request.Abort();
}
}
}
}
}
2 changes: 1 addition & 1 deletion BrowserSelect/Properties/Resources.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading