Files
ArchiSteamFarm/ArchiSteamFarm/Program.cs

386 lines
12 KiB
C#
Raw Normal View History

2015-10-28 19:21:27 +01:00
/*
_ _ _ ____ _ _____
/ \ _ __ ___ | |__ (_)/ ___| | |_ ___ __ _ _ __ ___ | ___|__ _ _ __ _ __ ___
/ _ \ | '__|/ __|| '_ \ | |\___ \ | __|/ _ \ / _` || '_ ` _ \ | |_ / _` || '__|| '_ ` _ \
/ ___ \ | | | (__ | | | || | ___) || |_| __/| (_| || | | | | || _|| (_| || | | | | | | |
/_/ \_\|_| \___||_| |_||_||____/ \__|\___| \__,_||_| |_| |_||_| \__,_||_| |_| |_| |_|
2017-01-02 20:05:21 +01:00
Copyright 2015-2017 Łukasz "JustArchi" Domeradzki
2015-10-28 19:21:27 +01:00
Contact: JustArchi@JustArchi.net
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
2016-03-09 03:10:33 +01:00
using System.Collections.Generic;
using System.Diagnostics;
2015-10-25 06:16:50 +01:00
using System.IO;
2016-03-09 03:52:04 +01:00
using System.Linq;
2015-10-29 17:36:16 +01:00
using System.Reflection;
using System.ServiceProcess;
2015-10-25 06:16:50 +01:00
using System.Threading;
2015-10-29 17:36:16 +01:00
using System.Threading.Tasks;
2017-01-06 13:20:36 +01:00
using ArchiSteamFarm.Localization;
using SteamKit2;
2015-10-25 06:16:50 +01:00
namespace ArchiSteamFarm {
internal static class Program {
internal static readonly ArchiLogger ArchiLogger = new ArchiLogger(SharedInfo.ASF);
internal static bool IsWCFRunning => WCF.IsServerRunning;
internal static GlobalConfig GlobalConfig { get; private set; }
internal static GlobalDatabase GlobalDatabase { get; private set; }
internal static bool IsRunningAsService { get; private set; }
internal static EMode Mode { get; private set; } = EMode.Normal;
internal static WebBrowser WebBrowser { get; private set; }
2016-01-03 20:36:13 +01:00
private static readonly object ConsoleLock = new object();
private static readonly ManualResetEventSlim ShutdownResetEvent = new ManualResetEventSlim(false);
2016-11-06 17:08:44 +01:00
private static readonly WCF WCF = new WCF();
2015-10-29 17:36:16 +01:00
private static bool ShutdownSequenceInitialized;
internal static void Exit(byte exitCode = 0) {
2017-01-06 13:20:36 +01:00
if (exitCode != 0) {
2017-01-06 13:21:56 +01:00
ArchiLogger.LogGenericError(Strings.ErrorExitingWithNonZeroErrorCode);
2017-01-06 13:20:36 +01:00
}
Shutdown();
2016-04-02 13:08:43 +02:00
Environment.Exit(exitCode);
}
2016-11-09 09:26:07 +01:00
internal static string GetUserInput(ASF.EUserInputType userInputType, string botName = SharedInfo.ASF, string extraInformation = null) {
if (userInputType == ASF.EUserInputType.Unknown) {
2016-03-12 06:01:55 +01:00
return null;
}
2016-06-28 10:36:28 +02:00
if (GlobalConfig.Headless || !Runtime.IsUserInteractive) {
ArchiLogger.LogGenericWarning("Received a request for user input, but process is running in headless mode!");
2016-04-06 16:37:45 +02:00
return null;
}
2015-10-28 20:01:43 +01:00
string result;
2015-10-25 06:16:50 +01:00
lock (ConsoleLock) {
Logging.OnUserInputStart();
switch (userInputType) {
2016-11-09 09:26:07 +01:00
case ASF.EUserInputType.DeviceID:
2016-05-30 01:57:06 +02:00
Console.Write("<" + botName + "> Please enter your Device ID (including \"android:\"): ");
2016-03-12 05:58:51 +01:00
break;
2016-11-09 09:26:07 +01:00
case ASF.EUserInputType.Login:
2016-05-30 01:57:06 +02:00
Console.Write("<" + botName + "> Please enter your login: ");
break;
2016-11-09 09:26:07 +01:00
case ASF.EUserInputType.Password:
2016-05-30 01:57:06 +02:00
Console.Write("<" + botName + "> Please enter your password: ");
break;
2016-11-09 09:26:07 +01:00
case ASF.EUserInputType.PhoneNumber:
2016-05-30 01:57:06 +02:00
Console.Write("<" + botName + "> Please enter your full phone number (e.g. +1234567890): ");
break;
2016-11-09 09:26:07 +01:00
case ASF.EUserInputType.SMS:
2016-05-30 01:57:06 +02:00
Console.Write("<" + botName + "> Please enter SMS code sent on your mobile: ");
break;
2016-11-09 09:26:07 +01:00
case ASF.EUserInputType.SteamGuard:
2016-05-30 01:57:06 +02:00
Console.Write("<" + botName + "> Please enter the auth code sent to your email: ");
break;
2016-11-09 09:26:07 +01:00
case ASF.EUserInputType.SteamParentalPIN:
2016-05-30 01:57:06 +02:00
Console.Write("<" + botName + "> Please enter steam parental PIN: ");
break;
2016-11-09 09:26:07 +01:00
case ASF.EUserInputType.RevocationCode:
2016-05-30 01:57:06 +02:00
Console.WriteLine("<" + botName + "> PLEASE WRITE DOWN YOUR REVOCATION CODE: " + extraInformation);
Console.Write("<" + botName + "> Hit enter once ready...");
break;
2016-11-09 09:26:07 +01:00
case ASF.EUserInputType.TwoFactorAuthentication:
2016-05-30 01:57:06 +02:00
Console.Write("<" + botName + "> Please enter your 2 factor auth code from your authenticator app: ");
break;
2016-11-09 09:26:07 +01:00
case ASF.EUserInputType.WCFHostname:
2016-12-11 16:56:33 +01:00
Console.Write("<" + botName + "> Please enter your WCF host: ");
break;
2016-03-12 06:01:55 +01:00
default:
2016-05-30 01:57:06 +02:00
Console.Write("<" + botName + "> Please enter not documented yet value of \"" + userInputType + "\": ");
2016-03-12 06:01:55 +01:00
break;
2015-10-25 06:16:50 +01:00
}
2016-05-13 06:32:42 +02:00
2015-10-28 20:01:43 +01:00
result = Console.ReadLine();
2016-05-30 01:57:06 +02:00
2016-04-13 16:48:11 +02:00
if (!Console.IsOutputRedirected) {
Console.Clear(); // For security purposes
}
2016-05-30 01:57:06 +02:00
Logging.OnUserInputEnd();
2015-10-25 06:16:50 +01:00
}
2015-12-16 01:17:54 +01:00
2016-05-30 01:57:06 +02:00
return !string.IsNullOrEmpty(result) ? result.Trim() : null;
2015-10-25 06:16:50 +01:00
}
internal static void Restart() {
if (!InitShutdownSequence()) {
return;
}
try {
Process.Start(Assembly.GetEntryAssembly().Location, string.Join(" ", Environment.GetCommandLineArgs().Skip(1)));
} catch (Exception e) {
ArchiLogger.LogGenericException(e);
}
ShutdownResetEvent.Set();
Environment.Exit(0);
}
2016-10-31 06:29:48 +01:00
internal static void Shutdown() {
2016-07-19 22:18:00 +02:00
if (!InitShutdownSequence()) {
2016-06-28 07:50:44 +02:00
return;
}
ShutdownResetEvent.Set();
2016-07-19 22:18:00 +02:00
}
2016-12-24 19:27:36 +01:00
private static async Task Init(string[] args) {
AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionHandler;
TaskScheduler.UnobservedTaskException += UnobservedTaskExceptionHandler;
string homeDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
if (!string.IsNullOrEmpty(homeDirectory)) {
Directory.SetCurrentDirectory(homeDirectory);
// Allow loading configs from source tree if it's a debug build
if (Debugging.IsDebugBuild) {
// Common structure is bin/(x64/)Debug/ArchiSteamFarm.exe, so we allow up to 4 directories up
for (byte i = 0; i < 4; i++) {
Directory.SetCurrentDirectory("..");
if (Directory.Exists(SharedInfo.ConfigDirectory)) {
break;
}
}
// If config directory doesn't exist after our adjustment, abort all of that
if (!Directory.Exists(SharedInfo.ConfigDirectory)) {
Directory.SetCurrentDirectory(homeDirectory);
}
}
2016-07-19 22:18:00 +02:00
}
// Parse pre-init args
if (args != null) {
ParsePreInitArgs(args);
}
Logging.InitLoggers();
ArchiLogger.LogGenericInfo("ASF V" + SharedInfo.Version);
if (!Runtime.IsRuntimeSupported) {
ArchiLogger.LogGenericError("ASF detected unsupported runtime version, program might NOT run correctly in current environment. You're running it at your own risk!");
Thread.Sleep(10000);
}
2016-07-19 22:18:00 +02:00
InitServices();
// If debugging is on, we prepare debug directory prior to running
if (GlobalConfig.Debug) {
if (Directory.Exists(SharedInfo.DebugDirectory)) {
Directory.Delete(SharedInfo.DebugDirectory, true);
Thread.Sleep(1000); // Dirty workaround giving Windows some time to sync
}
Directory.CreateDirectory(SharedInfo.DebugDirectory);
DebugLog.AddListener(new Debugging.DebugListener());
DebugLog.Enabled = true;
}
// Parse post-init args
if (args != null) {
2016-12-24 19:27:36 +01:00
await ParsePostInitArgs(args).ConfigureAwait(false);
}
// If we ran ASF as a client, we're done by now
if (Mode.HasFlag(EMode.Client) && !Mode.HasFlag(EMode.Server)) {
Exit();
}
2016-12-24 19:27:36 +01:00
await ASF.CheckForUpdate().ConfigureAwait(false);
await ASF.InitBots().ConfigureAwait(false);
ASF.InitFileWatcher();
}
2015-11-25 16:31:39 +01:00
private static void InitServices() {
2016-08-02 06:04:44 +02:00
string globalConfigFile = Path.Combine(SharedInfo.ConfigDirectory, SharedInfo.GlobalConfigFileName);
2016-07-31 17:38:14 +02:00
GlobalConfig = GlobalConfig.Load(globalConfigFile);
2016-03-06 23:28:56 +01:00
if (GlobalConfig == null) {
ArchiLogger.LogGenericError("Global config could not be loaded, please make sure that " + globalConfigFile + " exists and is valid! Did you forget to read wiki?");
2016-03-06 23:28:56 +01:00
Thread.Sleep(5000);
2016-04-02 13:08:43 +02:00
Exit(1);
2016-03-06 23:28:56 +01:00
}
2016-08-02 06:04:44 +02:00
string globalDatabaseFile = Path.Combine(SharedInfo.ConfigDirectory, SharedInfo.GlobalDatabaseFileName);
2016-07-31 17:38:14 +02:00
GlobalDatabase = GlobalDatabase.Load(globalDatabaseFile);
2016-03-07 02:39:55 +01:00
if (GlobalDatabase == null) {
ArchiLogger.LogGenericError("Global database could not be loaded, if issue persists, please remove " + globalDatabaseFile + " in order to recreate database!");
2016-03-07 02:39:55 +01:00
Thread.Sleep(5000);
2016-04-02 13:08:43 +02:00
Exit(1);
2016-03-07 02:39:55 +01:00
}
2016-03-06 23:28:56 +01:00
ArchiWebHandler.Init();
2015-11-25 16:31:39 +01:00
WebBrowser.Init();
2016-03-06 23:28:56 +01:00
WCF.Init();
WebBrowser = new WebBrowser(ArchiLogger);
2015-11-25 16:31:39 +01:00
}
private static bool InitShutdownSequence() {
if (ShutdownSequenceInitialized) {
return false;
}
ShutdownSequenceInitialized = true;
WCF.StopServer();
foreach (Bot bot in Bot.Bots.Values) {
bot.Stop();
}
return true;
}
private static void Main(string[] args) {
if (Runtime.IsUserInteractive) {
// App
2016-12-24 19:27:36 +01:00
Init(args).Wait();
// Wait for signal to shutdown
ShutdownResetEvent.Wait();
// We got a signal to shutdown
Exit();
} else {
// Service
IsRunningAsService = true;
using (Service service = new Service()) {
ServiceBase.Run(service);
}
}
}
2016-12-24 19:27:36 +01:00
private static async Task ParsePostInitArgs(IEnumerable<string> args) {
2016-07-24 00:36:15 +02:00
if (args == null) {
ArchiLogger.LogNullError(nameof(args));
2016-07-24 00:36:15 +02:00
return;
}
foreach (string arg in args) {
switch (arg) {
case "":
break;
2016-08-06 22:16:46 +02:00
case "--client":
2016-11-13 15:35:34 +01:00
Mode |= EMode.Client;
2016-08-06 22:16:46 +02:00
break;
case "--server":
2016-11-13 15:35:34 +01:00
Mode |= EMode.Server;
WCF.StartServer();
2016-12-24 19:27:36 +01:00
await ASF.InitBots().ConfigureAwait(false);
2016-08-06 22:16:46 +02:00
break;
2016-07-24 00:36:15 +02:00
default:
if (arg.StartsWith("--", StringComparison.Ordinal)) {
if (arg.StartsWith("--cryptkey=", StringComparison.Ordinal) && (arg.Length > 11)) {
CryptoHelper.SetEncryptionKey(arg.Substring(11));
2016-07-24 00:36:15 +02:00
}
break;
2016-07-24 00:36:15 +02:00
}
if (!Mode.HasFlag(EMode.Client)) {
ArchiLogger.LogGenericWarning("Ignoring command because --client wasn't specified: " + arg);
break;
}
ArchiLogger.LogGenericInfo("Response received: " + WCF.SendCommand(arg));
2016-07-24 00:36:15 +02:00
break;
}
}
}
private static void ParsePreInitArgs(IEnumerable<string> args) {
2016-05-13 06:32:42 +02:00
if (args == null) {
ArchiLogger.LogNullError(nameof(args));
2016-05-13 06:32:42 +02:00
return;
}
2016-01-03 20:36:13 +01:00
foreach (string arg in args) {
switch (arg) {
2016-05-30 01:57:06 +02:00
case "":
break;
2016-01-03 20:36:13 +01:00
case "--client":
2016-11-13 15:35:34 +01:00
Mode |= EMode.Client;
2016-01-03 20:36:13 +01:00
break;
case "--server":
2016-11-13 15:35:34 +01:00
Mode |= EMode.Server;
2016-01-03 20:36:13 +01:00
break;
default:
2016-05-13 06:32:42 +02:00
if (arg.StartsWith("--", StringComparison.Ordinal)) {
if (arg.StartsWith("--path=", StringComparison.Ordinal) && (arg.Length > 7)) {
Directory.SetCurrentDirectory(arg.Substring(7));
2016-06-28 09:24:32 +02:00
}
2016-01-03 20:36:13 +01:00
}
break;
}
}
}
2016-01-09 19:54:08 +01:00
private static void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs args) {
2016-07-10 20:17:35 +02:00
if (args?.ExceptionObject == null) {
ArchiLogger.LogNullError(nameof(args) + " || " + nameof(args.ExceptionObject));
2016-01-09 19:54:08 +01:00
return;
}
ArchiLogger.LogFatalException((Exception) args.ExceptionObject);
2016-01-09 19:54:08 +01:00
}
private static void UnobservedTaskExceptionHandler(object sender, UnobservedTaskExceptionEventArgs args) {
2016-07-10 20:17:35 +02:00
if (args?.Exception == null) {
ArchiLogger.LogNullError(nameof(args) + " || " + nameof(args.Exception));
return;
}
ArchiLogger.LogFatalException(args.Exception);
}
[Flags]
internal enum EMode : byte {
Normal = 0, // Standard most common usage
Client = 1, // WCF client
Server = 2 // WCF server
}
2016-06-28 06:58:59 +02:00
private sealed class Service : ServiceBase {
internal Service() {
ServiceName = SharedInfo.ServiceName;
}
2016-12-24 19:27:36 +01:00
protected override void OnStart(string[] args) => Task.Run(async () => {
2016-12-24 23:12:40 +01:00
// Normally it'd make sense to use already provided string[] args parameter above
// However, that one doesn't seem to work when ASF is started as a service, it's always null
// Therefore, we will use Environment args in such case
string[] envArgs = Environment.GetCommandLineArgs();
await Init(envArgs).ConfigureAwait(false);
2016-06-28 06:58:59 +02:00
ShutdownResetEvent.Wait();
Stop();
});
2016-06-28 06:58:59 +02:00
protected override void OnStop() => Shutdown();
2016-06-28 06:58:59 +02:00
}
}
}