Пример #1
0
        private void OnFileDownload(DownloadTask task)
        {
            if (task.status == DownloadStatus.Complete)
            {
                //_completeList.Add(task.storagePath);
                _currentTaskIndex++;
                if (_currentTaskIndex == _updateList.Count)
                {
                    OnAllDownloaded();
                }
            }
            else
            {
                string log = "GameUpdateMgr::OnFileDownload() - Failed:" + task.url + "#" + _currentTaskIndex + "," + task.errorCode.ToString();
                CLogger.LogWarn(log);
                _downloadMgr.StopService();
                //失败了也需要保存当前已更新的版本数据
                _downloadMgr.SaveTransferProgress("SaveOnError:" + task.file);
                //if (DownloadFileFailedHandler != null)
                //    DownloadFileFailedHandler(() => { DownloadMgr.Instance.StartService(); }, task.errorCode);

                EventCenter.Broadcast <DownloadTask, string, Action>((int)HotUpdateEventType.HotUpdateDownloadFail, task, log, delegate {
                    //_downloadMgr.Dispose();
                    //_downloadMgr = new DownloadMgr(FileUtils.LocalTempResRootPath, HotUpdateDefs.kBreakpointTransferInfoFile);
                    //DownloadUpdateList();

                    _downloadMgr.StartService();
                    _downloadMgr.AsyncDownloadList(_updateList, (!_isDownloadFromSourceResServer) ?
                                                   VersionMgr.Instance.projectManifestInfo.packageUrl : VersionMgr.Instance.projectManifestInfo.packageUrl_backup,
                                                   FileUtils.LocalTempResRootPath, OnFileDownload);

                    ;
                });
            }
        }
Пример #2
0
 /// <summary>
 /// 更新资源
 /// </summary>
 private void UpdateResource()
 {
     startUpdateTime = Utility.GetCurrentUTC() / 1000;
     _updateList     = _downloadMgr.StartContinueTransfer(new List <DownloadFileInfo>(VersionMgr.Instance.projectManifestInfo.assets));
     if (_updateList.Count > 0)
     {
         CLogger.Log("GameUpdateMgr::UpdateResource() - Start hot update resource.");
         _currentTaskIndex = 0;
         long leftDownloadBytes = _downloadMgr.TotalBytesToReceive - _downloadMgr.TotalReceivedBytes;
         if (leftDownloadBytes > 0 /* && StartDownloadNotifyHandler != null*/)
         {
             long diskLeftSpace = NativeManager.instance.GetFreeDiskSpace();//NativeMgr.Instance.CallStaticLongDefault("com.baitian.wrap.StorageWrap", "getAvailableInternalSize", "{}", -1);
             Debug.Log("###########diskLeftSpace=" + diskLeftSpace);
             if (diskLeftSpace != -1)
             {
                 if (diskLeftSpace < (_downloadMgr.TotalBytesToReceive /*VersionMgr.Instance.projectManifestInfo.uncompressedSize*/ - _downloadMgr.TotalReceivedBytes + 50 * 1024 * 1024L))
                 {
                     CLogger.LogWarn("GameUpdateMgr::UpdateResource() - 磁盘空间必须至少是补丁包解压后大小+50MB, diskLeftSpace:" + diskLeftSpace + ", 补丁包大小:" + leftDownloadBytes);
                     // 磁盘空间不足
                     EventCenter.Broadcast((int)HotUpdateEventType.DiskSpaceInsufficient);
                 }
                 else
                 {
                     EventCenter.Broadcast <long, long, Action>((int)HotUpdateEventType.StartHotUpdateNotify, _downloadMgr.TotalReceivedBytes,
                                                                _downloadMgr.TotalBytesToReceive, delegate { DownloadUpdateList(); });
                 }
             }
             else // 返回-1表示本地代码还未提供获取磁盘剩余空间的API实现
             {
                 //StartDownloadNotifyHandler(_downloadMgr.transferMgr.TotalReceivedBytes, _downloadMgr.transferMgr.TotalBytesToReceive, () =>
                 //    {
                 //        DownloadUpdateList();
                 //    });
                 EventCenter.Broadcast <long, long, Action>((int)HotUpdateEventType.StartHotUpdateNotify, _downloadMgr.TotalReceivedBytes,
                                                            _downloadMgr.TotalBytesToReceive, delegate { DownloadUpdateList(); });
             }
         }
         else
         {
             DownloadUpdateList();
         }
     }
     else
     {
         CLogger.Log("GameUpdateMgr::UpdateResource() - No need hot update.");
         OnUpdateComplete();
     }
 }
Пример #3
0
        /// <summary>
        /// Execure SQL query
        /// </summary>
        /// <param name="qry">The SQL query</param>
        /// <returns>SQL success/failure status code</returns>
        public SQLiteErrorCode Execute(string qry)
        {
            SQLiteCommand cmd;

            cmd             = m_sqlite_conn.CreateCommand();
            cmd.CommandText = qry;
            try
            {
                cmd.ExecuteNonQuery();
            }
            catch (SQLiteException e)
            {
                CLogger.LogWarn("Could not execute statement\n" + qry);
                CLogger.LogWarn(e.Message);
                return(e.ResultCode);
            }
            return(SQLiteErrorCode.Ok);
        }
Пример #4
0
 public static void Launch()
 {
     if (OperatingSystem.IsWindows())
     {
         using RegistryKey key = Registry.LocalMachine.OpenSubKey(BIGFISH_REG, RegistryKeyPermissionCheck.ReadSubTree); // HKLM32
         string launcherPath = Path.Combine(GetRegStrVal(key, "InstallationPath"), "bfgclient.exe");
         if (File.Exists(launcherPath))
         {
             Process.Start(launcherPath);
         }
         else
         {
             //SetFgColour(cols.errorCC, cols.errorLtCC);
             CLogger.LogWarn("Cannot start {0} launcher.", _name.ToUpper());
             Console.WriteLine("ERROR: Launcher couldn't start. Is it installed properly?");
             //Console.ResetColor();
         }
     }
 }
Пример #5
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());
        }
Пример #6
0
        /// <summary>
        /// Execure SQL select statement
        /// </summary>
        /// <param name="qry">The SQL query</param>
        /// <param name="dataReader">SQLiteDataReader which contains the SELECT result</param>
        /// <returns>SQL success/failure status code</returns>
        public SQLiteErrorCode ExecuteRead(string qry, out SQLiteDataReader dataReader)
        {
            SQLiteCommand cmd;

            cmd             = m_sqlite_conn.CreateCommand();
            cmd.CommandText = qry;
            try
            {
                dataReader = cmd.ExecuteReader();
            }
            catch (SQLiteException e)
            {
                CLogger.LogWarn("Could not execute statement\n" + qry);
                CLogger.LogWarn(e.Message);
                dataReader = null;
                return(e.ResultCode);
            }
            return(SQLiteErrorCode.Ok);
        }
Пример #7
0
 public static void Launch()
 {
     if (OperatingSystem.IsWindows())
     {
         using RegistryKey key = Registry.LocalMachine.OpenSubKey(IG_REG, RegistryKeyPermissionCheck.ReadSubTree); // HKLM64
         Process igcProcess   = new();
         string  launcherPath = Path.Combine(GetRegStrVal(key, GAME_INSTALL_LOCATION), "IGClient.exe");
         if (File.Exists(launcherPath))
         {
             CDock.StartAndRedirect(launcherPath);
         }
         else
         {
             //SetFgColour(cols.errorCC, cols.errorLtCC);
             CLogger.LogWarn("Cannot start {0} launcher.", _name.ToUpper());
             Console.WriteLine("ERROR: Launcher couldn't start. Is it installed properly?");
             //Console.ResetColor();
         }
     }
 }
Пример #8
0
        /// <summary>
        /// Open a separate data source and return the connection
        /// </summary>
        /// <param name="dataSource">Path to the data source</param>
        /// <returns><c>SQLiteConnection</c> object or <c>null</c> if not found</returns>
        public static SQLiteConnection OpenSeparateConnection(string dataSource)
        {
            if (!File.Exists(dataSource))
            {
                return(null);
            }
            SQLiteConnection connection = new SQLiteConnection("Data source=" + dataSource + ";Version=3;New=False;Compress=True;");

            try
            {
                CLogger.LogInfo("Connecting to Data Source " + dataSource);
                connection.Open();
            }
            catch (SQLiteException e)
            {
                CLogger.LogWarn("Database connection could not be established: " + e.ResultCode);
                return(null);
            }
            return(connection);
        }
Пример #9
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("--------------------");
        }
Пример #10
0
        public void GetGames(List <ImportGameData> gameDataList, bool expensiveIcons = false)
        {
            string strPlatform = GetPlatformString(ENUM);

            // Stop service (otherwise database is locked)
            ServiceController sc = new("OVRService");

            //bool restartSvc = false;
            try
            {
                if (sc.Status.Equals(ServiceControllerStatus.Running) || sc.Status.Equals(ServiceControllerStatus.StartPending))
                {
                    //restartSvc = true;
                    sc.Stop();
                    sc.WaitForStatus(ServiceControllerStatus.Stopped);
                }
            }
            catch (Exception e)
            {
                CLogger.LogError(e);
            }

            List <string> libPaths = new();
            Dictionary <ulong, string> exePaths = new();
            string db = Path.Combine(GetFolderPath(SpecialFolder.ApplicationData), OCULUS_DB);

            using (RegistryKey key = Registry.CurrentUser.OpenSubKey(OCULUS_LIBS, RegistryKeyPermissionCheck.ReadSubTree))
            {
                if (key != null)
                {
                    foreach (string lib in key.GetSubKeyNames())
                    {
                        using RegistryKey key2 = Registry.CurrentUser.OpenSubKey(Path.Combine(OCULUS_LIBS, lib), RegistryKeyPermissionCheck.ReadSubTree);
                        libPaths.Add(GetRegStrVal(key2, OCULUS_LIBPATH));
                    }
                }
            }

            foreach (string lib in libPaths)
            {
                List <string> libFiles = new();
                try
                {
                    string manifestPath = Path.Combine(lib, "Manifests");
                    libFiles = Directory.GetFiles(manifestPath, "*.json.mini", SearchOption.TopDirectoryOnly).ToList();
                    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
                    {
                        var options = new JsonDocumentOptions
                        {
                            AllowTrailingCommas = true
                        };

                        string strDocumentData = File.ReadAllText(file);

                        if (string.IsNullOrEmpty(strDocumentData))
                        {
                            CLogger.LogWarn(string.Format("Malformed {0} file: {1}", _name.ToUpper(), file));
                        }
                        else
                        {
                            using JsonDocument document = JsonDocument.Parse(@strDocumentData, options);
                            string name = GetStringProperty(document.RootElement, "canonicalName");
                            if (ulong.TryParse(GetStringProperty(document.RootElement, "appId"), out ulong id))
                            {
                                exePaths.Add(id, Path.Combine(lib, "Software", name, GetStringProperty(document.RootElement, "launchFile")));
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        CLogger.LogError(e, string.Format("Malformed {0} file: {1}", _name.ToUpper(), file));
                    }
                }
            }

            try
            {
                CultureInfo ci       = new("en-GB");
                TextInfo    ti       = ci.TextInfo;
                string      userName = CConfig.GetConfigString(CConfig.CFG_OCULUSID);
                //ulong userId = 0;

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

                // Get the user ID to check entitlements for expired trials

                /*
                 *              using (SQLiteCommand cmdU = new("SELECT hashkey, value FROM Objects WHERE typename = 'User'", con))
                 *              {
                 *                      using SQLiteDataReader rdrU = cmdU.ExecuteReader();
                 *                      while (rdrU.Read())
                 *                      {
                 *                              byte[] valU = new byte[rdrU.GetBytes(1, 0, null, 0, int.MaxValue) - 1];
                 *                              rdrU.GetBytes(1, 0, valU, 0, valU.Length);
                 *                              string strValU = System.Text.Encoding.Default.GetString(valU);
                 *
                 *                              string alias = ParseBlob(strValU, "alias", "app_entitlements");
                 *                              if (string.IsNullOrEmpty(userName))
                 *                              {
                 *                                      if (ulong.TryParse(rdrU.GetString(0), out userId))
                 *                                      {
                 *                                              userName = alias;
                 *                                              break;
                 *                                      }
                 *                              }
                 *                              else if (userName.Equals(alias, CDock.IGNORE_CASE))
                 *      {
                 *                                      ulong.TryParse(rdrU.GetString(0), out userId);
                 *                                      break;
                 *      }
                 *                      }
                 *              }
                 */

                using SQLiteCommand cmd    = new("SELECT hashkey, value FROM Objects WHERE typename = 'Application'", con);
                using SQLiteDataReader rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    string strID     = "";
                    string strTitle  = "";
                    string strLaunch = "";
                    string strAlias  = "";

                    string url = "";

                    /*
                     * string exePath = "", exePath2d = "", exeParams = "", exeParams2d = "";
                     * string state = "", time = "";
                     * bool isInstalled = false;
                     */
                    bool isInstalled = true;

                    if (ulong.TryParse(rdr.GetString(0), out ulong id))
                    {
                        strID = "oculus_" + id;
                    }
                    //else
                    //	strID = "oculus_" + name;

                    if (id == OCULUS_ENV_RIFT)
                    {
                        continue;
                    }

                    byte[] val = new byte[rdr.GetBytes(1, 0, null, 0, int.MaxValue) - 1];
                    rdr.GetBytes(1, 0, val, 0, val.Length);
                    string strVal = System.Text.Encoding.Default.GetString(val);

                    _ = ulong.TryParse(ParseBlob(strVal, "ApplicationAssetBundle", "can_access_feature_keys", -1, 0), out ulong assets);
                    //ulong.TryParse(ParseBlob(strVal, "PCBinary", "livestreaming_status", -1, 0), out ulong bin);
                    string name = ParseBlob(strVal, "canonical_name", "category");
                    strTitle = ParseBlob(strVal, "display_name", "display_short_description");
                    if (!string.IsNullOrEmpty(name) && string.IsNullOrEmpty(strTitle))
                    {
                        strTitle = ti.ToTitleCase(name.Replace('-', ' '));
                    }

                    using (SQLiteCommand cmd2 = new($"SELECT value FROM Objects WHERE hashkey = '{assets}'", con))
                    {
                        using SQLiteDataReader rdr2 = cmd2.ExecuteReader();
                        while (rdr2.Read())
                        {
                            byte[] val2 = new byte[rdr2.GetBytes(0, 0, null, 0, int.MaxValue) - 1];
                            rdr2.GetBytes(0, 0, val2, 0, val2.Length);
                            string strVal2 = System.Text.Encoding.Default.GetString(val2);
                            url = ParseBlob(strVal2, "uri", "version_code", strStart1: "size");
                        }
                    }

                    // The exe's can be gotten from the .json files, which we have to get anyway to figure out the install path

                    /*
                     * using (SQLiteCommand cmd3 = new($"SELECT value FROM Objects WHERE hashkey = '{bin}'", con))
                     * {
                     *  using SQLiteDataReader rdr3 = cmd3.ExecuteReader();
                     *  while (rdr3.Read())
                     *  {
                     *      byte[] val3 = new byte[rdr3.GetBytes(0, 0, null, 0, int.MaxValue) - 1];
                     *      rdr3.GetBytes(0, 0, val3, 0, val3.Length);
                     *      string strVal3 = System.Text.Encoding.Default.GetString(val3);
                     *      exePath = ParseBlob(strVal3, "launch_file", "launch_file_2d");
                     *      exePath2d = ParseBlob(strVal3, "launch_file_2d", "launch_parameters");
                     *      exeParams = ParseBlob(strVal3, "launch_parameters", "launch_parameters_2d");
                     *      exeParams2d = ParseBlob(strVal3, "launch_parameters_2d", "manifest_signature");
                     *  }
                     * }
                     *
                     * if (userId > 0)
                     * {
                     *  // TODO: If this is an expired trial, count it as not-installed
                     *  using SQLiteCommand cmd5 = new($"SELECT value FROM Objects WHERE hashkey = '{userId}:{id}'", con);
                     *  using SQLiteDataReader rdr5 = cmd5.ExecuteReader();
                     *  while (rdr5.Read())
                     *  {
                     *      byte[] val5 = new byte[rdr5.GetBytes(0, 0, null, 0, int.MaxValue) - 1];
                     *      rdr5.GetBytes(0, 0, val5, 0, val5.Length);
                     *      string strVal5 = System.Text.Encoding.Default.GetString(val5);
                     *      state = ParseBlob(strVal5, "active_state", "expiration_time");
                     *      if (state.Equals("PERMANENT"))
                     *          isInstalled = true;
                     *      else
                     *      {
                     *          time = ParseBlob(strVal5, "expiration_time", "grant_reason");
                     *          CLogger.LogDebug($"expiry: {state} {time}");
                     *          //if (!...expired)
                     *          isInstalled = true;
                     *      }
                     *  }
                     * }
                     * else
                     *  isInstalled = true;
                     */

                    if (exePaths.ContainsKey(id))
                    {
                        CLogger.LogDebug($"- {strTitle}");
                        strLaunch = exePaths[id];
                        strAlias  = GetAlias(Path.GetFileNameWithoutExtension(exePaths[id]));
                        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, isInstalled, strPlatform));
                    }
                    else
                    {
                        CLogger.LogDebug($"- *{strTitle}");
                        gameDataList.Add(new ImportGameData(strID, strTitle, "", "", "", "", false, strPlatform));

                        if (expensiveIcons && !string.IsNullOrEmpty(url))
                        {
                            // Download missing icons

                            string imgfile = Path.Combine(CDock.currentPath, CDock.IMAGE_FOLDER_NAME,
                                                          string.Concat(strTitle.Split(Path.GetInvalidFileNameChars())));
                            bool iconFound = false;
                            foreach (string ext in CDock.supportedImages)
                            {
                                if (File.Exists(imgfile + "." + ext))
                                {
                                    iconFound = true;
                                    break;
                                }
                            }
                            if (iconFound)
                            {
                                continue;
                            }

                            string zipfile = $"tmp_{_name}_{id}.zip";
                            try
                            {
#if DEBUG
                                // Don't re-download if file exists
                                if (!File.Exists(zipfile))
                                {
#endif
                                using WebClient client = new();
                                client.DownloadFile(url, zipfile);
#if DEBUG
                            }
#endif
                                using ZipArchive archive = ZipFile.OpenRead(zipfile);
                                foreach (ZipArchiveEntry entry in archive.Entries)
                                {
                                    foreach (string ext in CDock.supportedImages)
                                    {
                                        if (entry.Name.Equals("cover_square_image." + ext, CDock.IGNORE_CASE))
                                        {
                                            entry.ExtractToFile(imgfile + "." + ext);
                                            break;
                                        }
                                    }
                                }
//#if !DEBUG
                                File.Delete(zipfile);
//#endif
                            }
                            catch (Exception e)
                            {
                                CLogger.LogError(e, string.Format("Malformed {0} zip file!", _name.ToUpper()));
                            }
                        }
                    }
                }
                con.Close();
            }
            catch (Exception e)
            {
                CLogger.LogError(e, string.Format("Malformed {0} database output!", _name.ToUpper()));
            }
            //if (restartSvc)
            //    sc.Start();

            CLogger.LogDebug("--------------------");
        }
Пример #11
0
        public void GetGames(List <ImportGameData> gameDataList, bool expensiveIcons = false)
        {
            List <RegistryKey> keyList = new();

            // Get installed games
            using (RegistryKey key = Registry.CurrentUser.OpenSubKey(LEG_REG, RegistryKeyPermissionCheck.ReadSubTree)) // HKLM64
            {
                keyList = FindGameFolders(key, "");

                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 = GetRegStrVal(data, "InstallerUUID");
                        if (string.IsNullOrEmpty(strID))
                        {
                            strID = data.Name;
                        }
                        strTitle = GetRegStrVal(data, "ProductName");
                        if (string.IsNullOrEmpty(strTitle))
                        {
                            strTitle = data.Name;
                        }
                        CLogger.LogDebug($"- {strTitle}");
                        string exeFile = GetRegStrVal(data, "GameExe");
                        strLaunch = Path.Combine(GetRegStrVal(data, "InstDir").Trim(new char[] { ' ', '"' }), exeFile);
                        if (expensiveIcons)
                        {
                            using RegistryKey key2 = Registry.LocalMachine.OpenSubKey(NODE32_REG, RegistryKeyPermissionCheck.ReadSubTree), // HKLM32
                                  key3             = Registry.LocalMachine.OpenSubKey(NODE64_REG, RegistryKeyPermissionCheck.ReadSubTree); // HKLM64
                            List <RegistryKey> unList = FindGameKeys(key2, GAME_DISPLAY_NAME, strTitle, new string[] { "Legacy Games Launcher" });
                            if (unList.Count <= 0)
                            {
                                unList = FindGameKeys(key3, GAME_DISPLAY_NAME, strTitle, new string[] { "Legacy Games Launcher" });
                            }
                            foreach (RegistryKey unKey in unList)
                            {
                                strUninstall = GetRegStrVal(unKey, GAME_UNINSTALL_STRING); //.Trim(new char[] { ' ', '"' });
                                strIconPath  = GetRegStrVal(unKey, GAME_DISPLAY_ICON);     //.Trim(new char[] { ' ', '"' });
                                break;
                            }
                        }
                        if (string.IsNullOrEmpty(strIconPath))
                        {
                            strIconPath = strLaunch;
                        }
                        strAlias = GetAlias(Path.GetFileNameWithoutExtension(exeFile));
                        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));
                    }
                }
            }

            if (expensiveIcons && keyList.Count <= 0)
            {
                // if no games found in registry, check manually

                List <string> libPaths = new();

                string file = Path.Combine(GetFolderPath(SpecialFolder.ApplicationData), LEG_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())
                            {
                                element.TryGetProperty("settings", out JsonElement settings);
                                if (!settings.Equals(null))
                                {
                                    settings.TryGetProperty("gameLibraryPath", out JsonElement paths);
                                    if (!paths.Equals(null))
                                    {
                                        foreach (JsonElement path in paths.EnumerateArray())
                                        {
                                            if (!path.Equals(null))
                                            {
                                                libPaths.Add(path.ToString());
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            CLogger.LogError(e, string.Format("Malformed {0} file: {1}", _name.ToUpper(), file));
                        }
                    }
                }

                foreach (string path in libPaths)
                {
                    List <string> dirs = new();

                    try
                    {
                        if (!path.Equals(null) && Directory.Exists(path))
                        {
                            dirs.AddRange(Directory.GetDirectories(path, "*.*", SearchOption.TopDirectoryOnly));
                            foreach (string dir in dirs)
                            {
                                string strID       = Path.GetFileName(dir);
                                string strLaunch   = "";
                                string strAlias    = "";
                                string strPlatform = GetPlatformString(ENUM);

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