Exemple #1
0
        //public string EndorsementStatus { get; set; } = "Endorse mod";

        public async Task <bool?> GetEndorsementStatus(int currentuserid)
        {
            if (!NexusModsUtilities.HasAPIKey)
            {
                return(false);
            }
            if (checkedEndorsementStatus)
            {
                return(IsEndorsed);
            }
            try
            {
                var    client   = NexusModsUtilities.GetClient();
                string gamename = @"masseffect";
                if (Game == MEGame.ME2)
                {
                    gamename += @"2";
                }
                if (Game == MEGame.ME3)
                {
                    gamename += @"3";
                }
                var modinfo = await client.Mods.GetMod(gamename, NexusModID);

                if (modinfo.User.MemberID == currentuserid)
                {
                    IsEndorsed = false;
                    CanEndorse = false;
                    IsOwnMod   = true;
                    checkedEndorsementStatus = true;
                    return(null); //cannot endorse your own mods
                }
                var endorsementstatus = modinfo.Endorsement;
                if (endorsementstatus != null)
                {
                    if (endorsementstatus.EndorseStatus == Pathoschild.FluentNexus.Models.EndorsementStatus.Undecided || endorsementstatus.EndorseStatus == Pathoschild.FluentNexus.Models.EndorsementStatus.Abstained)
                    {
                        IsEndorsed = false;
                    }
                    else if (endorsementstatus.EndorseStatus == Pathoschild.FluentNexus.Models.EndorsementStatus.Endorsed)
                    {
                        IsEndorsed = true;
                    }

                    CanEndorse = true;
                }
                else
                {
                    IsEndorsed = false;
                    CanEndorse = false;
                }
                checkedEndorsementStatus = true;
                return(IsEndorsed);
            }
            catch (Exception e)
            {
                Log.Error(@"Error getting endorsement status: " + e.Message);
                return(false); //null would mean own mod. so just say its not endorsed atm.
            }
        }
 private void UnlinkFromNexus()
 {
     APIKeyText = "";
     NexusModsUtilities.WipeKeys();
     SetAuthorized(false);
     mainwindow.RefreshNexusStatus();
 }
 private void SetupDLM()
 {
     SettingUpNXM = true;
     Task.Run(() =>
     {
         NexusModsUtilities.SetupNXMHandling(nxmProgressDelegate, nxmFinishedDelegate);
     });
 }
Exemple #4
0
        /// <summary>
        /// Attempts to endorse/unendorse this mod on NexusMods.
        /// </summary>
        /// <param name="newEndorsementStatus"></param>
        /// <param name="endorse"></param>
        /// <param name="currentuserid"></param>
        public void EndorseMod(Action <Mod, bool> newEndorsementStatus, bool endorse, int currentuserid)
        {
            if (!NexusModsUtilities.HasAPIKey || !CanEndorse)
            {
                return;
            }
            NamedBackgroundWorker nbw = new NamedBackgroundWorker(@"ModSpecificEndorsement");

            nbw.DoWork += (a, b) =>
            {
                var    client   = NexusModsUtilities.GetClient();
                string gamename = @"masseffect";
                if (Game == MEGame.ME2)
                {
                    gamename += @"2";
                }
                if (Game == MEGame.ME3)
                {
                    gamename += @"3";
                }
                string telemetryOverride = null;
                try
                {
                    if (endorse)
                    {
                        client.Mods.Endorse(gamename, NexusModID, @"1.0").Wait();
                    }
                    else
                    {
                        client.Mods.Unendorse(gamename, NexusModID, @"1.0").Wait();
                    }
                }
                catch (Exception e)
                {
                    Log.Error(@"Error endorsing/unendorsing: " + e.ToString());
                    telemetryOverride = e.ToString();
                }

                checkedEndorsementStatus = false;
                IsEndorsed = GetEndorsementStatus(currentuserid).Result ?? false;
                Analytics.TrackEvent(@"Set endorsement for mod", new Dictionary <string, string>
                {
                    { @"Endorsed", endorse.ToString() },
                    { @"Succeeded", telemetryOverride ?? (endorse == IsEndorsed).ToString() }
                });
            };
            nbw.RunWorkerCompleted += (a, b) => {
                if (b.Error != null)
                {
                    Log.Error($@"Exception occured in {nbw.Name} thread: {b.Error.Message}");
                }
                newEndorsementStatus.Invoke(this, IsEndorsed);
            };
            nbw.RunWorkerAsync();
        }
        private void SaveSettings()
        {
            //Check Auth
            OperationInProgress = true;
            SettingsSubtext     = M3L.GetString(M3L.string_validatingSettings);
            Analytics.TrackEvent(@"Saving/authenticating to updater service", new Dictionary <string, string>()
            {
                { @"Username", Username },
                { @"LZMAPath", LZMAStoragePath },
                { @"ManifestPath", ManifestStoragePath }
            });
            CheckAuth(authCompletedCallback: (result) =>
            {
                if (result is bool?)
                {
                    bool?authenticated = (bool?)result;  //can't cast with is for some reason
                    if (authenticated.HasValue && authenticated.Value)
                    {
                        Settings.UpdaterServiceUsername            = Username;
                        Settings.UpdaterServiceLZMAStoragePath     = LZMAStoragePath;
                        Settings.UpdaterServiceManifestStoragePath = ManifestStoragePath;
                        Settings.Save();

                        MemoryStream encryptedStream = new MemoryStream();
                        var entropy = NexusModsUtilities.EncryptStringToStream(Password_TextBox.Password, encryptedStream);
                        Settings.SaveUpdaterServiceEncryptedValues(Convert.ToBase64String(entropy), Convert.ToBase64String(encryptedStream.ToArray()));
                        SettingsExpanded = false;
                        SettingsSubtext  = null;
                        if (mod != null)
                        {
                            StartPreparingModWrapper();
                        }
                        else
                        {
                            CurrentActionText = M3L.GetString(M3L.string_settingsSaved);
                        }
                    }
                }
                else if (result is string errorMessage)
                {
                    SettingsSubtext = errorMessage;
                }
                else
                {
                    SettingsSubtext = M3L.GetString(M3L.string_errorValidatingSettings);
                }
                OperationInProgress = false;
            });
        }
 public override void OnPanelVisible()
 {
     try
     {
         string currentKey = NexusModsUtilities.DecryptNexusmodsAPIKeyFromDisk();
         if (currentKey != null)
         {
             APIKeyText = currentKey;
             SetAuthorized(true);
         }
         else
         {
             SetAuthorized(false);
         }
     }
     catch (Exception e)
     {
         Log.Error(@"Error getting current API Key: " + e.Message);
         SetAuthorized(false);
     }
 }
Exemple #7
0
        //this is copied from NexusModsLogin.xaml.cs cause I'm too lazy to make it shared code for what will likely never change
        private void AuthorizeWithNexus()
        {
            NamedBackgroundWorker nbw = new NamedBackgroundWorker(@"NexusAPICredentialsCheck");

            nbw.DoWork += async(a, b) =>
            {
                IsAuthorizing = true;
                VisibleIcon   = true;
                SpinIcon      = true;
                ActiveIcon    = FontAwesomeIcon.Spinner;
                AuthorizeCommand.RaiseCanExecuteChanged();
                CloseCommand.RaiseCanExecuteChanged();
                AuthorizeToNexusText = M3L.GetString(M3L.string_pleaseWait);

                var apiKeyReceived = await NexusModsUtilities.SetupNexusLogin(x => Debug.WriteLine(x));

                Application.Current.Dispatcher.Invoke(delegate { mainwindow.Activate(); });
                if (!string.IsNullOrWhiteSpace(apiKeyReceived))
                {
                    //Check api key
                    AuthorizeToNexusText = M3L.GetString(M3L.string_checkingKey);
                    try
                    {
                        var authInfo = NexusModsUtilities.AuthToNexusMods(apiKeyReceived).Result;
                        if (authInfo != null)
                        {
                            using FileStream fs = new FileStream(System.IO.Path.Combine(Utilities.GetNexusModsCache(), @"nexusmodsapikey"), FileMode.Create);
                            File.WriteAllBytes(System.IO.Path.Combine(Utilities.GetNexusModsCache(), @"entropy"), NexusModsUtilities.EncryptStringToStream(apiKeyReceived, fs));
                            fs.Close();
                            mainwindow.NexusUsername = authInfo.Name;
                            mainwindow.NexusUserID   = authInfo.UserID;
                            SetAuthorized(true);
                            mainwindow.RefreshNexusStatus();
                            AuthorizedToNexusUsername = authInfo.Name;
                            Analytics.TrackEvent(@"Authenticated to NexusMods");
                        }
                        else
                        {
                            Log.Error(@"Error authenticating to nexusmods, no userinfo was returned, possible network issue");
                            mainwindow.NexusUsername = null;
                            mainwindow.NexusUserID   = 0;
                            SetAuthorized(false);
                            mainwindow.RefreshNexusStatus();
                        }
                    }
                    catch (ApiException apiException)
                    {
                        Log.Error(@"Error authenticating to NexusMods: " + apiException.ToString());
                        Application.Current.Dispatcher.Invoke(delegate { M3L.ShowDialog(window, M3L.GetString(M3L.string_interp_nexusModsReturnedAnErrorX, apiException.ToString()), M3L.GetString(M3L.string_errorAuthenticatingToNexusMods), MessageBoxButton.OK, MessageBoxImage.Error); });
                    }
                    catch (Exception e)
                    {
                        Log.Error(@"Other error authenticating to NexusMods: " + e.Message);
                    }
                }
                else
                {
                    Log.Error(@"No API key - setting authorized to false for NM");
                    SetAuthorized(false);
                }

                IsAuthorizing = false;
            };
            nbw.RunWorkerCompleted += (a, b) =>
            {
                if (b.Error != null)
                {
                    Log.Error($@"Exception occurred in {nbw.Name} thread: {b.Error.Message}");
                }
                VisibleIcon = IsAuthorized;
                if (IsAuthorized)
                {
                    ActiveIcon = FontAwesomeIcon.CheckCircle;
                }
                SpinIcon = false;
                AuthorizeCommand.RaiseCanExecuteChanged();
                CloseCommand.RaiseCanExecuteChanged();
            };
            nbw.RunWorkerAsync();
        }
Exemple #8
0
        /// <summary>
        /// Attempts to endorse/unendorse this mod on NexusMods.
        /// </summary>
        /// <param name="newEndorsementStatus"></param>
        /// <param name="endorse"></param>
        /// <param name="currentuserid"></param>
        public void EndorseMod(Action <Mod, bool, string> endorsementResultCallback, bool endorse)
        {
            if (NexusModsUtilities.UserInfo == null || !CanEndorse)
            {
                return;
            }
            NamedBackgroundWorker nbw = new NamedBackgroundWorker(@"ModSpecificEndorsement");

            nbw.DoWork += (a, b) =>
            {
                var    client   = NexusModsUtilities.GetClient();
                string gamename = @"masseffect";
                if (Game == MEGame.ME2)
                {
                    gamename += @"2";
                }
                if (Game == MEGame.ME3)
                {
                    gamename += @"3";
                }
                if (Game.IsLEGame() || Game == MEGame.LELauncher)
                {
                    gamename += @"legendaryedition";
                }
                string telemetryOverride       = null;
                string endorsementFailedReason = null;
                try
                {
                    if (endorse)
                    {
                        client.Mods.Endorse(gamename, NexusModID, @"1.0").Wait();
                    }
                    else
                    {
                        client.Mods.Unendorse(gamename, NexusModID, @"1.0").Wait();
                    }
                }
                catch (Exception e)
                {
                    if (e.InnerException != null)
                    {
                        if (e.InnerException.Message == @"NOT_DOWNLOADED_MOD")
                        {
                            // User did not download this mod from NexusMods
                            endorsementFailedReason = M3L.GetString(M3L.string_dialog_cannotEndorseNonDownloadedMod);
                        }
                        else if (e.InnerException.Message == @"TOO_SOON_AFTER_DOWNLOAD")
                        {
                            endorsementFailedReason = M3L.GetString(M3L.string_dialog_cannotEndorseUntil15min);
                        }
                    }
                    else
                    {
                        telemetryOverride = e.ToString();
                    }
                    Log.Error(@"Error endorsing/unendorsing: " + e.ToString());
                }

                checkedEndorsementStatus = false;
                IsEndorsed = GetEndorsementStatus().Result ?? false;
                Analytics.TrackEvent(@"Set endorsement for mod", new Dictionary <string, string>
                {
                    { @"Endorsed", endorse.ToString() },
                    { @"Succeeded", telemetryOverride ?? (endorse == IsEndorsed).ToString() }
                });
                b.Result = endorsementFailedReason;
            };
            nbw.RunWorkerCompleted += (a, b) =>
            {
                if (b.Error != null)
                {
                    Log.Error($@"Exception occurred in {nbw.Name} thread: {b.Error.Message}");
                }
                else if (b.Result is string endorsementFailedReason)
                {
                    endorsementResultCallback.Invoke(this, IsEndorsed, endorsementFailedReason);
                }
                else
                {
                    endorsementResultCallback.Invoke(this, IsEndorsed, null);
                }
            };
            nbw.RunWorkerAsync();
        }
Exemple #9
0
        /// <summary>
        /// Loads the information about this nxmlink into this object. Subscribe to OnInitialized() to know when it has initialized and is ready for download to begin.
        /// THIS IS A BLOCKING CALL DO NOT RUN ON THE UI
        /// </summary>
        public void Initialize()
        {
            Log.Information($@"Initializing {NXMLink}");
            Task.Run(() =>
            {
                try
                {
                    DownloadLinks.Clear();

                    var nxmlink  = NXMLink.Substring(6);
                    var queryPos = nxmlink.IndexOf('?');

                    var info   = queryPos > 0 ? nxmlink.Substring(0, queryPos) : nxmlink;
                    var infos  = info.Split('/');
                    domain     = infos[0];
                    var modid  = int.Parse(infos[2]);
                    var fileid = int.Parse(infos[4]);

                    if (!NexusModsUtilities.AllSupportedNexusDomains.Contains(domain))
                    {
                        Log.Error($@"Cannot download file from unsupported domain: {domain}. Open your preferred mod manager from that game first");
                        Initialized           = true;
                        ProgressIndeterminate = false;
                        OnModDownloadError?.Invoke(this,
                                                   M3L.GetString(M3L.string_interp_dialog_modNotForThisModManager, domain));
                        return;
                    }

                    ModFile = NexusModsUtilities.GetClient().ModFiles.GetModFile(domain, modid, fileid).Result;
                    if (ModFile != null)
                    {
                        if (ModFile.Category != FileCategory.Deleted)
                        {
                            if (queryPos > 0)
                            {
                                // download with manager
                                string querystring = nxmlink.Substring(queryPos);
                                var parameters     = HttpUtility.ParseQueryString(querystring);

                                // Check if parameters are correct!
                                DownloadLinks.AddRange(NexusModsUtilities.GetDownloadLinkForFile(domain, modid, fileid,
                                                                                                 parameters[@"key"], int.Parse(parameters[@"expires"])).Result);
                            }
                            else
                            {
                                // premium?
                                if (!NexusModsUtilities.UserInfo.IsPremium)
                                {
                                    Log.Error(
                                        $@"Cannot download {ModFile.FileName}: User is not premium, but this link is not generated from NexusMods");
                                    Initialized           = true;
                                    ProgressIndeterminate = false;
                                    OnModDownloadError?.Invoke(this,
                                                               M3L.GetString(M3L.string_dialog_mustBePremiumUserToDownload));
                                    return;
                                }

                                DownloadLinks.AddRange(NexusModsUtilities.GetDownloadLinkForFile(domain, modid, fileid)
                                                       ?.Result);
                            }

                            ProgressMaximum = ModFile.Size * 1024; // Bytes
                            Initialized     = true;
                            Log.Error($@"ModDownload has initialized: {ModFile.FileName}");
                            OnInitialized?.Invoke(this, null);
                        }
                        else
                        {
                            Log.Error($@"Cannot download {ModFile.FileName}: File deleted from NexusMods");
                            Initialized           = true;
                            ProgressIndeterminate = false;
                            OnModDownloadError?.Invoke(this,
                                                       M3L.GetString(M3L.string_dialog_cannotDownloadDeletedFile));
                        }
                    }
                }
                catch (Exception e)
                {
                    Log.Error($@"Error downloading {ModFile?.FileName}: {e.Message}");
                    Initialized           = true;
                    ProgressIndeterminate = false;
                    OnModDownloadError?.Invoke(this, M3L.GetString(M3L.string_interp_errorDownloadingModX, e.Message));
                }
            });
        }
Exemple #10
0
 private void RegisterM3()
 {
     NexusModsUtilities.SetupNXMHandling();
 }
        /// <summary>
        /// Loads the information about this nxmlink into this object. Subscribe to OnInitialized() to know when it has initialized and is ready for download to begin.
        /// THIS IS A BLOCKING CALL DO NOT RUN ON THE UI
        /// </summary>
        public void Initialize()
        {
            Log.Information($@"Initializing {NXMLink}");
            Task.Run(() =>
            {
                try
                {
                    DownloadLinks.Clear();

                    ProtocolLink = NexusProtocolLink.Parse(NXMLink);
                    if (ProtocolLink == null)
                    {
                        return;                       // Parse failed.
                    }
                    if (!NexusModsUtilities.AllSupportedNexusDomains.Contains(ProtocolLink?.Domain))
                    {
                        Log.Error($@"Cannot download file from unsupported domain: {ProtocolLink?.Domain}. Open your preferred mod manager from that game first");
                        Initialized           = true;
                        ProgressIndeterminate = false;
                        OnModDownloadError?.Invoke(this,
                                                   M3L.GetString(M3L.string_interp_dialog_modNotForThisModManager, ProtocolLink.Domain));
                        return;
                    }

                    ModFile = NexusModsUtilities.GetClient().ModFiles.GetModFile(ProtocolLink.Domain, ProtocolLink.ModId, ProtocolLink.FileId).Result;
                    if (ModFile != null)
                    {
                        if (ModFile.Category != FileCategory.Deleted)
                        {
                            if (ProtocolLink.Key != null)
                            {
                                // Website click
                                if (ProtocolLink.Domain is @"masseffect" or @"masseffect2" && !IsDownloadWhitelisted(ProtocolLink.Domain, ModFile))
                                {
                                    // Check to see file has moddesc.ini the listing
                                    var fileListing = NexusModsUtilities.GetFileListing(ModFile);
                                    if (fileListing == null || !HasModdescIni(fileListing))
                                    {
                                        Log.Error($@"This file is not whitelisted for download and does not contain a moddesc.ini file, this is not a mod manager mod: {ModFile.FileName}");
                                        Initialized           = true;
                                        ProgressIndeterminate = false;
                                        OnModDownloadError?.Invoke(this, M3L.GetString(M3L.string_interp_nexusModNotCompatible, ModFile.Name));
                                        return;
                                    }
                                }


                                // download with manager was clicked.

                                // Check if parameters are correct!
                                DownloadLinks.AddRange(NexusModsUtilities.GetDownloadLinkForFile(ProtocolLink).Result);
                            }
                            else
                            {
                                // premium?
                                if (!NexusModsUtilities.UserInfo.IsPremium)
                                {
                                    Log.Error(
                                        $@"Cannot download {ModFile.FileName}: User is not premium, but this link is not generated from NexusMods");
                                    Initialized           = true;
                                    ProgressIndeterminate = false;
                                    OnModDownloadError?.Invoke(this,
                                                               M3L.GetString(M3L.string_dialog_mustBePremiumUserToDownload));
                                    return;
                                }

                                DownloadLinks.AddRange(NexusModsUtilities.GetDownloadLinkForFile(ProtocolLink)
                                                       ?.Result);
                            }

                            ProgressMaximum = ModFile.SizeInBytes ?? ModFile.SizeInKilobytes * 1024L; // SizeKb is the original version. They added SizeInBytes at my request
                            Initialized     = true;
                            Log.Information($@"ModDownload has initialized: {ModFile.FileName}");
                            OnInitialized?.Invoke(this, null);
                        }
                        else
                        {
                            Log.Error($@"Cannot download {ModFile.FileName}: File deleted from NexusMods");
                            Initialized           = true;
                            ProgressIndeterminate = false;
                            OnModDownloadError?.Invoke(this,
                                                       M3L.GetString(M3L.string_dialog_cannotDownloadDeletedFile));
                        }
                    }
                }
                catch (Exception e)
                {
                    Log.Error($@"Error downloading {ModFile?.FileName}: {e.Message}");
                    Initialized           = true;
                    ProgressIndeterminate = false;
                    OnModDownloadError?.Invoke(this, M3L.GetString(M3L.string_interp_errorDownloadingModX, e.Message));
                }
            });
        }