Пример #1
0
        /// <summary>
        /// 不再断点续传
        /// </summary>
        /// <param name="task"></param>
        private void Download(DownloadTask task)
        {
            try
            {
                if (File.Exists(task.storagePath))
                {
                    File.Delete(task.storagePath);
                }
                Uri uri = new Uri(task.url);
                CLogger.Log("DownloadThread::Download() - start download:" + uri);

                HttpWebRequest request2 = (HttpWebRequest)WebRequest.Create(uri);
                request2.ReadWriteTimeout = kTimeOut;
                HttpWebResponse response2 = (HttpWebResponse)request2.GetResponse();
                task.fileLength = response2.ContentLength;
                bool transferOkay = this.ReadBytesFromResponse(task, response2);
                response2.Close();
                request2.Abort();
                if (transferOkay)
                {
                    this.OnDownloadFinished(task, null);
                }
            }
            catch (Exception ex)
            {
                string s = "DownloadThread::Download() - " + ex.Message + "@" + task.url + "#" + ex.StackTrace;
                CLogger.LogError(s);
                this.OnDownloadFinished(task, ex);
            }
        }
Пример #2
0
Файл: Itch.cs Проект: Nutzzz/GLC
 public static void InstallGame(CGame game)
 {
     CDock.DeleteCustomImage(game.Title);
     if (OperatingSystem.IsWindows())
     {
         try
         {
             using RegistryKey key = Registry.ClassesRoot.OpenSubKey(@"itch\shell\open\command", RegistryKeyPermissionCheck.ReadSubTree);
             string[] subs    = GetRegStrVal(key, null).Split(' ');
             string   command = "";
             string   args    = "";
             for (int i = 0; i > subs.Length; i++)
             {
                 if (i > 0)
                 {
                     args += subs[i];
                 }
                 else
                 {
                     command = subs[0];
                 }
             }
             CDock.StartAndRedirect(command, args.Replace("%1", INSTALL_GAME + "/" + GetGameID(game.ID)));
         }
         catch (Exception e)
         {
             CLogger.LogError(e);
         }
     }
 }
Пример #3
0
    public override void activate()
    {
        ovrGamepadController = GetComponent <OVRGamepadController>();
        ovrPlayerController  = GetComponent <OVRPlayerController>();

        if (ovrPlayerController == null)
        {
            CLogger.LogError("Fallback to COVRPlayerControllerCoupled failed. Missing OVRGamepadController component.");
            return;
        }
        else
        {
            //Enable OVRPlayerController to support keyboard movement
            ovrPlayerController.enabled = true;
        }

        if (ovrGamepadController == null)
        {
            CLogger.LogWarning("COVRPlayerControllerCoupled is missing OVRGamepadController component.");
        }
        else
        {
            //Enable OVRGamepadController to support gamepad movement
            ovrGamepadController.enabled = true;
        }
    }
Пример #4
0
        /// <summary>
        /// Get enum description
        /// </summary>
        /// <returns>description string</returns>
        /// <param name="enum">Enum</param>
        public static string GetDescription <T>(this T source)
        {
            try
            {
                FieldInfo field = source.GetType().GetField(source.ToString());

                DescriptionAttribute[] attr = (DescriptionAttribute[])field.GetCustomAttributes(
                    typeof(DescriptionAttribute), false);

                if (attr != null && attr.Length > 0)
                {
                    return(attr[0].Description);
                }
            }
            catch (Exception e)
            {
                CLogger.LogError(e);
            }
            Type   type   = source.GetType();
            string output = type.GetEnumName(source);

            if (!string.IsNullOrEmpty(output))
            {
                return(output);
            }
            return(source.ToString());
        }
Пример #5
0
        /// <summary>
        /// Find game keys in specified root
        /// Looks for a key-value pair inside the specified root.
        /// </summary>
        /// <param name="root">Root folder that will be scanned</param>
        /// <param name="strValData">A substring of the target value data in the subkey</param>
        /// <param name="strValName">The target value name that should contain the target value data</param>
        /// <param name="ignore">Function will ignore these subkey names (used to ignore things like launchers)</param>
        /// <returns>List of game registry keys</returns>
        public static List <RegistryKey> FindGameKeys(RegistryKey root, string strValData, string strValName, string[] ignoreKeys)
        {
            LinkedList <RegistryKey> toCheck  = new();
            List <RegistryKey>       gameKeys = new();

            toCheck.AddLast(root);

            while (toCheck.Count > 0)
            {
                root = toCheck.First.Value;
                toCheck.RemoveFirst();

                if (root != null)
                {
                    foreach (var name in root.GetValueNames())
                    {
                        if (root.GetValueKind(name) == RegistryValueKind.String && name.Equals(strValName))
                        {
                            if (((string)root.GetValue(name)).Contains(strValData, CDock.IGNORE_CASE))
                            {
                                gameKeys.Add(root);
                                break;
                            }
                        }
                    }

                    foreach (var sub in root.GetSubKeyNames())              // Add subkeys to search list
                    {
                        if (sub.Equals("Microsoft"))                        // Microsoft folder only contains system stuff and it doesn't need searching
                        {
                            break;
                        }

                        bool ignore = false;
                        foreach (string entry in ignoreKeys)
                        {
                            if (sub.Equals(entry))
                            {
                                ignore = true;
                                break;
                            }
                        }
                        if (!ignore)
                        {
                            try
                            {
                                toCheck.AddLast(root.OpenSubKey(sub, RegistryKeyPermissionCheck.ReadSubTree));
                            }
                            catch (Exception e)
                            {
                                CLogger.LogError(e);
                            }
                        }
                    }
                }
            }
            return(gameKeys);
        }
    // Use this for initialization
    void Start()
    {
        #if UNITY_EDITOR || UNITY_STANDALONE_WIN
        switch (deviceTypeIndex)
        {
        //Auto selection
        case 0:
            virtDevice = getStandardVirtualizerDevice();
            if (virtDevice == null)
            {
                fallbackToStandardCoupled();
                return;
            }
            break;

        //Standard de-coupled virtualizer input
        case 1:
            virtDevice = getStandardVirtualizerDevice();
            break;

        //TODO: Standard coupled movement input
        case 2:
            fallbackToStandardCoupled();
            return;

        //Faild to find VirtDevice
        default:
            break;
        }
        #endif

        #if UNITY_ANDROID
        virtDevice = new CVirtDeviceBluetooth();
        #endif

        if (virtDevice != null)
        {
            CLogger.Log("Virtualizer device found, connecting...");

            if (virtDevice.Open())
            {
                CLogger.Log("Successfully connected to Virtualizer device.");

                //Reset ResetPlayerOrientation and PlayerHeight
                virtDevice.ResetPlayerOrientation();
                virtDevice.GetPlayerHeight();
            }
            else
            {
                CLogger.LogError("Failed to connect to Virtualizer device.");
            }
        }
        else
        {
            CLogger.LogError("Virtualizer device not found...");
        }
    }
Пример #7
0
Файл: Epic.cs Проект: Nutzzz/GLC
        public void GetGames(List <ImportGameData> gameDataList, bool expensiveIcons = false)
        {
            string dir = Path.Combine(GetFolderPath(SpecialFolder.CommonApplicationData), EPIC_ITEMS);

            if (!Directory.Exists(dir))
            {
                CLogger.LogInfo("{0} games not found in ProgramData.", _name.ToUpper());
                return;
            }
            string[] files = Directory.GetFiles(dir, "*.item", SearchOption.TopDirectoryOnly);
            CLogger.LogInfo("{0} {1} games found", files.Length, _name.ToUpper());

            foreach (string file in files)
            {
                string strDocumentData = File.ReadAllText(file);

                if (string.IsNullOrEmpty(strDocumentData))
                {
                    continue;
                }

                try
                {
                    using JsonDocument document = JsonDocument.Parse(@strDocumentData, jsonTrailingCommas);
                    string strID = GetStringProperty(document.RootElement, "AppName");
                    if (string.IsNullOrEmpty(strID))
                    {
                        strID = Path.GetFileName(file);
                    }
                    string strTitle = GetStringProperty(document.RootElement, "DisplayName");
                    CLogger.LogDebug($"- {strTitle}");
                    string strLaunch   = GetStringProperty(document.RootElement, "LaunchExecutable"); // DLCs won't have this set
                    string strAlias    = "";
                    string strPlatform = GetPlatformString(ENUM);

                    if (!string.IsNullOrEmpty(strLaunch))
                    {
                        strLaunch = Path.Combine(GetStringProperty(document.RootElement, "InstallLocation"), strLaunch);
                        strAlias  = GetAlias(GetStringProperty(document.RootElement, "MandatoryAppFolderName"));
                        if (strAlias.Length > strTitle.Length)
                        {
                            strAlias = GetAlias(strTitle);
                        }
                        if (strAlias.Equals(strTitle, CDock.IGNORE_CASE))
                        {
                            strAlias = "";
                        }
                        gameDataList.Add(new ImportGameData(strID, strTitle, strLaunch, strLaunch, "", strAlias, true, strPlatform));
                    }
                }
                catch (Exception e)
                {
                    CLogger.LogError(e, string.Format("Malformed {0} file: {1}", _name.ToUpper(), file));
                }
            }
            CLogger.LogDebug("--------------------");
        }
Пример #8
0
        private bool ReadBytesFromResponse(DownloadTask task, WebResponse response)
        {
            bool okay = false;
            DownloadFileTransferInfo fileInfo = _transferMgr.GetDownloadFileInfo(task.file);

            FileUtils.Instance.CheckDirExistsForFile(task.storagePath);

            using (FileStream fileStream = new FileStream(task.storagePath, task.receivedLength == 0 ? FileMode.Create : FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                try
                {
                    fileStream.Position = task.receivedLength;
                    byte[] array = new byte[1024];
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        int bytesRead = 0;
                        while (task.receivedLength < task.fileLength)
                        {
                            bytesRead = responseStream.Read(array, 0, array.Length);
                            //Debug.Log("############bytesRead=" + bytesRead);
                            fileStream.Write(array, 0, bytesRead);
                            task.receivedLength      += bytesRead;
                            _currentTaskReceivedBytes = task.receivedLength;

                            _transferMgr.UpdateFileTransferProgress(fileInfo, task.receivedLength);
                        }

                        okay = true;
                    }

                    if (task.receivedLength != task.fileLength)
                    {
                        string s = string.Format("DownloadThread::ReadBytesFromResponse() - Download length not fit Error:{0}/{1}", task.receivedLength, task.fileLength);
                        CLogger.LogError(s);
                        okay = false;
                        this.OnDownloadFinished(task, new Exception(s));
                    }
                }
                catch (System.Threading.ThreadAbortException)
                {
                    // 忽略
                }
                catch (Exception ex)
                {
                    okay = false;
                    string s = ex.Message + "\n" + ex.StackTrace;
                    CLogger.LogError(s);
                    this.OnDownloadFinished(task, ex);
                }
                finally
                {
                    _transferMgr.SaveTransferProgress("DownloadThread->>ReadBytesFromResponse");
                }
            }

            return(okay);
        }
Пример #9
0
        public IEnumerator RequestRemoteVersionCode(string versionManifestUrl, Action <string> failedCallback, Action <ResponseVersionManifestData> finishCallback)
        {
            // 请求远程最新版本信息
            if (versionManifestUrl.Contains("?"))
            {
                versionManifestUrl += "&__cdn_asset_version__=" + (DateTime.Now - TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1))).TotalSeconds;
            }
            else
            {
                versionManifestUrl += "?__cdn_asset_version__=" + (DateTime.Now - TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1))).TotalSeconds;
            }
            WWW www = new WWW(versionManifestUrl);

            yield return(www);

            if (!string.IsNullOrEmpty(www.error))
            {
                CLogger.LogError("VersionMgr::RequestRemoteVersionCode() - request remote_version.manifest error: " + www.error);
                if (failedCallback != null)
                {
                    CLogger.Log("VersionMgr::RequestRemoteVersionCode() - Request version.manifest failed. Please try again!");
                    failedCallback(www.error);
                }
                www.Dispose();
                yield break;
            }
            // 解析远程最新版本信息
            ResponseVersionManifestData manifestData = null;
            string remoteVersion = string.Empty;

            try
            {
                manifestData  = JsonUtility.FromJson <ResponseVersionManifestData>(www.text);
                remoteVersion = manifestData.version;
            }catch (Exception e)
            {
                CLogger.LogError("VersionMgr::RequestRemoteVersionCode() - parse version.manifest exception: " + e.Message);
                if (failedCallback != null)
                {
                    CLogger.Log("VersionMgr::RequestRemoteVersionCode() - Request version.manifest failed. Please try again!");
                    failedCallback(e.Message);
                }
                www.Dispose();
                yield break;
            }

            manifestData = manifestData != null ? manifestData : new ResponseVersionManifestData();
            CLogger.Log("VersionMgr::RequestRemoteVersionCode() - RequestRemoteVersionCode: " + remoteVersion);
            www.Dispose();
            www = null;

            if (finishCallback != null)
            {
                finishCallback(manifestData);
            }
        }
Пример #10
0
        public void GetGames(List <ImportGameData> gameDataList, bool expensiveIcons = false)
        {
            List <RegistryKey> keyList     = new();
            List <string>      dirs        = new();
            string             strPlatform = GetPlatformString(ENUM);
            string             path        = "";

            try
            {
                path = Path.Combine(GetFolderPath(SpecialFolder.CommonApplicationData), ORIGIN_CONTENT);
                if (Directory.Exists(path))
                {
                    dirs.AddRange(Directory.GetDirectories(path, "*.*", SearchOption.TopDirectoryOnly));
                }
            }
            catch (Exception e)
            {
                CLogger.LogError(e, string.Format("{0} directory read error: {1}", _name.ToUpper(), path));
            }

            CLogger.LogInfo("{0} {1} games found", dirs.Count, _name.ToUpper());
            foreach (string dir in dirs)
            {
                string[] files   = Array.Empty <string>();
                string   install = "";

                string strID     = Path.GetFileName(dir);
                string strTitle  = strID;
                string strLaunch = "";
                //string strIconPath = "";
                string strUninstall = "";
                string strAlias     = "";

                try
                {
                    files = Directory.GetFiles(dir, "*.mfst", SearchOption.TopDirectoryOnly);
                }
                catch (Exception e)
                {
                    CLogger.LogError(e);
                }

                foreach (string file in files)
                {
                    try
                    {
                        string   strDocumentData = File.ReadAllText(file);
                        string[] subs            = strDocumentData.Split('&');
                        foreach (string sub in subs)
                        {
                            if (sub.StartsWith(ORIGIN_PATH))
                            {
                                install = sub[15..];
Пример #11
0
    private void fallbackToStandardCoupled()
    {
        CVirtPlayerControllerCoupled coupledController = GetComponent <CVirtPlayerControllerCoupled>();

        if (coupledController != null)
        {
            CLogger.Log("Fallback to CVirtPlayerControllerCoupled implementation.");
            coupledController.activate();
        }
        else
        {
            CLogger.LogError("No CVirtPlayerControllerCoupled implementation available, fallback not possible.");
        }
    }
Пример #12
0
 /// <summary>
 /// Get a value from the registry if it exists
 /// </summary>
 /// <param name="key">The registry key</param>
 /// <param name="valName">The registry value name</param>
 /// <returns>the value's string data</returns>
 public static string GetRegStrVal(RegistryKey key, string valName)
 {
     try
     {
         object valData = key.GetValue(valName);
         if (valData != null)
         {
             return(valData.ToString());
         }
     }
     catch (Exception e)
     {
         CLogger.LogError(e);
     }
     return(string.Empty);
 }
Пример #13
0
 private void OnDownloadFinished(DownloadTask task, Exception ex)
 {
     if (ex != null)
     {
         if (ex.Message.Contains("Sharing violation on path"))
         {
             return;
         }
         DownloadError error;
         if (ex.Message.Contains("ConnectFailure") || ex.Message.Contains("NameResolutionFailure") || ex.Message.Contains("No route to host"))
         {
             error = DownloadError.ServerMaintenance;
         }
         else if (ex.Message.Contains("404"))
         {
             error = DownloadError.NotFound;
         }
         else if (ex.Message.Contains("403"))
         {
             error = DownloadError.ServerMaintenance;
         }
         else if (ex.Message.Contains("Disk full"))
         {
             error = DownloadError.DiskFull;
         }
         else if (ex.Message.Contains("timed out") || ex.Message.Contains("time out") || ex.Message.Contains("Error getting response stream"))
         {
             error = DownloadError.Timeout;
         }
         else if (ex.Message.Contains("length not fit"))
         {
             error = DownloadError.NetworkDisconnect;
         }
         else
         {
             error = DownloadError.Unknown;
         }
         CLogger.LogError("DownloadThread::OnDownloadFinished() - download failed: " + task.url + ", error message:" + ex.Message);
         NotifyResult(task, DownloadStatus.Fail, error);
         Thread.Sleep(1000);  // Downloading thread sleep for 3000ms when a exception occurred in the process of downloading
     }
     else
     {
         CLogger.Log("DownloadThread::OnDownloadFinished() -" + task.url);
         CheckMD5AfterDownload(task);
     }
 }
Пример #14
0
        /// <summary>
        /// Create SQLiteConnection and open the data source
        /// </summary>
        /// <param name="create">If <c>true</c> and data source is not found, create new one and apply schema</param>
        /// <param name="dataSource">Path to the data source</param>
        /// <returns>SQL success/failure error code</returns>
        public SQLiteErrorCode Open(bool create, string dataSource = SQL_MAIN_DATA_SOURCE)
        {
            if (IsOpen())
            {
                return(SQLiteErrorCode.Ok);
            }

            bool exists = File.Exists(dataSource);

            if (exists || create) // Only open if it's there or if we're making a new one
            {
                m_sqlite_conn = new SQLiteConnection("Data source=" + dataSource + ";Version=3;New=False;Compress=True;");
                try
                {
                    CLogger.LogInfo("Connecting to Data Source " + dataSource);
                    m_sqlite_conn.Open();
                }
                catch (SQLiteException e)
                {
                    CLogger.LogWarn("Database connection could not be established: " + e.ResultCode);
                    return(e.ResultCode);
                }
            }

            if (create && !exists) // New DB. Apply schema
            {
                string script;
                try
                {
                    script = File.ReadAllText("CreateDB.sql");
                }
                catch (IOException e)
                {
                    CLogger.LogError(e);
                    return(SQLiteErrorCode.Unknown); // Use unknown for non-sql issues
                }
                if (script.Length > 0)
                {
                    Execute(script);
                }
            }
            return(MaybeUpdateSchema());
        }
Пример #15
0
        public void ReadTransferProgress()
        {
            lock (_locker)
            {
                if (File.Exists(_transferInfoFilePath))
                {
                    string json = File.ReadAllText(_transferInfoFilePath);
                    _transferInfo = JsonUtility.FromJson <BreakpointTransferInfo>(json);
                    if (_transferInfo == null)
                    {
                        CLogger.LogError("解析本地断点续传记录json文件失败,json string=" + json);
                    }
                }

                if (_transferInfo == null)
                {
                    _transferInfo = new BreakpointTransferInfo();
                }
            }
        }
Пример #16
0
        /// <summary>
        /// Get a value from the registry if it exists
        /// </summary>
        /// <param name="key">The registry key</param>
        /// <param name="valName">The registry value name</param>
        /// <returns>the value's data as a string</returns>
        public static byte[] GetRegBinaryVal(RegistryKey key, string valName)
        {
            try
            {
                object valData = key.GetValue(valName);

                /*
                 * Type valType = valData.GetType();
                 * if (valData != null && valType == typeof(byte))
                 * {
                 */
                //if (byte.TryParse(valData.ToString(), out byte result))
                return((byte[])valData);
                //}
            }
            catch (Exception e)
            {
                CLogger.LogError(e);
            }
            return(null);
        }
Пример #17
0
        /// <summary>
        /// Export game data from memory to the game.json config file
        /// NOTE: At the moment, the program will pretty pretty much create a brand new JSON file and override all of the content...
        /// ... I need to find a nice workaround as JsonDocument class is read-only.
        /// </summary>
        /// <returns>True is successful, otherwise false</returns>
        public static bool Export(List <CGameData.CGame> gameList)
        {
            var options = new JsonWriterOptions
            {
                Indented = true
            };

            try
            {
                using (var stream = new MemoryStream())
                {
                    using (var writer = new Utf8JsonWriter(stream, options))
                    {
                        writer.WriteStartObject();
                        writer.WriteStartArray(GAMES_ARRAY);
                        for (int i = 0; i < gameList.Count; i++)
                        {
                            WriteGame(writer, stream, options, gameList[i]);
                        }
                        writer.WriteEndArray();
                        writer.WriteEndObject();
                    }

                    string strJsonData = Encoding.UTF8.GetString(stream.ToArray());
                    byte[] bytes       = new UTF8Encoding(true).GetBytes(strJsonData);

                    using (FileStream fs = File.Create(GAME_JSON_FILE))
                    {
                        fs.Write(bytes, 0, bytes.Length);
                    }
                }
            }
            catch (Exception ex)
            {
                CLogger.LogError(ex);
                return(false);
            }

            return(true);
        }
Пример #18
0
        /// <summary>
        /// Get a value from the registry if it exists
        /// </summary>
        /// <param name="key">The registry key</param>
        /// <param name="valName">The registry value name</param>
        /// <returns>the value's DWORD (UInt32) data</returns>
        public static int?GetRegDWORDVal(RegistryKey key, string valName)
        {
            try
            {
                object valData = key.GetValue(valName);

                /*
                 * Type valType = valData.GetType();
                 * if (valData != null && valType == typeof(int))
                 * {
                 */
                if (int.TryParse(valData.ToString(), out int result))
                {
                    return(result);
                }
                //}
            }
            catch (Exception e)
            {
                CLogger.LogError(e);
            }
            return(null);
        }
Пример #19
0
        /// <summary>
        /// Create empty games.json file with the empty array
        /// </summary>
        /// <returns>True if file created, otherwise false</returns>
        private static bool CreateEmptyFile()
        {
            var options = new JsonWriterOptions
            {
                Indented = true
            };

            try
            {
                using (var stream = new MemoryStream())
                {
                    using (var writer = new Utf8JsonWriter(stream, options))
                    {
                        writer.WriteStartObject();
                        writer.WriteStartArray(GAMES_ARRAY);
                        writer.WriteEndArray();
                        writer.WriteEndObject();
                    }

                    string strJsonData = Encoding.UTF8.GetString(stream.ToArray());
                    byte[] bytes       = new UTF8Encoding(true).GetBytes(strJsonData);

                    using (FileStream fs = File.Create(GAME_JSON_FILE))
                    {
                        fs.Write(bytes, 0, bytes.Length);
                    }
                }
            }
            catch (Exception ex)
            {
                CLogger.LogError(ex);
                return(false);
            }

            return(true);
        }
Пример #20
0
        public void GetGames(List <ImportGameData> gameDataList, bool expensiveIcons = false)
        {
            List <RegistryKey> keyList;

            using (RegistryKey key = Registry.LocalMachine.OpenSubKey(BIGFISH_GAMES, RegistryKeyPermissionCheck.ReadSubTree))             // HKLM32
            {
                if (key == null)
                {
                    CLogger.LogInfo("{0} client not found in the registry.", _name.ToUpper());
                    return;
                }

                keyList = FindGameFolders(key, "");

                CLogger.LogInfo("{0} {1} games found", keyList.Count > 1 ? keyList.Count - 1 : keyList.Count, _name.ToUpper());
                foreach (var data in keyList)
                {
                    string wrap = Path.GetFileName(data.Name);
                    if (wrap.Equals(BIGFISH_CASINO_ID))                      // hide Big Fish Casino Activator
                    {
                        continue;
                    }

                    string strID        = "bfg_" + wrap;
                    string strTitle     = "";
                    string strLaunch    = "";
                    string strIconPath  = "";
                    string strUninstall = "";
                    string strAlias     = "";
                    string strPlatform  = GetPlatformString(ENUM);
                    try
                    {
                        //found = true;
                        bool isInstalled = false;
                        strTitle = GetRegStrVal(data, "Name");

                        // If this is an expired trial, count it as not-installed
                        int activated = (int)GetRegDWORDVal(data, "Activated");
                        int daysLeft  = (int)GetRegDWORDVal(data, "DaysLeft");
                        int timeLeft  = (int)GetRegDWORDVal(data, "TimeLeft");
                        if (activated > 0 || timeLeft > 0 || daysLeft > 0)
                        {
                            isInstalled = true;
                            CLogger.LogDebug($"- {strTitle}");
                        }
                        else
                        {
                            CLogger.LogDebug($"- *{strTitle}");
                        }

                        strLaunch = GetRegStrVal(data, BIGFISH_PATH);
                        strAlias  = GetAlias(strTitle);
                        if (strAlias.Equals(strTitle, CDock.IGNORE_CASE))
                        {
                            strAlias = "";
                        }
                        //strIconPath = GetRegStrVal(data, "Thumbnail");	// 80x80
                        strIconPath = GetRegStrVal(data, "feature");                                // 175x150

                        //ushort userRating = (ushort)GetRegDWORDVal(data, "Rating"); // Not used?
                        uint     numberRuns = (uint)GetRegDWORDVal(data, "PlayCount");
                        byte[]   dateData   = GetRegBinaryVal(data, "LastActionTime");
                        DateTime lastRun    = BFRegToDateTime(dateData);
                        //CLogger.LogDebug("    LastActionTime: " + BitConverter.ToString(dateData) + " -> " + lastRun.ToShortDateString());

                        List <RegistryKey> unKeyList;
                        using (RegistryKey key2 = Registry.LocalMachine.OpenSubKey(NODE32_REG, RegistryKeyPermissionCheck.ReadSubTree))                         // HKLM32
                        {
                            if (key2 != null)
                            {
                                unKeyList = FindGameFolders(key2, BIGFISH_PREFIX);
                                foreach (var data2 in unKeyList)
                                {
                                    if (GetRegStrVal(data2, BIGFISH_ID).Equals(wrap))
                                    {
                                        if (string.IsNullOrEmpty(strIconPath))
                                        {
                                            strIconPath = GetRegStrVal(data2, GAME_DISPLAY_ICON).Trim(new char[] { ' ', '"' });
                                        }
                                        strUninstall = GetRegStrVal(data2, GAME_UNINSTALL_STRING).Trim(new char[] { ' ', '"' });
                                    }
                                }
                            }
                        }
                        if (string.IsNullOrEmpty(strIconPath) && expensiveIcons)
                        {
                            bool   success = false;
                            string dir     = Path.GetDirectoryName(strLaunch);
                            string xmlPath = Path.Combine(dir, "bfgstate.xml");
                            try
                            {
                                if (File.Exists(xmlPath))
                                {
                                    XmlDocument doc = new();
                                    doc.Load(xmlPath);
                                    //XmlNode node = doc.DocumentElement.SelectSingleNode("thumbnail");	// 80x80
                                    XmlNode node = doc.DocumentElement.SelectSingleNode("feature");                                             // 175x150
                                    if (node != null)
                                    {
                                        strIconPath = node.InnerText;
                                        if (File.Exists(strIconPath))
                                        {
                                            success = true;
                                        }
                                        else
                                        {
                                            // Use website to download missing icons
                                            if (!(bool)(CConfig.GetConfigBool(CConfig.CFG_IMGDOWN)))
                                            {
                                                if (CDock.DownloadCustomImage(strTitle, GetIconUrl(GetGameID(strID), strTitle)))
                                                {
                                                    success = true;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                CLogger.LogError(e);
                            }
                            if (!success)
                            {
                                strIconPath = CGameFinder.FindGameBinaryFile(dir, strTitle);
                            }
                        }
                        if (!(string.IsNullOrEmpty(strLaunch)))
                        {
                            gameDataList.Add(
                                new ImportGameData(strID, strTitle, strLaunch, strIconPath, strUninstall, strAlias, isInstalled, strPlatform, dateLastRun: lastRun, numRuns: numberRuns));
                        }
                    }
                    catch (Exception e)
                    {
                        CLogger.LogError(e);
                    }
                }
            }
            CLogger.LogDebug("------------------------");
        }
Пример #21
0
        public void GetGames(List <ImportGameData> gameDataList, bool expensiveIcons = false)
        {
            List <string> igcIds      = new();
            string        strPlatform = GetPlatformString(ENUM);

            // Get installed games
            string file = Path.Combine(GetFolderPath(SpecialFolder.ApplicationData), IG_JSON);

            if (!File.Exists(file))
            {
                CLogger.LogInfo("{0} installed games not found in AppData", _name.ToUpper());
                return;
            }
            else
            {
                string strDocumentData = File.ReadAllText(file);

                if (string.IsNullOrEmpty(strDocumentData))
                {
                    CLogger.LogWarn(string.Format("Malformed {0} file: {1}", _name.ToUpper(), file));
                }
                else
                {
                    try
                    {
                        using JsonDocument document = JsonDocument.Parse(@strDocumentData, jsonTrailingCommas);
                        foreach (JsonElement element in document.RootElement.EnumerateArray())
                        {
                            string strID     = "";
                            string strTitle  = "";
                            string strLaunch = "";
                            string strAlias  = "";

                            element.TryGetProperty("target", out JsonElement target);
                            if (!target.Equals(null))
                            {
                                target.TryGetProperty("item_data", out JsonElement item);
                                if (!item.Equals(null))
                                {
                                    strID = GetStringProperty(item, "id_key_name");
                                    igcIds.Add(strID);
                                    strTitle = GetStringProperty(item, "name");
                                }
                            }
                            element.TryGetProperty("path", out JsonElement paths);
                            if (!paths.Equals(null))
                            {
                                foreach (JsonElement path in paths.EnumerateArray())
                                {
                                    strLaunch = CGameFinder.FindGameBinaryFile(path.ToString(), strTitle);
                                }
                            }

                            CLogger.LogDebug($"- {strTitle}");

                            if (!string.IsNullOrEmpty(strLaunch))
                            {
                                strAlias = GetAlias(Path.GetFileNameWithoutExtension(strLaunch));
                                if (strAlias.Length > strTitle.Length)
                                {
                                    strAlias = GetAlias(strTitle);
                                }
                                if (strAlias.Equals(strTitle, CDock.IGNORE_CASE))
                                {
                                    strAlias = "";
                                }
                                gameDataList.Add(new ImportGameData(strID, strTitle, strLaunch, strLaunch, "", strAlias, true, strPlatform));
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        CLogger.LogError(e, string.Format("Malformed {0} file: {1}", _name.ToUpper(), file));
                    }
                }
            }

            // Get not-installed games
            if (!(bool)CConfig.GetConfigBool(CConfig.CFG_INSTONLY))
            {
                file = Path.Combine(GetFolderPath(SpecialFolder.ApplicationData), IG_OWN_JSON);
                if (!File.Exists(file))
                {
                    CLogger.LogInfo("{0} not-installed games not found in AppData", _name.ToUpper());
                }
                else
                {
                    CLogger.LogDebug("{0} not-installed games:", _name.ToUpper());

                    string strDocumentData = File.ReadAllText(file);

                    if (string.IsNullOrEmpty(strDocumentData))
                    {
                        CLogger.LogWarn(string.Format("Malformed {0} file: {1}", _name.ToUpper(), file));
                    }
                    else
                    {
                        try
                        {
                            using JsonDocument document = JsonDocument.Parse(@strDocumentData, jsonTrailingCommas);
                            bool        exists = false;
                            bool        found  = false;
                            JsonElement coll   = new();
                            document.RootElement.TryGetProperty("gala_data", out JsonElement gData);
                            if (!gData.Equals(null))
                            {
                                gData.TryGetProperty("data", out JsonElement data);
                                if (!data.Equals(null))
                                {
                                    data.TryGetProperty("showcase_content", out JsonElement sContent);
                                    if (!sContent.Equals(null))
                                    {
                                        sContent.TryGetProperty("content", out JsonElement content);
                                        if (!content.Equals(null))
                                        {
                                            content.TryGetProperty("user_collection", out coll);
                                            if (!coll.Equals(null))
                                            {
                                                exists = true;
                                            }
                                        }
                                    }
                                }
                            }

                            if (exists)
                            {
                                foreach (JsonElement prod in coll.EnumerateArray())
                                {
                                    string strID = GetStringProperty(prod, "prod_id_key_name");
                                    if (!string.IsNullOrEmpty(strID))
                                    {
                                        foreach (string id in igcIds)
                                        {
                                            if (id.Equals(strID))
                                            {
                                                found = true;
                                            }
                                        }
                                        if (!found)
                                        {
                                            string strTitle = GetStringProperty(prod, "prod_name");
                                            CLogger.LogDebug($"- *{strTitle}");
                                            gameDataList.Add(new ImportGameData(strID, strTitle, "", "", "", "", false, strPlatform));

                                            // Use prod_dev_image to download not-installed icons
                                            if (!(bool)(CConfig.GetConfigBool(CConfig.CFG_IMGDOWN)))
                                            {
                                                string devName = GetStringProperty(prod, "prod_dev_namespace");
                                                string image   = GetStringProperty(prod, "prod_dev_image");
                                                if (!string.IsNullOrEmpty(devName) && !string.IsNullOrEmpty(image))
                                                {
                                                    string iconUrl = $"https://www.indiegalacdn.com/imgs/devs/{devName}/products/{strID}/prodmain/{image}";
                                                    CDock.DownloadCustomImage(strTitle, iconUrl);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            CLogger.LogError(e, string.Format("Malformed {0} file: {1}", _name.ToUpper(), file));
                        }
                    }
                }
            }
            CLogger.LogDebug("--------------------");
        }
Пример #22
0
        public void GetGames(List <ImportGameData> gameDataList, bool expensiveIcons = false)
        {
            bool   error = false;
            string file  = Path.Combine(GetFolderPath(SpecialFolder.LocalApplicationData), PLARIUM_DB);

            /*
             * string launcherPath = "";
             * int? lang = 1;
             *
             * using (RegistryKey launcherKey = Registry.CurrentUser.OpenSubKey(PLARIUM_REG, RegistryKeyPermissionCheck.ReadSubTree)) // HKCU64
             * {
             *      if (launcherKey == null)
             *      {
             *              CLogger.LogInfo("{0} client not found in the registry.", _name.ToUpper());
             *              return;
             *      }
             *      launcherPath = GetRegStrVal(launcherKey, PLARIUM_FOLDER);
             *      lang = GetRegDWORDVal(launcherKey, "Language");
             * }
             */


            if (!File.Exists(file))
            {
                CLogger.LogInfo("{0} database not found.", _name.ToUpper());
                return;
            }
            try
            {
                while (true)
                {
                    string strDocumentData = File.ReadAllText(file);

                    if (string.IsNullOrEmpty(strDocumentData))
                    {
                        error = true;
                        break;
                    }

                    using JsonDocument document = JsonDocument.Parse(@strDocumentData, jsonTrailingCommas);
                    document.RootElement.TryGetProperty("InstalledGames", out JsonElement games);
                    if (games.Equals(null))
                    {
                        error = true;
                        break;
                    }

                    foreach (JsonProperty game in games.EnumerateObject())
                    {
                        CultureInfo ci = new("en-GB");
                        TextInfo    ti = ci.TextInfo;

                        string strID       = "";
                        string strTitle    = "";
                        string strLaunch   = "";
                        string strAlias    = "";
                        string strPlatform = GetPlatformString(ENUM);

                        foreach (JsonProperty gameVal in game.Value.EnumerateObject())
                        {
                            if (gameVal.Name.Equals("InsalledGames", CDock.IGNORE_CASE))
                            {
                                foreach (JsonProperty install in gameVal.Value.EnumerateObject())
                                {
                                    string num = install.Value.GetString();
                                    string id  = install.Name;
                                    strID = "plarium_" + id;
                                    string path = Path.Combine(GetFolderPath(SpecialFolder.LocalApplicationData), PLARIUM_GAMES, id, num);
                                    strLaunch = FindGameBinaryFile(path, id);
                                    string infoPath = Path.Combine(path, id + "_Data", "app.info");
                                    string jsonPath = Path.Combine(path, "settings.json");
                                    if (File.Exists(infoPath))
                                    {
                                        int i = 0;
                                        foreach (string line in File.ReadLines(infoPath))
                                        {
                                            if (i == 1)
                                            {
                                                strTitle = line.Trim();
                                                break;
                                            }
                                            i++;
                                        }
                                    }
                                    if (string.IsNullOrEmpty(strTitle) && File.Exists(jsonPath))
                                    {
                                        string strDocumentData2 = File.ReadAllText(jsonPath);
                                        if (!string.IsNullOrEmpty(strDocumentData2))
                                        {
                                            using JsonDocument document2 = JsonDocument.Parse(@strDocumentData2, jsonTrailingCommas);
                                            strTitle = GetStringProperty(document2.RootElement, "productName");
                                        }
                                    }
                                    if (string.IsNullOrEmpty(strTitle))
                                    {
                                        strTitle = ti.ToTitleCase(strID);
                                    }
                                    CLogger.LogDebug($"- {strTitle}");
                                    strAlias = GetAlias(Path.GetFileNameWithoutExtension(strLaunch));
                                    if (strAlias.Length > strTitle.Length)
                                    {
                                        strAlias = GetAlias(strTitle);
                                    }
                                    if (strAlias.Equals(strTitle, CDock.IGNORE_CASE))
                                    {
                                        strAlias = "";
                                    }
                                    if (!string.IsNullOrEmpty(strLaunch))
                                    {
                                        gameDataList.Add(new ImportGameData(strID, strTitle, strLaunch, strLaunch, "", strAlias, true, strPlatform));
                                    }
                                }
                            }
                        }
                    }
                    break;
                }
            }
            catch (Exception e)
            {
                CLogger.LogError(e, string.Format("Malformed {0} file: {1}", _name.ToUpper(), file));
            }

            if (error)
            {
                CLogger.LogInfo("Malformed {0} file: {1}", _name.ToUpper(), file);
                return;
            }
            CLogger.LogDebug("------------------------");
        }
Пример #23
0
        public void GetGames(List <ImportGameData> gameDataList, bool expensiveIcons = false)
        {
            List <string> azIds       = new();
            string        strPlatform = GetPlatformString(ENUM);

            // Get installed games
            string db = Path.Combine(GetFolderPath(SpecialFolder.LocalApplicationData), AMAZON_DB);

            if (!File.Exists(db))
            {
                CLogger.LogInfo("{0} installed game database not found.", _name.ToUpper());
                //return;
            }

            try
            {
                using SQLiteConnection con = new($"Data Source={db}");
                con.Open();

                using SQLiteCommand cmd    = new("SELECT Id, InstallDirectory, ProductTitle FROM DbSet;", con);
                using SQLiteDataReader rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    string dir   = rdr.GetString(1);
                    string strID = rdr.GetString(0);
                    azIds.Add(strID);
                    string strTitle = rdr.GetString(2);
                    CLogger.LogDebug($"- {strTitle}");
                    string strLaunch    = START_GAME + strID;
                    string strIconPath  = "";
                    string strUninstall = "";

                    using (RegistryKey key = Registry.CurrentUser.OpenSubKey(Path.Combine(NODE64_REG, "AmazonGames", strTitle), RegistryKeyPermissionCheck.ReadSubTree))
                    {
                        if (key != null)
                        {
                            strIconPath  = GetRegStrVal(key, "DisplayIcon");
                            strUninstall = GetRegStrVal(key, "UninstallString");
                        }
                    }
                    if (string.IsNullOrEmpty(strIconPath))
                    {
                        if (expensiveIcons)
                        {
                            bool   success  = false;
                            string fuelPath = Path.Combine(dir, "fuel.json");
                            if (File.Exists(fuelPath))
                            {
                                string strDocumentData = File.ReadAllText(fuelPath);

                                if (!string.IsNullOrEmpty(strDocumentData))
                                {
                                    using JsonDocument document = JsonDocument.Parse(@strDocumentData, jsonTrailingCommas);
                                    document.RootElement.TryGetProperty("Main", out JsonElement main);
                                    if (!main.Equals(null))
                                    {
                                        string iconFile = GetStringProperty(main, "Command");
                                        if (!string.IsNullOrEmpty(strIconPath))
                                        {
                                            strIconPath = Path.Combine(dir, iconFile);
                                            success     = true;
                                        }
                                    }
                                }
                            }
                            if (!success)
                            {
                                strIconPath = CGameFinder.FindGameBinaryFile(dir, strTitle);
                            }
                        }
                    }
                    if (string.IsNullOrEmpty(strUninstall))
                    {
                        strUninstall = Path.Combine(Directory.GetParent(dir).FullName, UNINST_GAME) + " " + UNINST_GAME_ARGS + " " + strID;
                    }
                    string strAlias = GetAlias(strTitle);

                    if (!string.IsNullOrEmpty(strLaunch))
                    {
                        if (strAlias.Equals(strTitle, CDock.IGNORE_CASE))
                        {
                            strAlias = "";
                        }
                        gameDataList.Add(new ImportGameData(strID, strTitle, strLaunch, strIconPath, strUninstall, strAlias, true, strPlatform));
                    }
                }
                con.Close();
            }
            catch (Exception e)
            {
                CLogger.LogError(e, string.Format("Malformed {0} database output!", _name.ToUpper()));
            }

            // Get not-installed games
            if (!(bool)CConfig.GetConfigBool(CConfig.CFG_INSTONLY))
            {
                db = Path.Combine(GetFolderPath(SpecialFolder.LocalApplicationData), AMAZON_OWN_DB);
                if (!File.Exists(db))
                {
                    CLogger.LogInfo("{0} not-installed game database not found.", _name.ToUpper());
                }
                else
                {
                    CLogger.LogDebug("{0} not-installed games:", _name.ToUpper());
                    try
                    {
                        using SQLiteConnection con = new($"Data Source={db}");
                        con.Open();

                        using SQLiteCommand cmd    = new("SELECT Id, ProductIconUrl, ProductIdStr, ProductTitle FROM DbSet;", con);
                        using SQLiteDataReader rdr = cmd.ExecuteReader();
                        while (rdr.Read())
                        {
                            bool   found = false;
                            string strID = rdr.GetString(2); // TODO: Should I use Id or ProductIdStr?
                            foreach (string id in azIds)
                            {
                                if (id.Equals(strID))
                                {
                                    found = true;
                                }
                            }
                            if (!found)
                            {
                                string strTitle = rdr.GetString(3);
                                CLogger.LogDebug($"- *{strTitle}");
                                gameDataList.Add(new ImportGameData(strID, strTitle, "", "", "", "", false, strPlatform));

                                // Use ProductIconUrl to download not-installed icons
                                if (!(bool)(CConfig.GetConfigBool(CConfig.CFG_IMGDOWN)))
                                {
                                    string iconUrl = rdr.GetString(1);
                                    CDock.DownloadCustomImage(strTitle, iconUrl);
                                }
                            }
                        }
                        con.Close();
                    }
                    catch (Exception e)
                    {
                        CLogger.LogError(e, string.Format("Malformed {0} database output!", _name.ToUpper()));
                    }
                }
            }
            CLogger.LogDebug("-------------------");
        }
Пример #24
0
        public void GetGames(List <ImportGameData> gameDataList, bool expensiveIcons = false)
        {
            Dictionary <string, string> installDict = new();
            List <RegistryKey>          keyList;

            /*
             * string launcherPath = "";
             *
             * using (RegistryKey launcherKey = Registry.CurrentUser.OpenSubKey(Path.Combine(NODE64_REG, WARGAMING_UNREG), RegistryKeyPermissionCheck.ReadSubTree)) // HKCU64
             * {
             *      if (launcherKey == null)
             *      {
             *              CLogger.LogInfo("{0} client not found in the registry.", _name.ToUpper());
             *              return;
             *      }
             *      launcherPath = GetRegStrVal(launcherKey, GAME_DISPLAY_ICON);
             *      int pathIndex = launcherPath.IndexOf(",");
             *      if (pathIndex > -1)
             *              launcherPath = launcherPath.Substring(0, pathIndex);
             * }
             */
            string dataPath = Path.Combine(GetFolderPath(SpecialFolder.CommonApplicationData), WARGAMING_DATA);

            try
            {
                if (Directory.Exists(dataPath))
                {
                    foreach (var dir in Directory.EnumerateDirectories(dataPath))
                    {
                        foreach (var file in Directory.EnumerateFiles(dir))
                        {
                            foreach (string line in File.ReadLines(file))
                            {
                                installDict.Add(Path.GetFileName(dir).ToUpper(), line.Trim());
                                break;
                            }
                            break;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                CLogger.LogError(e);
            }

            using (RegistryKey key = Registry.CurrentUser.OpenSubKey(NODE64_REG, RegistryKeyPermissionCheck.ReadSubTree))             // HKCU64
            {
                keyList = FindGameKeys(key, "Wargaming.net", "Publisher", new string[] { WARGAMING_UNREG });

                CLogger.LogInfo("{0} {1} games found", keyList.Count, _name.ToUpper());
                foreach (var data in keyList)
                {
                    string strID        = "";
                    string strTitle     = "";
                    string strLaunch    = "";
                    string strIconPath  = "";
                    string strUninstall = "";
                    string strAlias     = "";
                    string strPlatform  = GetPlatformString(ENUM);

                    try
                    {
                        strID    = Path.GetFileName(data.Name).ToUpper();
                        strTitle = GetRegStrVal(data, GAME_DISPLAY_NAME);
                        CLogger.LogDebug($"- {strTitle}");
                        string installPath = GetRegStrVal(data, GAME_INSTALL_LOCATION);
                        installDict.Remove(strID);
                        //installDict.Remove(installPath);
                        strLaunch   = FindGameBinaryFile(installPath, strTitle);
                        strIconPath = GetRegStrVal(data, GAME_DISPLAY_ICON);
                        int iconIndex = strIconPath.IndexOf(',');
                        if (iconIndex > -1)
                        {
                            strIconPath = strIconPath.Substring(0, iconIndex);
                        }
                        strUninstall = GetRegStrVal(data, GAME_UNINSTALL_STRING);
                        strAlias     = GetAlias(Path.GetFileNameWithoutExtension(strLaunch.Trim(new char[] { ' ', '\'', '"' })));
                        if (strAlias.Length > strTitle.Length)
                        {
                            strAlias = GetAlias(strTitle);
                        }
                        if (strAlias.Equals(strTitle, CDock.IGNORE_CASE))
                        {
                            strAlias = "";
                        }
                    }
                    catch (Exception e)
                    {
                        CLogger.LogError(e);
                    }
                    if (!(string.IsNullOrEmpty(strLaunch)))
                    {
                        gameDataList.Add(
                            new ImportGameData(strID, strTitle, strLaunch, strIconPath, strUninstall, strAlias, true, strPlatform));
                    }
                }
            }

            foreach (var kv in installDict)
            {
                string path        = kv.Value;
                string strID       = kv.Key;
                string strTitle    = "";
                string strLaunch   = "";
                string strIconPath = "";
                string strAlias    = "";
                string strPlatform = GetPlatformString(ENUM);

                try
                {
                    string xmlPath = Path.Combine(path, "game_metadata", "metadata.xml");
                    if (File.Exists(xmlPath))
                    {
                        XmlDocument doc = new();
                        doc.Load(xmlPath);
                        foreach (XmlNode exeNode in
                                 doc.SelectSingleNode("/protocol/predefined_section/executables").ChildNodes)
                        {
                            XmlAttribute arch = exeNode.Attributes["arch"];
                            if (arch != null && arch.Value.Equals("x64", CDock.IGNORE_CASE))
                            {
                                strLaunch = Path.Combine(path, exeNode.InnerText);
                            }
                            if (string.IsNullOrEmpty(strLaunch))
                            {
                                strLaunch = exeNode.InnerText;
                            }
                        }
                        XmlNode name = doc.SelectSingleNode("/protocol/predefined_section/name");
                        if (name != null && !string.IsNullOrEmpty(name.InnerText))
                        {
                            strTitle = name.InnerText;
                        }
                    }
                    if (string.IsNullOrEmpty(strLaunch))
                    {
                        strLaunch = FindGameBinaryFile(path, strID);
                    }
                    if (string.IsNullOrEmpty(strTitle))
                    {
                        strTitle = Path.GetFileNameWithoutExtension(strLaunch);
                    }
                    CLogger.LogDebug($"- {strTitle}");
                    if (expensiveIcons)
                    {
                        strIconPath = Path.Combine(path, "game_metadata", "game.ico");
                        if (!File.Exists(strIconPath))
                        {
                            strIconPath = strLaunch;
                        }
                    }
                    else
                    {
                        strIconPath = strLaunch;
                    }
                    strAlias = GetAlias(Path.GetFileNameWithoutExtension(strLaunch.Trim(new char[] { ' ', '\'', '"' })));
                    if (strAlias.Length > strTitle.Length)
                    {
                        strAlias = GetAlias(strTitle);
                    }
                    if (strAlias.Equals(strTitle, CDock.IGNORE_CASE))
                    {
                        strAlias = "";
                    }
                    if (!(string.IsNullOrEmpty(strLaunch)))
                    {
                        gameDataList.Add(
                            new ImportGameData(strID, strTitle, strLaunch, strIconPath, "", strAlias, true, strPlatform));
                    }
                }
                catch (Exception e)
                {
                    CLogger.LogError(e);
                }
            }
            CLogger.LogDebug("------------------------");
        }
Пример #25
0
Файл: Riot.cs Проект: Nutzzz/GLC
        public void GetGames(List <ImportGameData> gameDataList, bool expensiveIcons = false)
        {
            string dataPath = Path.Combine(GetFolderPath(SpecialFolder.CommonApplicationData), RIOT_FOLDER);

            try
            {
                if (Directory.Exists(dataPath))
                {
                    // Should we use YamlDotNet parser?

                    string strClientPath = "";

                    var clientFile = Path.Combine(dataPath, RIOT_CLIENT_FILE);
                    if (File.Exists(clientFile))
                    {
                        string strDocumentData = File.ReadAllText(clientFile);

                        if (!string.IsNullOrEmpty(strDocumentData))
                        {
                            using JsonDocument document = JsonDocument.Parse(@strDocumentData, jsonTrailingCommas);
                            strClientPath = GetStringProperty(document.RootElement, "rc_live");
                        }
                    }

                    string metaPath = Path.Combine(dataPath, "Metadata");
                    if (Directory.Exists(metaPath))
                    {
                        foreach (var dir in Directory.EnumerateDirectories(metaPath))
                        {
                            string path         = "";
                            string strID        = Path.GetFileName(dir);
                            string strTitle     = "";
                            string strLaunch    = "";
                            string strIconPath  = "";
                            string strUninstall = "";
                            string strAlias     = "";
                            string strPlatform  = GetPlatformString(ENUM);

                            foreach (var settingsFile in Directory.EnumerateFiles(dir, "*.yaml"))
                            {
                                foreach (string line in File.ReadLines(settingsFile))
                                {
                                    if (line.StartsWith("product_install_full_path"))
                                    {
                                        path = line.Substring(line.IndexOf('"')).Trim().Trim('"');
                                    }
                                    else if (line.StartsWith("shortcut_name"))
                                    {
                                        strTitle = Path.GetFileNameWithoutExtension(line.Substring(line.IndexOf('"')).Trim().Trim('"'));
                                    }
                                }
                                break;
                            }
                            foreach (var iconFile in Directory.EnumerateFiles(dir, "*.ico"))
                            {
                                strIconPath = iconFile;
                                break;
                            }
                            if (!string.IsNullOrEmpty(strTitle))
                            {
                                strLaunch = FindGameBinaryFile(path, strTitle);
                                if (!string.IsNullOrEmpty(strLaunch))
                                {
                                    if (string.IsNullOrEmpty(strIconPath))
                                    {
                                        strIconPath = strLaunch;
                                    }
                                    if (!string.IsNullOrEmpty(strClientPath))
                                    {
                                        strUninstall = "\"" + strClientPath + "\" --uninstall-product=" + Path.GetFileNameWithoutExtension(strID) + " --uninstall-patchline=live";
                                    }
                                    strAlias = GetAlias(strTitle);
                                    if (strAlias.Equals(strTitle, CDock.IGNORE_CASE))
                                    {
                                        strAlias = "";
                                    }
                                    gameDataList.Add(new ImportGameData(strID, strTitle, strLaunch, strIconPath, strUninstall, strAlias, true, strPlatform));
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                CLogger.LogError(e);
            }
            CLogger.LogDebug("------------------------");
        }
Пример #26
0
        public void GetGames(List <ImportGameData> gameDataList, bool expensiveIcons = false)
        {
            string strInstallPath = "";
            string strClientPath  = "";

            using (RegistryKey key = Registry.LocalMachine.OpenSubKey(STEAM_REG, RegistryKeyPermissionCheck.ReadSubTree))             // HKLM32
            {
                if (key == null)
                {
                    CLogger.LogInfo("{0} client not found in the registry.", _name.ToUpper());
                    return;
                }

                strInstallPath = GetRegStrVal(key, GAME_INSTALL_PATH);
                strClientPath  = Path.Combine(strInstallPath, STEAM_PATH);
            }

            if (!Directory.Exists(strClientPath))
            {
                CLogger.LogInfo("{0} library not found: {1}", _name.ToUpper(), strClientPath);
                return;
            }

            string        libFile = Path.Combine(strClientPath, STEAM_LIBFILE);
            List <string> libs    = new()
            {
                strClientPath
            };
            int nLibs = 1;

            try
            {
                if (File.Exists(libFile))
                {
                    SteamWrapper document     = new(libFile);
                    ACF_Struct   documentData = document.ACFFileToStruct();
                    ACF_Struct   folders      = new();
                    if (documentData.SubACF.ContainsKey(STEAM_LIBARR))
                    {
                        folders = documentData.SubACF[STEAM_LIBARR];
                    }
                    else if (documentData.SubACF.ContainsKey(STEAM_LIBARR.ToLower()))
                    {
                        folders = documentData.SubACF[STEAM_LIBARR.ToLower()];
                    }
                    for (; nLibs <= STEAM_MAX_LIBS; ++nLibs)
                    {
                        folders.SubItems.TryGetValue(nLibs.ToString(), out string library);
                        if (string.IsNullOrEmpty(library))
                        {
                            if (folders.SubACF.ContainsKey(nLibs.ToString()))
                            {
                                folders.SubACF[nLibs.ToString()].SubItems.TryGetValue("path", out library);
                            }
                            if (string.IsNullOrEmpty(library))
                            {
                                nLibs--;
                                break;
                            }
                        }
                        library = Path.Combine(library, STEAM_PATH);
                        if (!library.Equals(strClientPath) && Directory.Exists(library))
                        {
                            libs.Add(library);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                CLogger.LogError(e, string.Format("Malformed {0} file: {1}", _name.ToUpper(), libFile));
                nLibs--;
            }

            int           i        = 0;
            List <string> allFiles = new();

            foreach (string lib in libs)
            {
                List <string> libFiles = new();
                try
                {
                    libFiles = Directory.GetFiles(lib, "appmanifest_*.acf", SearchOption.TopDirectoryOnly).ToList();
                    allFiles.AddRange(libFiles);
                    CLogger.LogInfo("{0} {1} games found in library {2}", libFiles.Count, _name.ToUpper(), lib);
                }
                catch (Exception e)
                {
                    CLogger.LogError(e, string.Format("{0} directory read error: {1}", _name.ToUpper(), lib));
                    continue;
                }

                foreach (string file in libFiles)
                {
                    try
                    {
                        SteamWrapper document     = new(file);
                        ACF_Struct   documentData = document.ACFFileToStruct();
                        ACF_Struct   app          = documentData.SubACF["AppState"];

                        string id = app.SubItems["appid"];
                        if (id.Equals("228980"))                          // Steamworks Common Redistributables
                        {
                            continue;
                        }

                        string strID    = Path.GetFileName(file);
                        string strTitle = app.SubItems["name"];
                        CLogger.LogDebug($"- {strTitle}");
                        string strLaunch    = START_GAME + "/" + id;
                        string strIconPath  = "";
                        string strUninstall = "";
                        string strAlias     = "";
                        string strPlatform  = GetPlatformString(ENUM);

                        strAlias = GetAlias(strTitle);
                        if (!string.IsNullOrEmpty(strLaunch))
                        {
                            using (RegistryKey key = Registry.LocalMachine.OpenSubKey(Path.Combine(NODE64_REG, STEAM_GAME_PREFIX + id), RegistryKeyPermissionCheck.ReadSubTree),                              // HKLM64
                                   key2 = Registry.LocalMachine.OpenSubKey(Path.Combine(NODE32_REG, STEAM_GAME_PREFIX + id), RegistryKeyPermissionCheck.ReadSubTree))                                         // HKLM32
                            {
                                if (key != null)
                                {
                                    strIconPath = GetRegStrVal(key, GAME_DISPLAY_ICON).Trim(new char[] { ' ', '"' });
                                }
                                else if (key2 != null)
                                {
                                    strIconPath = GetRegStrVal(key2, GAME_DISPLAY_ICON).Trim(new char[] { ' ', '"' });
                                }
                            }
                            if (string.IsNullOrEmpty(strIconPath) && expensiveIcons)
                            {
                                bool success = false;

                                // Search for an .exe to use as icon
                                strIconPath = CGameFinder.FindGameBinaryFile(Path.Combine(lib, "common", app.SubItems["installdir"]), strTitle);
                                if (!string.IsNullOrEmpty(strIconPath))
                                {
                                    success  = true;
                                    strAlias = GetAlias(Path.GetFileNameWithoutExtension(strIconPath));
                                    if (strAlias.Length > strTitle.Length)
                                    {
                                        strAlias = GetAlias(strTitle);
                                    }
                                }

                                if (!success && !(bool)(CConfig.GetConfigBool(CConfig.CFG_IMGDOWN)))
                                {
                                    // Download missing icons
                                    string iconUrl = $"https://cdn.cloudflare.steamstatic.com/steam/apps/{id}/capsule_184x69.jpg";
                                    if (CDock.DownloadCustomImage(strTitle, iconUrl))
                                    {
                                        success = true;
                                    }
                                }
                            }
                            if (strAlias.Equals(strTitle, CDock.IGNORE_CASE))
                            {
                                strAlias = "";
                            }
                            strUninstall = UNINST_GAME + "/" + id;
                            gameDataList.Add(new ImportGameData(strID, strTitle, strLaunch, strIconPath, strUninstall, strAlias, true, strPlatform));
                        }
                    }
                    catch (Exception e)
                    {
                        CLogger.LogError(e, string.Format("Malformed {0} file: {1}", _name.ToUpper(), file));
                    }
                }
                i++;

                /*
                 * if (i > nLibs)
                 *      CLogger.LogDebug("---------------------");
                 */
            }

            // Get not-installed games
            if (!(bool)CConfig.GetConfigBool(CConfig.CFG_INSTONLY))
            {
                // First get Steam user ID
                ulong userId = (ulong)CConfig.GetConfigULong(CConfig.CFG_STEAMID);

                if (userId < 1)
                {
                    try
                    {
                        ulong  userIdTmp     = 0;
                        string userName      = "";
                        string userNameTmp   = "";
                        string strConfigPath = Path.Combine(strInstallPath, "config");
                        string appFile       = Path.Combine(strConfigPath, STEAM_APPFILE);

                        if (File.Exists(appFile))
                        {
                            SteamWrapper appDoc     = new(appFile);
                            ACF_Struct   appDocData = appDoc.ACFFileToStruct();
                            ACF_Struct   appData    = appDocData.SubACF["SteamAppData"];

                            appData.SubItems.TryGetValue("AutoLoginUser", out userName);

                            SteamWrapper usrDoc     = new(Path.Combine(strConfigPath, STEAM_USRFILE));
                            ACF_Struct   usrDocData = usrDoc.ACFFileToStruct();
                            ACF_Struct   usrData    = usrDocData.SubACF["users"];

                            foreach (KeyValuePair <string, ACF_Struct> user in usrData.SubACF)
                            {
                                if (!ulong.TryParse(user.Key, out userIdTmp))
                                {
                                    userIdTmp = 0;
                                }

                                foreach (KeyValuePair <string, string> userVal in user.Value.SubItems)
                                {
                                    if (userVal.Key.Equals("AccountName"))
                                    {
                                        userNameTmp = userVal.Value;
                                        if (userNameTmp.Equals(userName))
                                        {
                                            if (!ulong.TryParse(user.Key, out userId))
                                            {
                                                userId = 0;
                                            }
                                        }
                                    }
                                    if (userVal.Key.Equals("MostRecent") && userVal.Value.Equals("1") && string.IsNullOrEmpty(userName))
                                    {
                                        userId   = userIdTmp;
                                        userName = userNameTmp;
                                        break;
                                    }
                                }
                            }
                            if (userId < 1)
                            {
                                userId   = userIdTmp;
                                userName = userNameTmp;
                            }
                        }
                        if (userId > 0)
                        {
                            CLogger.LogInfo("Setting default {0} user to {1} #{2}", _name.ToUpper(), userName, userId);
                            CConfig.SetConfigValue(CConfig.CFG_STEAMID, userId);
                            ExportConfig();
                        }
                    }
                    catch (Exception e)
                    {
                        CLogger.LogError(e, string.Format("Malformed {0} file: {1} or {2}", _name.ToUpper(), STEAM_APPFILE, STEAM_USRFILE));
                    }
                }

                if (userId > 0)
                {
                    // Download game list from public user profile
                    try
                    {
                        string url = string.Format("https://steamcommunity.com/profiles/{0}/games/?tab=all", userId);

                        /*
                         #if DEBUG
                         * // Don't re-download if file exists
                         * string tmpfile = $"tmp_{NAME}.html";
                         * if (!File.Exists(tmpfile))
                         * {
                         *      using (var client = new WebClient());
                         *      client.DownloadFile(url, tmpfile);
                         * }
                         * HtmlDocument doc = new HtmlDocument
                         * {
                         *      OptionUseIdAttribute = true
                         * };
                         * doc.Load(tmpfile);
                         #else
                         */
                        HtmlWeb web = new()
                        {
                            UseCookies = true
                        };
                        HtmlDocument doc = web.Load(url);
                        doc.OptionUseIdAttribute = true;
//#endif
                        HtmlNode gameList = doc.DocumentNode.SelectSingleNode("//script[@language='javascript']");
                        if (gameList != null)
                        {
                            CLogger.LogDebug("{0} not-installed games (user #{1}):", _name.ToUpper(), userId);

                            var options = new JsonDocumentOptions
                            {
                                AllowTrailingCommas = true
                            };
                            string rgGames = gameList.InnerText.Remove(0, gameList.InnerText.IndexOf('['));
                            rgGames = rgGames.Remove(rgGames.IndexOf(';'));

                            using JsonDocument document = JsonDocument.Parse(@rgGames, options);
                            foreach (JsonElement game in document.RootElement.EnumerateArray())
                            {
                                ulong id = GetULongProperty(game, "appid");
                                if (id > 0)
                                {
                                    // Check if game is already installed
                                    string strID = $"appmanifest_{id}.acf";
                                    bool   found = false;
                                    foreach (string file in allFiles)
                                    {
                                        if (file.EndsWith(strID))
                                        {
                                            found = true;
                                        }
                                    }
                                    if (!found)
                                    {
                                        string strTitle    = GetStringProperty(game, "name");
                                        string strPlatform = GetPlatformString(ENUM);

                                        // Add not-installed games
                                        CLogger.LogDebug($"- *{strTitle}");
                                        gameDataList.Add(new ImportGameData(strID, strTitle, "", "", "", "", false, strPlatform));

                                        // Use logo to download not-installed icons
                                        if (!(bool)(CConfig.GetConfigBool(CConfig.CFG_IMGDOWN)))
                                        {
                                            string iconUrl = GetStringProperty(game, "logo");
                                            CDock.DownloadCustomImage(strTitle, iconUrl);
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            CLogger.LogInfo("Can't get not-installed {0} games. Profile may not be public.\n" +
                                            "To change this, go to <https://steamcommunity.com/my/edit/settings>.",
                                            _name.ToUpper());
                        }

                        /*
                         #if DEBUG
                         *      File.Delete(tmpfile);
                         #endif
                         */
                    }
                    catch (Exception e)
                    {
                        CLogger.LogError(e);
                    }
                    CLogger.LogDebug("---------------------");
                }
            }
        }
Пример #27
0
        public void GetGames(List <ImportGameData> gameDataList, bool expensiveIcons = false)
        {
            List <RegistryKey> keyList     = new();
            string             strPlatform = GetPlatformString(ENUM);

            //string arcFolder = Path.Combine(GetFolderPath(SpecialFolder.ApplicationData), "Arc"); // AppData\Roaming

            /*
             * string launcherPath = "";
             *
             * using (RegistryKey launcherKey = Registry.LocalMachine.OpenSubKey(Path.Combine(ARC_REG, "Arc"), RegistryKeyPermissionCheck.ReadSubTree)) // HKLM32
             * {
             *      if (launcherKey == null)
             *      {
             *              CLogger.LogInfo("{0} client not found in the registry.", _name.ToUpper());
             *              return;
             *      }
             *      launcherPath = GetRegStrVal(launcherKey, "client");
             * }
             */

            using (RegistryKey key = Registry.LocalMachine.OpenSubKey(Path.Combine(ARC_REG, ARC_GAMES), RegistryKeyPermissionCheck.ReadSubTree)) // HKLM32
            {
                foreach (string subKey in key.GetSubKeyNames())                                                                                  // Add subkeys to search list
                {
                    try
                    {
                        if (subKey.IndexOf("en") > -1)
                        {
                            keyList.Add(key.OpenSubKey(subKey, RegistryKeyPermissionCheck.ReadSubTree));
                        }
                    }
                    catch (Exception e)
                    {
                        CLogger.LogError(e);
                    }
                }
                CLogger.LogInfo("{0} {1} games found", keyList.Count, _name.ToUpper());
                foreach (var data in keyList)
                {
                    string id = GetRegStrVal(data, ARC_ID);
                    if (string.IsNullOrEmpty(id))
                    {
                        id = Path.GetFileName(data.Name);
                        int idIndex = id.IndexOf("en");
                        if (idIndex > -1)
                        {
                            id = id.Substring(0, idIndex);
                        }
                    }
                    string name      = Path.GetFileName(GetRegStrVal(data, ARC_PATH).Trim(new char[] { '"', '\\', '/' }));
                    int    nameIndex = name.IndexOf("_en");
                    if (nameIndex > -1)
                    {
                        name = name.Substring(0, nameIndex);
                    }
                    string strID      = "";
                    string strTitle   = "";
                    string strLaunch  = "";
                    string strAlias   = "";
                    bool   bInstalled = true;

                    try
                    {
                        strID = "arc_" + id;
                        if (!string.IsNullOrEmpty(name))
                        {
                            strTitle = name;
                        }
                        else
                        {
                            strTitle = id;
                        }
                        CLogger.LogDebug($"- {strTitle}");
                        strLaunch = GetRegStrVal(data, ARC_EXEPATH);
                        strAlias  = GetAlias(Path.GetFileNameWithoutExtension(strLaunch));
                        if (strAlias.Length > strTitle.Length)
                        {
                            strAlias = GetAlias(strTitle);
                        }
                        if (strAlias.Equals(strTitle, CDock.IGNORE_CASE))
                        {
                            strAlias = "";
                        }
                        int?installed = GetRegDWORDVal(data, ARC_INST);
                        if (installed != null && installed == 0)
                        {
                            bInstalled = false;
                        }
                    }
                    catch (Exception e)
                    {
                        CLogger.LogError(e);
                    }
                    if (!(string.IsNullOrEmpty(strLaunch)))
                    {
                        gameDataList.Add(
                            new ImportGameData(strID, strTitle, strLaunch, strLaunch, "", strAlias, bInstalled, strPlatform));
                    }
                }
            }
            CLogger.LogDebug("------------------------");
        }
Пример #28
0
        private UnzipStatus UnzipOrMoveTempToAsset(string tempFileName, int unzipTaskIndex, int maxUnzipTasks)
        {
            UnzipStatus status       = UnzipStatus.Success;
            string      tempFullPath = FileUtils.LocalTempResRootPath + tempFileName;

            if (tempFullPath.EndsWith(".zip"))
            {
                List <string> allUnzipFileNames;
                CLogger.Log("GameUpdateMgr::UnzipOrMoveTempToAsset() - Start unzip file, fullName=" + tempFileName);
                //EventHandler<Ionic.Zip.ExtractProgressEventArgs> extractProgress = (object sender, Ionic.Zip.ExtractProgressEventArgs e) =>
                //{
                //    _totalUnzipProgress = (unzipTaskIndex + (float)e.BytesTransferred / e.TotalBytesToTransfer) / maxUnzipTasks;
                //};
                status = ZipUtil.UnZip(tempFullPath, FileUtils.LocalResRootPath, out allUnzipFileNames);
                if (status == UnzipStatus.Success)
                {
                    CLogger.Log("GameUpdateMgr::UnzipOrMoveTempToAsset() - Unzip file success, fullName=" + tempFileName);
                    for (int i = 0; i < allUnzipFileNames.Count; i++)
                    {
                        VersionMgr.Instance.UpdateLocalCacheData(allUnzipFileNames[i]);
                    }

                    //EventCenter.Broadcast((int)HotUpdateEventType.UnzipFileNotify, allUnzipFileNames);
                    MainThreadRunner.Instance.RunOnMainThread(() => { EventCenter.Broadcast((int)HotUpdateEventType.UnzipFileNotify, allUnzipFileNames.ToArray()); });
                }
                else
                {
                    CLogger.Log("GameUpdateMgr::UnzipOrMoveTempToAsset() - Unzip file faild, fullName=" + tempFileName);
                }
            }
            else
            {
                try
                {
                    //string dstAssetPath = FileUtils.Instance.FullPathForFile(tempFileName, ResourceType.ASSET_BUNDLE);
                    string dstAssetPath = PathManager.URL(tempFileName, AssetLoad.AssetType.eNone, false);
                    if (File.Exists(dstAssetPath))
                    {
                        File.Delete(dstAssetPath);
                    }
                    FileUtils.Instance.CheckDirExistsForFile(dstAssetPath);
                    File.Copy(tempFullPath, dstAssetPath);
                    VersionMgr.Instance.UpdateLocalCacheData(tempFileName);

                    MainThreadRunner.Instance.RunOnMainThread(() => {
                        List <string> allUnzipFileNames = new List <string>();
                        allUnzipFileNames.Add(tempFileName);
                        EventCenter.Broadcast((int)HotUpdateEventType.UnzipFileNotify, allUnzipFileNames.ToArray());
                    });
                }
                catch (Exception e)
                {
                    CLogger.LogError("GameUpdateMgr::UnzipOrMoveTempToAsset() - Exception: " + e.Message);
                    if (e.Message.Contains("Disk full"))
                    {
                        status = UnzipStatus.DiskFull;
                    }
                    status = UnzipStatus.Exception;
                }
            }
            return(status);
        }
Пример #29
0
        public void GetGames(List <ImportGameData> gameDataList, bool expensiveIcons = false)
        {
            List <RegistryKey> keyList;
            List <string>      uplayIds     = new();
            List <string>      uplayIcons   = new();
            string             launcherPath = "";
            string             strPlatform  = GetPlatformString(ENUM);

            using (RegistryKey launcherKey = Registry.LocalMachine.OpenSubKey(Path.Combine(NODE32_REG, UPLAY_UNREG), RegistryKeyPermissionCheck.ReadSubTree))             // HKLM32
            {
                if (launcherKey == null)
                {
                    CLogger.LogInfo("{0} client not found in the registry.", _name.ToUpper());
                    return;
                }
                launcherPath = GetRegStrVal(launcherKey, GAME_INSTALL_LOCATION);
            }

            using (RegistryKey key = Registry.LocalMachine.OpenSubKey(NODE32_REG, RegistryKeyPermissionCheck.ReadSubTree))             // HKLM32
            {
                keyList = FindGameFolders(key, UPLAY_PREFIX);

                CLogger.LogInfo("{0} {1} games found", keyList.Count, _name.ToUpper());
                foreach (var data in keyList)
                {
                    string loc = GetRegStrVal(data, GAME_INSTALL_LOCATION);

                    string strID        = "";
                    string strTitle     = "";
                    string strLaunch    = "";
                    string strIconPath  = "";
                    string strUninstall = "";
                    string strAlias     = "";
                    try
                    {
                        strID = Path.GetFileName(data.Name);
                        uplayIds.Add(strID);
                        strTitle = GetRegStrVal(data, GAME_DISPLAY_NAME);
                        CLogger.LogDebug($"- {strTitle}");
                        strLaunch   = START_GAME + GetGameID(strID);
                        strIconPath = GetRegStrVal(data, GAME_DISPLAY_ICON).Trim(new char[] { ' ', '"' });
                        uplayIcons.Add(strIconPath);
                        if (string.IsNullOrEmpty(strIconPath) && expensiveIcons)
                        {
                            strIconPath = CGameFinder.FindGameBinaryFile(loc, strTitle);
                        }
                        strUninstall = GetRegStrVal(data, GAME_UNINSTALL_STRING);                         //.Trim(new char[] { ' ', '"' });
                        strAlias     = GetAlias(Path.GetFileNameWithoutExtension(loc.Trim(new char[] { ' ', '\'', '"' }).Trim(new char[] { '/', '\\' })));
                        if (strAlias.Length > strTitle.Length)
                        {
                            strAlias = GetAlias(strTitle);
                        }
                        if (strAlias.Equals(strTitle, CDock.IGNORE_CASE))
                        {
                            strAlias = "";
                        }
                    }
                    catch (Exception e)
                    {
                        CLogger.LogError(e);
                    }
                    if (!(string.IsNullOrEmpty(strLaunch)))
                    {
                        gameDataList.Add(
                            new ImportGameData(strID, strTitle, strLaunch, strIconPath, strUninstall, strAlias, true, strPlatform));
                    }
                }
            }

            // Get not-installed games
            if (!(bool)CConfig.GetConfigBool(CConfig.CFG_INSTONLY) && !(string.IsNullOrEmpty(launcherPath)))
            {
                string uplayCfgFile = Path.Combine(launcherPath, @"cache\configuration\configurations");
                try
                {
                    if (File.Exists(uplayCfgFile))
                    {
                        char[]        trimChars   = { ' ', '\'', '"' };
                        List <string> uplayCfg    = new();
                        int           nGames      = 0;
                        bool          dlc         = false;
                        string        strID       = "";
                        string        strTitle    = "";
                        string        strIconPath = "";

                        CLogger.LogDebug("{0} not-installed games:", _name.ToUpper());
                        uplayCfg.AddRange(File.ReadAllLines(uplayCfgFile));
                        foreach (string line in uplayCfg)                          // Note if the last game is valid, this method won't catch it; but that appears very unlikely
                        {
                            if (line.Trim().StartsWith("root:"))
                            {
                                if (nGames > 0 && !(string.IsNullOrEmpty(strID)) && dlc == false)
                                {
                                    bool found = false;
                                    foreach (string id in uplayIds)
                                    {
                                        if (id.Equals(strID))
                                        {
                                            found = true;
                                        }
                                    }
                                    if (!found)
                                    {
                                        // The Uplay ID is not always available, so this is an alternative test
                                        // However, if user has e.g., a demo and the full game installed, this might get a false negative
                                        foreach (string icon in uplayIcons)
                                        {
                                            if (Path.GetFileName(icon).Equals(Path.GetFileName(strIconPath)))
                                            {
                                                found = true;
                                            }
                                        }
                                    }
                                    if (!found)
                                    {
                                        strTitle = strTitle.Replace("''", "'");
                                        CLogger.LogDebug($"- *{strTitle}");
                                        gameDataList.Add(
                                            new ImportGameData(strID, strTitle, "", strIconPath, "", "", false, strPlatform));
                                    }
                                }

                                nGames++;
                                dlc         = false;
                                strID       = "";
                                strTitle    = "";
                                strIconPath = "";
                            }

                            if (dlc == true)
                            {
                                continue;
                            }
                            else if (line.Trim().StartsWith("is_dlc: yes"))
                            {
                                dlc = true;
                                continue;
                            }
                            else if (string.IsNullOrEmpty(strTitle) && line.Trim().StartsWith("name: "))
                            {
                                strTitle = line[(line.IndexOf("name:") + 6)..].Trim(trimChars);
Пример #30
0
        public void GetGames(List <ImportGameData> gameDataList, bool expensiveIcons = false)
        {
            List <string> dirs = new();

            // Get installed games
            if (OperatingSystem.IsWindows())
            {
                using RegistryKey key = Registry.LocalMachine.OpenSubKey(PARADOX_REG, RegistryKeyPermissionCheck.ReadSubTree); // HKLM32
                if (key == null)
                {
                    CLogger.LogInfo("{0} client not found in the registry.", _name.ToUpper());
                }
                else
                {
                    string path = GetRegStrVal(key, PARADOX_PATH);

                    try
                    {
                        if (!path.Equals(null) && Directory.Exists(path))
                        {
                            dirs.AddRange(Directory.GetDirectories(Path.Combine(Directory.GetParent(Directory.GetParent(path).ToString()).ToString(), "games"), "*.*", SearchOption.TopDirectoryOnly));
                            foreach (string dir in dirs)
                            {
                                CultureInfo ci = new("en-GB");
                                TextInfo    ti = ci.TextInfo;

                                string strID       = Path.GetFileName(dir);
                                string strTitle    = "";
                                string strLaunch   = "";
                                string strAlias    = "";
                                string strPlatform = GetPlatformString(ENUM);

                                strTitle = ti.ToTitleCase(strID.Replace('_', ' '));
                                CLogger.LogDebug($"- {strTitle}");
                                strLaunch = CGameFinder.FindGameBinaryFile(dir, strTitle);
                                strAlias  = GetAlias(Path.GetFileNameWithoutExtension(strLaunch));
                                if (strAlias.Length > strTitle.Length)
                                {
                                    strAlias = GetAlias(strTitle);
                                }
                                if (strAlias.Equals(strTitle, CDock.IGNORE_CASE))
                                {
                                    strAlias = "";
                                }
                                if (!(string.IsNullOrEmpty(strLaunch)))
                                {
                                    gameDataList.Add(
                                        new ImportGameData(strID, strTitle, strLaunch, strLaunch, "", strAlias, true, strPlatform));
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        CLogger.LogError(e);
                    }
                }
            }

            // Get not-installed games
            if (!(bool)CConfig.GetConfigBool(CConfig.CFG_INSTONLY))
            {
                string folder = Path.Combine(GetFolderPath(SpecialFolder.LocalApplicationData), PARADOX_JSON);
                if (!Directory.Exists(folder))
                {
                    CLogger.LogInfo("{0} games not found in Local AppData.", _name.ToUpper());
                }
                else
                {
                    CLogger.LogDebug("{0} not-installed games:", _name.ToUpper());

                    string[] files = Directory.GetFiles(folder, "*.json", SearchOption.TopDirectoryOnly);

                    foreach (string file in files)
                    {
                        if (file.EndsWith("_installableGames.json") && !(file.StartsWith("_noUser")))
                        {
                            string strDocumentData = File.ReadAllText(file);

                            if (string.IsNullOrEmpty(strDocumentData))
                            {
                                continue;
                            }

                            try
                            {
                                using JsonDocument document = JsonDocument.Parse(@strDocumentData, jsonTrailingCommas);
                                document.RootElement.TryGetProperty("content", out JsonElement content);
                                if (!content.Equals(null))
                                {
                                    foreach (JsonElement game in content.EnumerateArray())
                                    {
                                        game.TryGetProperty("_name", out JsonElement id);

                                        // Check if game is already installed
                                        bool found = false;
                                        foreach (string dir in dirs)
                                        {
                                            if (id.ToString().Equals(Path.GetFileName(dir)))
                                            {
                                                found = true;
                                            }
                                        }
                                        if (!found)
                                        {
                                            game.TryGetProperty("_displayName", out JsonElement title);
                                            game.TryGetProperty("_owned", out JsonElement owned);
                                            if (!id.Equals(null) && !title.Equals(null) && owned.ToString().ToLower().Equals("true"))
                                            {
                                                string strID    = id.ToString();
                                                string strTitle = title.ToString();
                                                CLogger.LogDebug($"- *{strTitle}");
                                                string strPlatform = GetPlatformString(ENUM);
                                                gameDataList.Add(new ImportGameData(strID, strTitle, "", "", "", "", false, strPlatform));
                                            }
                                        }
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                CLogger.LogError(e, string.Format("Malformed {0} file: {1}", _name.ToUpper(), file));
                            }
                        }
                    }
                }
            }
            CLogger.LogDebug("--------------------");
        }