Example #1
0
 public CharacterExtended(Character character, string fileElement = null, SINner mySINnerLoading = null) : this(character, fileElement)
 {
     if (mySINnerLoading != null)
     {
         this._MySINnerFile = mySINnerLoading;
     }
 }
        private async void MyOnSaveUpload(object sender, Character input)
        {
            try
            {
                input.OnSaveCompleted -= MyOnSaveUpload;
                CharacterExtended ce = new CharacterExtended(input, null);
                var found            = await StaticUtils.Client.GetByIdWithHttpMessagesAsync(ce.MySINnerFile.Id.Value);

                if (found.Response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var sinjson = await found.Response.Content.ReadAsStringAsync();

                    var    foundobj = Newtonsoft.Json.JsonConvert.DeserializeObject <SINner>(sinjson);
                    SINner foundsin = foundobj as SINner;
                    if (foundsin.LastChange >= ce.MyCharacter.FileLastWriteTime)
                    {
                        //is already up to date!
                        return;
                    }
                }
                ce.MySINnerFile.SiNnerMetaData.Tags = ce.PopulateTags();
                ce.PrepareModel();
                await ChummerHub.Client.Backend.Utils.PostSINnerAsync(ce);

                await ChummerHub.Client.Backend.Utils.UploadChummerFileAsync(ce);
            }
            catch (Exception e)
            {
                System.Diagnostics.Trace.TraceError(e.ToString());
            }
            finally
            {
                IsSaving = false;
            }
        }
Example #3
0
        private void bRestore_Click(object sender, EventArgs e)
        {
            var folderBrowserDialog1 = new FolderBrowserDialog();

            // Show the FolderBrowserDialog.
            DialogResult result = folderBrowserDialog1.ShowDialog();

            if (result == DialogResult.OK)
            {
                string folderName = folderBrowserDialog1.SelectedPath;
                try
                {
                    DirectoryInfo d     = new DirectoryInfo(folderName); //Assuming Test is your Folder
                    FileInfo[]    Files = d.GetFiles("*.chum5json");     //Getting Text files
                    foreach (FileInfo file in Files)
                    {
                        try
                        {
                            string           sinjson          = File.ReadAllText(file.FullName);
                            SINner           sin              = Newtonsoft.Json.JsonConvert.DeserializeObject <SINner>(sinjson);
                            UploadInfoObject uploadInfoObject = new UploadInfoObject();
                            uploadInfoObject.Client         = PluginHandler.MyUploadClient;
                            uploadInfoObject.UploadDateTime = DateTime.Now;
                            uploadInfoObject.SiNners        = new List <SINner>
                            {
                                sin
                            };
                            var t = StaticUtils.Client.PostWithHttpMessagesAsync(uploadInfoObject);
                            t.ContinueWith((posttask) =>
                            {
                                if (posttask.Result.Response.IsSuccessStatusCode)
                                {
                                    System.Diagnostics.Trace.TraceInformation("SINner " + sin.Id + " posted!");
                                }
                                else
                                {
                                    string msg  = posttask.Result.Response.ReasonPhrase + ": " + Environment.NewLine;
                                    var content = posttask.Result.Response.Content.ReadAsStringAsync().Result;
                                    msg        += content;
                                    System.Diagnostics.Trace.TraceWarning("SINner " + sin.Id + " not posted: " + msg);
                                }
                            });
                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Trace.TraceError("Could not read file " + file.FullName + ": " + ex.ToString());
                            continue;
                        }
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Trace.TraceError(ex.ToString());
                    Invoke(new Action(() => MessageBox.Show(ex.Message)));
                }
            }
        }
Example #4
0
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'SINnerExample.GetSINnerExample()'
        public SINner GetSINnerExample()
#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'SINnerExample.GetSINnerExample()'
        {
            Guid parentTagGuid = Guid.NewGuid();
            Guid childTagGuid  = Guid.NewGuid();
            var  sin           = new SINner
            {
                Id             = Guid.NewGuid(),
                UploadClientId = Guid.NewGuid()
            };

            sin.SINnerMetaData = new SINnerMetaData()
            {
                Id         = Guid.NewGuid(),
                Tags       = new List <Tag>(),
                Visibility = new SINnerVisibility()
                {
                    IsGroupVisible = true,
                    UserRights     = new List <SINnerUserRight>()
                    {
                        new SINnerUserRight(sin.Id.Value)
                        {
                            EMail   = "*****@*****.**",
                            CanEdit = true
                        }
                    }
                }
            };
            var parenttag = new Tag(sin, null)
            {
                Id              = parentTagGuid,
                TagName         = "TestTag",
                TagValue        = "TestTagValue",
                TagType         = Tag.TagValueEnum.@string,
                ParentTagId     = Guid.Empty,
                IsUserGenerated = true
            };

            parenttag.Tags = new List <Tag>()
            {
                new Tag(sin, parenttag)
                {
                    Id              = childTagGuid,
                    TagName         = "TestChildTag",
                    TagValue        = "TestChildTagValue",
                    TagType         = Tag.TagValueEnum.@string,
                    ParentTagId     = parentTagGuid,
                    IsUserGenerated = false
                }
            };
            sin.SINnerMetaData.Tags.Add(parenttag);
            //sin.MyExtendedAttributes.JsonSummary = "{}";
            sin.LastChange = DateTime.Now;
            return(sin);
        }
Example #5
0
        private async Task RestoreTask(FolderBrowserDialog folderBrowserDialog1)
        {
            string folderName = folderBrowserDialog1.SelectedPath;

            try
            {
                DirectoryInfo d     = new DirectoryInfo(folderName); //Assuming Test is your Folder
                FileInfo[]    Files = d.GetFiles("*.chum5json");     //Getting Text files
                foreach (FileInfo file in Files)
                {
                    try
                    {
                        using (new CursorWait(true, this))
                        {
                            string           sinjson          = File.ReadAllText(file.FullName);
                            SINner           sin              = Newtonsoft.Json.JsonConvert.DeserializeObject <SINner>(sinjson);
                            UploadInfoObject uploadInfoObject = new UploadInfoObject();
                            uploadInfoObject.Client         = PluginHandler.MyUploadClient;
                            uploadInfoObject.UploadDateTime = DateTime.Now;
                            uploadInfoObject.SiNners        = new List <SINner>
                            {
                                sin
                            };
                            var   client   = StaticUtils.GetClient();
                            var   posttask = client.PostSINWithHttpMessagesAsync(uploadInfoObject);
                            await posttask;

                            if (posttask.Result.Response.IsSuccessStatusCode)
                            {
                                Log.Info("SINner " + sin.Id + " posted!");
                            }
                            else
                            {
                                string msg     = posttask.Result.Response.ReasonPhrase + ": " + Environment.NewLine;
                                var    content = posttask.Result.Response.Content.ReadAsStringAsync().Result;
                                msg += content;
                                Log.Warn("SINner " + sin.Id + " not posted: " + msg);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex, "Could not read file " + file.FullName + ": ");
                        continue;
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                Invoke(new Action(() => Program.MainForm.ShowMessageBox(ex.Message)));
            }
        }
Example #6
0
        private async static void OnMyAfterSelect(SINner sinner, CharacterCache objCache, TreeViewEventArgs treeViewEventArgs)
        {
            string loadFilePath = null;

            using (new CursorWait(true, PluginHandler.MainForm))
            {
                string zipPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "SINner", sinner.Id.Value.ToString());
                if (Directory.Exists(zipPath))
                {
                    var files = Directory.EnumerateFiles(zipPath, "*.chum5", SearchOption.TopDirectoryOnly);
                    foreach (var file in files)
                    {
                        DateTime lastwrite = File.GetLastWriteTime(file);
                        if ((lastwrite >= sinner.LastChange) ||
                            sinner.LastChange == null)
                        {
                            loadFilePath      = file;
                            objCache.FilePath = loadFilePath;
                            break;
                        }
                        File.Delete(file);
                    }
                }
                if (String.IsNullOrEmpty(objCache.FilePath))
                {
                    objCache.FilePath = await DownloadFileTask(sinner, objCache);
                }

                if (!String.IsNullOrEmpty(objCache.FilePath))
                {
                    //I copy the values, because I dont know what callbacks are registered...
                    var tempCache = new CharacterCache(objCache.FilePath);
                    objCache.Background     = tempCache.Background;
                    objCache.MugshotBase64  = tempCache.MugshotBase64;
                    objCache.BuildMethod    = tempCache.BuildMethod;
                    objCache.CharacterAlias = tempCache.CharacterAlias;
                    objCache.CharacterName  = tempCache.CharacterName;
                    objCache.CharacterNotes = tempCache.CharacterNotes;
                    objCache.Concept        = tempCache.Concept;
                    objCache.Created        = tempCache.Created;
                    objCache.Description    = tempCache.Description;
                    objCache.Essence        = tempCache.Essence;
                    objCache.GameNotes      = tempCache.GameNotes;
                    objCache.Karma          = tempCache.Karma;
                    objCache.FileName       = tempCache.FileName;
                    objCache.Metatype       = tempCache.Metatype;
                    objCache.Metavariant    = tempCache.Metavariant;
                    objCache.PlayerName     = tempCache.PlayerName;
                    objCache.SettingsFile   = tempCache.SettingsFile;
                }
                treeViewEventArgs.Node.Text = objCache.CalculatedName();
            }
        }
        private async Task LeaveGroupTask(SINner mySINnerFile, SINnerGroup myGroup, bool noupdate = false)
        {
            try
            {
                var client   = StaticUtils.GetClient();
                var response = await client.DeleteLeaveGroupWithHttpMessagesAsync(myGroup.Id, mySINnerFile.Id);

                if ((response.Response.StatusCode == HttpStatusCode.OK))
                {
                    try
                    {
                        MyCE = MyCE;
                        if (!noupdate)
                        {
                            TlpGroupSearch_VisibleChanged(null, new EventArgs());
                        }
                    }
                    catch (Exception e)
                    {
                        Log.Warn("Group disbanded: " + e.Message);
                        Program.MainForm.ShowMessageBox("Group " + myGroup.Groupname + " disbanded because of no members left.");
                    }
                    finally
                    {
                        if ((!noupdate) && (MyParentForm?.MyParentForm != null))
#pragma warning disable 4014
                        {
                            MyParentForm?.MyParentForm?.CheckSINnerStatus();
                        }
#pragma warning restore 4014
                    }
                }
                else
                {
                    var rescontent = await response.Response.Content.ReadAsStringAsync();

                    string msg = "StatusCode: " + response.Response.StatusCode + Environment.NewLine;
                    msg += rescontent;
                    Log.Info(msg);
                    Program.MainForm.ShowMessageBox(msg);
                }
            }
            catch (Exception e)
            {
                Log.Error(e);
                Program.MainForm.ShowMessageBox(e.Message.ToString());
            }
            if (!noupdate)
            {
                OnGroupJoinCallback?.Invoke(this, myGroup);
            }
        }
Example #8
0
        private async Task <SINner> CheckIfUpdateSINnerFile(SINner dbsinner, ApplicationUser user)
        {
            if (dbsinner != null)
            {
                var roles = await _userManager.GetRolesAsync(user);

                foreach (var role in roles)
                {
                    if (role.ToUpperInvariant() == "Administrator".ToUpperInvariant())
                    {
                        return(dbsinner);
                    }
                }
                var editseq = (from a in dbsinner.SINnerMetaData.Visibility.UserRights where a.EMail.ToUpperInvariant() == user.NormalizedEmail select a).ToList();
                foreach (var edit in editseq)
                {
                    if (edit.CanEdit == true)
                    {
                        return(dbsinner);
                    }
                }
                if (dbsinner.MyGroup != null)
                {
                    if (!String.IsNullOrEmpty(dbsinner.MyGroup.MyAdminIdentityRole))
                    {
                        var localadmins = await _userManager.GetUsersInRoleAsync(dbsinner.MyGroup.MyAdminIdentityRole);

                        if (localadmins.Contains(user))
                        {
                            return(dbsinner);
                        }
                    }
                    if (!String.IsNullOrEmpty(dbsinner.MyGroup.GroupCreatorUserName))
                    {
                        if (dbsinner.MyGroup.GroupCreatorUserName == user.UserName)
                        {
                            return(dbsinner);
                        }
                    }
                }
                throw new ChummerHub.NoUserRightException(user.UserName, dbsinner.Id);
            }
            return(null);
        }
Example #9
0
        private async Task <SINner> CheckIfUpdateSINnerFile(SINner dbsinner, ApplicationUser user)
        {
            if (dbsinner != null)
            {
                if (dbsinner.SINnerMetaData?.Visibility?.UserRights == null)
                {
                    dbsinner = await(from a in _context.SINners
                                     .Include(a => a.SINnerMetaData)
                                     .Include(a => a.SINnerMetaData.Visibility)
                                     .Include(a => a.SINnerMetaData.Visibility.UserRights)
                                     .Include(a => a.MyGroup)
                                     select a).FirstOrDefaultAsync();
                }
                var editseq = (from a in dbsinner.SINnerMetaData.Visibility.UserRights where a.EMail == user.NormalizedEmail select a).ToList();
                foreach (var edit in editseq)
                {
                    if (edit.CanEdit == true)
                    {
                        return(dbsinner);
                    }
                }
                if (dbsinner.MyGroup != null)
                {
                    if (!String.IsNullOrEmpty(dbsinner.MyGroup.MyAdminIdentityRole))
                    {
                        var localadmins = await _userManager.GetUsersInRoleAsync(dbsinner.MyGroup.MyAdminIdentityRole);

                        if (localadmins.Contains(user))
                        {
                            return(dbsinner);
                        }
                    }
                    if (!String.IsNullOrEmpty(dbsinner.MyGroup.GroupCreatorUserName))
                    {
                        if (dbsinner.MyGroup.GroupCreatorUserName == user.UserName)
                        {
                            return(dbsinner);
                        }
                    }
                }
                throw new ChummerHub.NoUserRightException(user.UserName, dbsinner.Id);
            }
            return(null);
        }
Example #10
0
        public async Task <bool> Upload()
        {
            try
            {
                using (new CursorWait(true, PluginHandler.MainForm))
                {
                    if (MySINnerFile.DownloadedFromSINnersTime > this.MyCharacter.FileLastWriteTime)
                    {
                        return(true);
                    }
                    var client = await StaticUtils.GetClient();

                    var found = await client.GetSINByIdWithHttpMessagesAsync(this.MySINnerFile.Id.Value);

                    if (found.Response.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        var sinjson = await found.Response.Content.ReadAsStringAsync();

                        var    foundobj = Newtonsoft.Json.JsonConvert.DeserializeObject <SINner>(sinjson);
                        SINner foundsin = foundobj as SINner;
                        if (foundsin.LastChange >= this.MyCharacter.FileLastWriteTime)
                        {
                            //is already up to date!
                            return(true);
                        }
                    }
                    this.MySINnerFile.SiNnerMetaData.Tags = this.PopulateTags();
                    await this.PrepareModel();

                    await ChummerHub.Client.Backend.Utils.PostSINnerAsync(this);

                    await ChummerHub.Client.Backend.Utils.UploadChummerFileAsync(this);

                    return(true);
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Trace.TraceError(e.Message, e);
                Debug.WriteLine(e.ToString());
                throw;
            }
        }
Example #11
0
        public CharacterExtended(Character character, string fileElement = null, SINner mySINnerLoading = null, frmCharacterRoster.CharacterCache myCharacterCache = null) : this(character, fileElement, myCharacterCache)
        {
            if (mySINnerLoading != null)
            {
                var backup = MySINnerFile;
                MySINnerFile = mySINnerLoading;
                if (MySINnerFile?.SiNnerMetaData != null)
                {
                    if (MySINnerFile.SiNnerMetaData.Id == null || MySINnerFile.SiNnerMetaData.Id == Guid.Empty)
                    {
                        MySINnerFile.SiNnerMetaData.Id = backup.SiNnerMetaData.Id;
                    }

                    if (MySINnerFile.SiNnerMetaData.Tags?.Count < backup?.SiNnerMetaData?.Tags?.Count)
                    {
                        MySINnerFile.SiNnerMetaData.Tags = new List <Tag>(backup.SiNnerMetaData.Tags);
                    }
                }
            }
        }
Example #12
0
        private void UploadFilePermission(DriveService service, SINner chummerFile)
        {
            try
            {
                Google.Apis.Drive.v3.Data.Permission permission = new Google.Apis.Drive.v3.Data.Permission();
                permission.Type = "anyone";
                permission.Role = "reader";
                permission.AllowFileDiscovery = true;

                PermissionsResource.CreateRequest request = service.Permissions.Create(permission, chummerFile.GoogleDriveFileId);
                request.Fields = "id";
                request.Execute();
            }
            catch (Exception e)
            {
                string msg = "Error while setting permissions for " + chummerFile.Id + ": " + Environment.NewLine;
                msg += e.ToString();
                _logger.LogError(msg);
                throw;
            }
        }
        public CharacterExtended(Character character, string fileElement = null, SINner mySINnerLoading = null) : this(character, fileElement)
        {
            if (mySINnerLoading != null)
            {
                var backup = this._MySINnerFile;
                this._MySINnerFile = mySINnerLoading;
                if ((this._MySINnerFile?.SiNnerMetaData?.Id == null) ||
                    (this._MySINnerFile.SiNnerMetaData?.Id == Guid.Empty))
                {
                    if (this._MySINnerFile?.SiNnerMetaData != null)
                    {
                        this._MySINnerFile.SiNnerMetaData.Id = backup.SiNnerMetaData.Id;
                    }
                }

                if (this._MySINnerFile?.SiNnerMetaData?.Tags?.Count() < backup?.SiNnerMetaData?.Tags?.Count())
                {
                    this._MySINnerFile.SiNnerMetaData.Tags = backup.SiNnerMetaData.Tags;
                }
            }
        }
Example #14
0
        private static void OnMyDoubleClick(SINner sinner, CharacterCache objCache)
        {
            var t = DownloadFileTask(sinner, objCache);

            t.ContinueWith((downloadtask) =>
            {
                PluginHandler.MySINnerLoading = sinner;
                PluginHandler.MainForm.CharacterRoster.SetMyEventHandlers(true);
                string filepath = downloadtask.Result as string;
                PluginHandler.MainForm.DoThreadSafe(() =>
                {
                    Character c = PluginHandler.MainForm.LoadCharacter(filepath);
                    if (c != null)
                    {
                        SwitchToCharacter(c);
                    }
                    SwitchToCharacter(objCache);

                    PluginHandler.MainForm.CharacterRoster.SetMyEventHandlers(false);
                    PluginHandler.MySINnerLoading = null;
                });
            });
        }
Example #15
0
        public CharacterExtended(Character character, string fileElement = null, SINner mySINnerLoading = null) : this(character, fileElement)
        {
            if (mySINnerLoading != null)
            {
                var backup = this._MySINnerFile;
                this._MySINnerFile = mySINnerLoading;
                if ((this._MySINnerFile.MyExtendedAttributes?.Id == null) ||
                    (this._MySINnerFile.MyExtendedAttributes?.Id == Guid.Empty) ||
                    (String.IsNullOrEmpty(this._MySINnerFile.MyExtendedAttributes?.JsonSummary)))
                {
                    this._MySINnerFile.MyExtendedAttributes = backup.MyExtendedAttributes;
                }
                if ((this._MySINnerFile.SiNnerMetaData?.Id == null) ||
                    (this._MySINnerFile.SiNnerMetaData?.Id == Guid.Empty))
                {
                    this._MySINnerFile.SiNnerMetaData.Id = backup.SiNnerMetaData.Id;
                }

                if (this._MySINnerFile.SiNnerMetaData.Tags.Count() < backup.SiNnerMetaData.Tags.Count())
                {
                    this._MySINnerFile.SiNnerMetaData.Tags = backup.SiNnerMetaData.Tags;
                }
            }
        }
        public CharacterExtended(Character character, string fileElement = null)
        {
            MyCharacter  = character;
            MySINnerFile = new SINner();
            if (string.IsNullOrEmpty(fileElement))
            {
                MySINnerFile.SiNnerMetaData = new SINnerMetaData
                {
                    Id         = Guid.NewGuid(),
                    Tags       = new List <Tag>(),
                    Visibility = new SINnerVisibility()
                };
            }
            else
            {
                try
                {
                    MySINnerFile.SiNnerMetaData = JsonConvert.DeserializeObject <SINnerMetaData>(fileElement);
                }
                catch (Exception e)
                {
                    System.Diagnostics.Trace.TraceWarning(e.ToString());
                }
            }

            if (MySINnerFile.SiNnerMetaData.Visibility != null)
            {
                if (MySINnerFile.SiNnerMetaData.Visibility.Id == null)
                {
                    MySINnerFile.SiNnerMetaData.Visibility.Id = Guid.NewGuid();
                }
                return;
            }

            if (!string.IsNullOrEmpty(Properties.Settings.Default.SINnerVisibility))
            {
                MySINnerFile.SiNnerMetaData.Visibility =
                    JsonConvert.DeserializeObject <SINnerVisibility>(Properties.Settings.Default.SINnerVisibility);
            }

            if (MySINnerFile.SiNnerMetaData.Visibility?.Id == null)
            {
                MySINnerFile.SiNnerMetaData.Visibility.Id = Guid.NewGuid();
            }

            var cache = new frmCharacterRoster.CharacterCache(character.FileName);

            this.MySINnerFile.LastChange = MyCharacter.FileLastWriteTime;

            if (MySINnerIds.TryGetValue(MyCharacter.Alias, out var singuid))
            {
                MySINnerFile.Id = singuid;
            }
            else
            {
                MySINnerFile.Id = Guid.NewGuid();
                MySINnerIds.Add(MyCharacter.Alias, MySINnerFile.Id.Value);
                MySINnerIds = MySINnerIds; //Save it!
            }
            this.MySINnerFile.JsonSummary = JsonConvert.SerializeObject(cache);
        }
Example #17
0
        private async Task <ActionResult <ResultAccountGetSinnersByAuthorization> > GetSINnersByAuthorizationInternal()
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();
            //var tc = new Microsoft.ApplicationInsights.TelemetryClient();
            ResultAccountGetSinnersByAuthorization res = null;

            SINSearchGroupResult ret = new SINSearchGroupResult();

            res = new ResultAccountGetSinnersByAuthorization(ret);
            SINnerGroup       sg  = new SINnerGroup();
            SINnerSearchGroup ssg = new SINnerSearchGroup(sg)
            {
                MyMembers = new List <SINnerSearchGroupMember>()
            };

            using (var t = new TransactionScope(TransactionScopeOption.Required,
                                                new TransactionOptions
            {
                IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted
            }, TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    var user = await _signInManager.UserManager.GetUserAsync(User);

                    if (user == null)
                    {
                        var e = new AuthenticationException("User is not authenticated.");
                        res = new ResultAccountGetSinnersByAuthorization(e)
                        {
                            ErrorText = "Unauthorized"
                        };
                        return(BadRequest(res));
                    }

                    var roles = await _userManager.GetRolesAsync(user);

                    ret.Roles     = roles.ToList();
                    ssg.Groupname = user.UserName;
                    ssg.Id        = Guid.Empty;
                    //get all from visibility
                    List <SINner> mySinners = await SINner.GetSINnersFromUser(user, _context, true);

                    MetricTelemetry mt = new MetricTelemetry("GetSINersByAuthorization", "SINners found",
                                                             mySinners.Count, 0, 0, 0, 0);
                    tc.TrackMetric(mt);
                    foreach (var sin in mySinners)
                    {
                        //check if that char is already added:
                        var foundseq = (from a in ssg.MyMembers where a.MySINner.Id == sin.Id select a);
                        if (foundseq.Any())
                        {
                            continue;
                        }
                        sin.LastDownload = DateTime.Now;
                        SINnerSearchGroupMember ssgm = new SINnerSearchGroupMember
                        {
                            MySINner = sin,
                            Username = user.UserName
                        };
                        if (sin.MyGroup?.Id != null)
                        {
                            if (!user.FavoriteGroups.Any(a => a.FavoriteGuid == sin.MyGroup.Id.Value))
                            {
                                user.FavoriteGroups.Add(new ApplicationUserFavoriteGroup()
                                {
                                    FavoriteGuid = sin.MyGroup.Id.Value
                                });
                            }
                        }
                        else
                        {
                            ssg.MyMembers.Add(ssgm);
                        }
                    }

                    user.FavoriteGroups = user.FavoriteGroups.GroupBy(a => a.FavoriteGuid).Select(b => b.First()).ToList();


                    foreach (var singroupId in user.FavoriteGroups)
                    {
                        SINnerSearchGroup ssgFromSIN;
                        var singroup = await _context.SINnerGroups.FirstOrDefaultAsync(a => a.Id == singroupId.FavoriteGuid);

                        if (ssg.MySINSearchGroups.Any(a => a.Id == singroupId.FavoriteGuid))
                        {
                            ssgFromSIN = ssg.MySINSearchGroups.FirstOrDefault(a => a.Id == singroupId.FavoriteGuid);
                        }
                        else
                        {
                            ssgFromSIN = new SINnerSearchGroup(singroup);
                            ssg.MySINSearchGroups.Add(ssgFromSIN);
                        }

                        //add all members of his group
                        var members = await singroup.GetGroupMembers(_context, false);

                        foreach (var member in members)
                        {
                            member.LastDownload     = DateTime.Now;
                            member.MyGroup          = singroup;
                            member.MyGroup.MyGroups = new List <SINnerGroup>();
                            SINnerSearchGroupMember sinssgGroupMember = new SINnerSearchGroupMember
                            {
                                MySINner = member
                            };
                            //check if it is already added:
                            var groupseq = from a in ssgFromSIN.MyMembers where a.MySINner == member select a;
                            if (groupseq.Any())
                            {
                                continue;
                            }
                            ssgFromSIN.MyMembers.Add(sinssgGroupMember);
                            //}
                        }

                        singroup.PasswordHash = "";
                        singroup.MyGroups     = new List <SINnerGroup>();
                    }
                    await _context.SaveChangesAsync();

                    ret.SINGroups.Add(ssg);
                    res = new ResultAccountGetSinnersByAuthorization(ret);

                    return(Ok(res));
                }
                catch (Exception e)
                {
                    try
                    {
                        var user = await _signInManager.UserManager.GetUserAsync(User);

                        ExceptionTelemetry et = new ExceptionTelemetry(e);
                        et.Properties.Add("user", User.Identity.Name);
                        tc.TrackException(et);
                    }
                    catch (Exception ex)
                    {
                        _logger?.LogError(ex.ToString());
                    }

                    res = new ResultAccountGetSinnersByAuthorization(e);
                    return(BadRequest(res));
                }
                finally
                {
                    Microsoft.ApplicationInsights.DataContracts.AvailabilityTelemetry telemetry =
                        new Microsoft.ApplicationInsights.DataContracts.AvailabilityTelemetry("GetSINnersByAuthorization",
                                                                                              DateTimeOffset.Now, sw.Elapsed, "Azure", res?.CallSuccess ?? false, res?.ErrorText);
                    tc.TrackAvailability(telemetry);
                }

#pragma warning disable CS0162 // Unreachable code detected
                t.Complete();
#pragma warning restore CS0162 // Unreachable code detected
            }
        }
Example #18
0
        private async Task <IActionResult> PostSINnerInternal(UploadInfoObject uploadInfo)
        {
            _logger.LogTrace("Post SINnerInternalt: " + uploadInfo + ".");
            ApplicationUser user   = null;
            SINner          sinner = null;

            try
            {
                if (!ModelState.IsValid)
                {
                    var errors = ModelState.Select(x => x.Value.Errors)
                                 .Where(y => y.Count > 0)
                                 .ToList();
                    string msg = "ModelState is invalid: ";
                    foreach (var err in errors)
                    {
                        foreach (var singleerr in err)
                        {
                            msg += Environment.NewLine + "\t" + singleerr.ToString();
                        }
                    }
                    return(BadRequest(new HubException(msg)));
                }
                if (uploadInfo.UploadDateTime == null)
                {
                    uploadInfo.UploadDateTime = DateTime.Now;
                }
                if (uploadInfo.Client != null)
                {
                    if (!UploadClientExists(uploadInfo.Client.Id))
                    {
                        _context.UploadClients.Add(uploadInfo.Client);
                    }
                    else
                    {
                        _context.UploadClients.Attach(uploadInfo.Client);
                        _context.Entry(uploadInfo.Client).State = EntityState.Modified;
                        _context.Entry(uploadInfo.Client).CurrentValues.SetValues(uploadInfo.Client);
                    }
                }
                var returncode = HttpStatusCode.OK;
                user = await _signInManager.UserManager.FindByNameAsync(User.Identity.Name);

                foreach (var tempsinner in uploadInfo.SINners)
                {
                    sinner = tempsinner;
                    if (sinner.Id.ToString() == "string")
                    {
                        sinner.Id = Guid.Empty;
                    }

                    if (String.IsNullOrEmpty(sinner.MyExtendedAttributes.JsonSummary))
                    {
                        return(BadRequest("sinner " + sinner.Id + ": JsonSummary == null"));
                    }

                    if (sinner.SINnerMetaData.Visibility.UserRights.Any() == false)
                    {
                        return(BadRequest("Sinner  " + sinner.Id + ": Visibility contains no entries!"));
                    }

                    if (sinner.LastChange == null)
                    {
                        return(BadRequest("Sinner  " + sinner.Id + ": LastChange not set!"));
                    }
                    if ((sinner.SINnerMetaData.Visibility.Id == null) ||
                        (sinner.SINnerMetaData.Visibility.Id == Guid.Empty))
                    {
                        sinner.SINnerMetaData.Visibility.Id = Guid.NewGuid();
                    }
                    var oldsinner = (from a in _context.SINners.Include(a => a.SINnerMetaData.Visibility.UserRights)
                                     .Include(b => b.MyGroup)
                                     where a.Id == sinner.Id
                                     select a).FirstOrDefault();
                    if (oldsinner != null)
                    {
                        var  olduserrights = oldsinner.SINnerMetaData.Visibility.UserRights.ToList();
                        bool canedit       = false;
                        foreach (var oldright in olduserrights)
                        {
                            if ((oldright.EMail.ToLowerInvariant() == user.Email.ToLowerInvariant() &&
                                 (oldright.CanEdit == true)))
                            {
                                canedit = true;
                                break;
                            }
                        }
                        if (!canedit)
                        {
                            string msg = "SINner " + sinner.Id + " is not editable for user " + user.Email + ".";
                            throw new NoUserRightException(msg);
                        }
                        _context.UserRights.RemoveRange(olduserrights);
                        bool userfound = false;
                        foreach (var ur in sinner.SINnerMetaData.Visibility.UserRights)
                        {
                            if (ur.EMail.ToLowerInvariant() == user.Email.ToLowerInvariant())
                            {
                                ur.CanEdit = true;
                                userfound  = true;
                            }
                            ur.Id       = Guid.NewGuid();
                            ur.SINnerId = sinner.Id;
                            _context.UserRights.Add(ur);
                        }
                        if (!userfound)
                        {
                            SINerUserRight ownUser = new SINerUserRight();
                            ownUser.Id       = Guid.NewGuid();
                            ownUser.SINnerId = sinner.Id;
                            ownUser.CanEdit  = true;
                            ownUser.EMail    = user.Email;
                            sinner.SINnerMetaData.Visibility.UserRights.Add(ownUser);
                            _context.UserRights.Add(ownUser);
                        }
                    }
                    else
                    {
                        var ownuserfound = false;
                        var list         = sinner.SINnerMetaData.Visibility.UserRights.ToList();
                        foreach (var ur in list)
                        {
                            ur.SINnerId = sinner.Id;
                            if (ur.EMail.ToLowerInvariant() == "*****@*****.**".ToLowerInvariant())
                            {
                                sinner.SINnerMetaData.Visibility.UserRights.Remove(ur);
                            }
                            if (ur.EMail.ToLowerInvariant() == user.Email.ToLowerInvariant())
                            {
                                ownuserfound = true;
                            }
                        }
                        if (!ownuserfound)
                        {
                            SINerUserRight ownright = new SINerUserRight();
                            ownright.CanEdit  = true;
                            ownright.EMail    = user.Email;
                            ownright.SINnerId = sinner.Id;
                            ownright.Id       = Guid.NewGuid();
                            sinner.SINnerMetaData.Visibility.UserRights.Add(ownright);
                        }
                    }

                    foreach (var tag in sinner.SINnerMetaData.Tags)
                    {
                        tag.SetSinnerIdRecursive(sinner.Id);
                    }

                    sinner.UploadClientId = uploadInfo.Client.Id;
                    SINner dbsinner = await CheckIfUpdateSINnerFile(sinner.Id.Value, user);

                    SINnerGroup oldgroup = null;
                    if (dbsinner != null)
                    {
                        oldgroup = dbsinner.MyGroup;
                        _context.SINners.Attach(dbsinner);
                        if (String.IsNullOrEmpty(sinner.GoogleDriveFileId))
                        {
                            sinner.GoogleDriveFileId = dbsinner.GoogleDriveFileId;
                        }
                        if (String.IsNullOrEmpty(sinner.DownloadUrl))
                        {
                            sinner.DownloadUrl = dbsinner.DownloadUrl;
                        }

                        _context.UserRights.RemoveRange(dbsinner.SINnerMetaData.Visibility.UserRights);
                        _context.SINnerVisibility.Remove(dbsinner.SINnerMetaData.Visibility);
                        var alltags = await dbsinner.GetTagsForSinnerFlat(_context);

                        _context.Tags.RemoveRange(alltags);
                        _context.SINnerMetaData.Remove(dbsinner.SINnerMetaData);
                        _context.SINners.Remove(dbsinner);
                        dbsinner.SINnerMetaData.Visibility.UserRights.Clear();
                        dbsinner.SINnerMetaData.Visibility = null;
                        dbsinner.SINnerMetaData.Tags       = null;
                        dbsinner.SINnerMetaData            = null;

                        await _context.SaveChangesAsync();

                        await _context.SINners.AddAsync(sinner);

                        string msg = "Sinner " + sinner.Id + " updated: " + _context.Entry(dbsinner).State.ToString();
                        msg += Environment.NewLine + Environment.NewLine + "LastChange: " + dbsinner.LastChange;
                        _logger.LogError(msg);
                        List <Tag> taglist = sinner.SINnerMetaData.Tags;
                        UpdateEntityEntries(taglist);
                    }
                    else
                    {
                        returncode     = HttpStatusCode.Created;
                        sinner.MyGroup = null;
                        _context.SINners.Add(sinner);
                    }

                    try
                    {
                        await _context.SaveChangesAsync();

                        if (oldgroup != null)
                        {
                            var roles = await _userManager.GetRolesAsync(user);

                            await SINnerGroupController.PutSiNerInGroupInternal(oldgroup.Id.Value, sinner.Id.Value, user, _context,
                                                                                _logger, oldgroup.PasswordHash, roles);
                        }
                    }
                    catch (DbUpdateConcurrencyException ex)
                    {
                        foreach (var entry in ex.Entries)
                        {
                            if (entry.Entity is SINner)
                            {
                                Utils.DbUpdateConcurrencyExceptionHandler(entry, _logger);
                            }
                            else if (entry.Entity is Tag)
                            {
                                Utils.DbUpdateConcurrencyExceptionHandler(entry, _logger);
                            }
                            else
                            {
                                throw new NotSupportedException(
                                          "Don't know how to handle concurrency conflicts for "
                                          + entry.Metadata.Name);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        try
                        {
                            var tc = new Microsoft.ApplicationInsights.TelemetryClient();
                            Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry telemetry = new Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry(e);
                            telemetry.Properties.Add("User", user?.Email);
                            telemetry.Properties.Add("SINnerId", sinner?.Id?.ToString());
                            tc.TrackException(telemetry);
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError(ex.ToString());
                        }
                        if (e is HubException)
                        {
                            return(Conflict(e));
                        }

                        HubException hue = new HubException("Exception in PostSINnerFile: " + e.ToString(), e);
                        //var msg = new System.Net.Http.HttpResponseMessage(HttpStatusCode.Conflict) { ReasonPhrase = e.Message };
                        return(Conflict(hue));
                    }
                }

                List <Guid> myids = (from a in uploadInfo.SINners select a.Id.Value).ToList();
                switch (returncode)
                {
                case HttpStatusCode.OK:
                    return(Accepted("PostSIN", myids));

                case HttpStatusCode.Created:
                    return(CreatedAtAction("PostSIN", myids));

                default:
                    break;
                }
                return(BadRequest());
            }
            catch (Exception e)
            {
                try
                {
                    var tc = new Microsoft.ApplicationInsights.TelemetryClient();
                    Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry telemetry = new Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry(e);
                    telemetry.Properties.Add("User", user?.Email);
                    telemetry.Properties.Add("SINnerId", sinner?.Id?.ToString());
                    tc.TrackException(telemetry);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.ToString());
                }
                if (e is HubException)
                {
                    return(BadRequest(e));
                }

                HubException hue = new HubException("Exception in PostSINnerFile: " + e.Message, e);
                return(BadRequest(hue));
            }
        }
Example #19
0
        public async Task <IActionResult> PutSIN([FromRoute] Guid id, IFormFile uploadedFile)
        {
            ApplicationUser user     = null;
            SINner          dbsinner = null;

            try
            {
                var sin = await _context.SINners.Include(a => a.SINnerMetaData.Visibility.UserRights).FirstOrDefaultAsync(a => a.Id == id);

                if (sin == null)
                {
                    return(NotFound("Sinner with Id " + id + " not found!"));
                }
                user = await _signInManager.UserManager.FindByNameAsync(User.Identity.Name);

                dbsinner = await CheckIfUpdateSINnerFile(id, user);

                if (dbsinner == null)
                {
                    return(Conflict("CheckIfUpdateSINnerFile"));
                }
                sin.GoogleDriveFileId = dbsinner.GoogleDriveFileId;
                if (user == null)
                {
                    throw new NoUserRightException("User not found!");
                }

                sin.DownloadUrl = Startup.GDrive.StoreXmlInCloud(sin, uploadedFile);
                _context.Entry(dbsinner).CurrentValues.SetValues(sin);
                try
                {
                    var tc = new Microsoft.ApplicationInsights.TelemetryClient();
                    Microsoft.ApplicationInsights.DataContracts.EventTelemetry telemetry = new Microsoft.ApplicationInsights.DataContracts.EventTelemetry("PutStoreXmlInCloud");
                    telemetry.Properties.Add("User", user.Email);
                    telemetry.Properties.Add("SINnerId", sin.Id.ToString());
                    telemetry.Properties.Add("FileName", uploadedFile.FileName?.ToString());
                    telemetry.Metrics.Add("FileSize", uploadedFile.Length);
                    tc.TrackEvent(telemetry);
                }
                catch (Exception e)
                {
                    _logger.LogError(e.ToString());
                }
                try
                {
                    int x = await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException e)
                {
                    return(Conflict(e));
                }

                return(Ok(sin.DownloadUrl));
            }
            catch (NoUserRightException e)
            {
                return(BadRequest(e));
            }
            catch (Exception e)
            {
                try
                {
                    var tc = new Microsoft.ApplicationInsights.TelemetryClient();
                    Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry telemetry = new Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry(e);
                    telemetry.Properties.Add("User", user?.Email);
                    telemetry.Properties.Add("SINnerId", dbsinner?.Id?.ToString());
                    telemetry.Properties.Add("FileName", uploadedFile.FileName?.ToString());
                    telemetry.Metrics.Add("FileSize", uploadedFile.Length);
                    tc.TrackException(telemetry);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.ToString());
                }
                if (e is HubException)
                {
                    return(BadRequest(e));
                }
                HubException hue = new HubException("Exception in PutSINnerFile: " + e.Message, e);
                return(BadRequest(hue));
            }
        }
Example #20
0
        private string UpdateFileToDrive(DriveService service, IFormFile uploadFile, string conentType, SINner chummerFile)
        {
            FilesResource.UpdateMediaUpload request;
            try
            {
                var fileMetadata = new Google.Apis.Drive.v3.Data.File();
                fileMetadata.Properties = new Dictionary <string, string>();
                foreach (var tag in chummerFile.SINnerMetaData.Tags)
                {
                    fileMetadata.Properties.Add(tag.Display, tag.TagValue);
                }
                fileMetadata.Name = chummerFile.Id.ToString() + ".chum5z";
                //fileMetadata.Parents = new List<string> { _folderId };
                _logger.LogError("Updating " + uploadFile.FileName + " as " + fileMetadata.Name);// + " to folder: " + _folderId);
                //fileMetadata.MimeType = _contentType;
                fileMetadata.OriginalFilename = uploadFile.FileName;

                request        = service.Files.Update(fileMetadata, chummerFile.GoogleDriveFileId, uploadFile.OpenReadStream(), conentType);
                request.Fields = "id, webContentLink";
                var uploadprogress = request.Upload();

                while ((uploadprogress.Status != Google.Apis.Upload.UploadStatus.Completed) &&
                       (uploadprogress.Status != Google.Apis.Upload.UploadStatus.Failed))
                {
                    if (uploadprogress.Exception != null)
                    {
                        throw uploadprogress.Exception;
                    }
                    uploadprogress = request.Resume();
                }
                if (uploadprogress.Status == Google.Apis.Upload.UploadStatus.Failed)
                {
                    _logger.LogError("Chummer \"" + chummerFile.Id.ToString() + "\" upload failed: " + uploadprogress.Exception?.ToString());
                    throw uploadprogress.Exception;
                }
            }
            catch (Exception e)
            {
                Exception innere = e;
                while (innere.InnerException != null)
                {
                    innere = innere.InnerException;
                }
                _logger.LogError(innere.ToString());
                throw;
            }

            _logger.LogError("Chummer \"" + chummerFile.Id.ToString() + "\" updated: " + request.ResponseBody?.WebContentLink.ToString());

            chummerFile.GoogleDriveFileId = request.ResponseBody?.Id;
            chummerFile.DownloadUrl       = request.ResponseBody?.WebContentLink;

            //UploadFilePermission(service, chummerFile);

            return(request.ResponseBody?.WebContentLink);
        }
Example #21
0
        private async Task <SINner> CheckIfUpdateSINnerFileInternal(Guid id, ApplicationUser user, bool allincludes)
        {
            if (id == Guid.Empty)
            {
                throw new ArgumentNullException("id", "Id is empty!");
            }

            SINner dbsinner = null;

            if (allincludes)
            {
                dbsinner = await(from a in _context.SINners
                                 .Include(a => a.SINnerMetaData)
                                 .Include(a => a.SINnerMetaData.Visibility)
                                 .Include(a => a.SINnerMetaData.Visibility.UserRights)
                                 .Include(a => a.MyExtendedAttributes)
                                 .Include(a => a.MyGroup)
                                 where a.Id == id
                                 select a).FirstOrDefaultAsync();
            }
            else
            {
                dbsinner = await(from a in _context.SINners
                                 .Include(a => a.MyGroup)
                                 where a.Id == id
                                 select a).FirstOrDefaultAsync();
            }

            if (dbsinner == null)
            {
                return(null);
            }
            var dbsinnerseq = await(from a in _context.UserRights
                                    where a.SINnerId == id &&
                                    a.EMail.ToUpperInvariant() == user.NormalizedEmail &&
                                    a.CanEdit == true
                                    select a).ToListAsync();

            if (dbsinnerseq.Any())
            {
                return(dbsinner);
            }
            if (dbsinner.MyGroup != null)
            {
                if (!String.IsNullOrEmpty(dbsinner.MyGroup.MyAdminIdentityRole))
                {
                    var localadmins = await _userManager.GetUsersInRoleAsync(dbsinner.MyGroup.MyAdminIdentityRole);

                    if (localadmins.Contains(user))
                    {
                        return(dbsinner);
                    }
                }
                if (!String.IsNullOrEmpty(dbsinner.MyGroup.GroupCreatorUserName))
                {
                    if (dbsinner.MyGroup.GroupCreatorUserName == user.UserName)
                    {
                        return(dbsinner);
                    }
                }
            }
            throw new ChummerHub.NoUserRightException(user.UserName, dbsinner.Id);
        }
        internal static async Task <ActionResult <SINner> > PutSiNerInGroupInternal(Guid GroupId, Guid SinnerId, ApplicationUser user, ApplicationDbContext context, ILogger logger, string pwhash, IList <string> userroles)
        {
            try
            {
                if (GroupId == Guid.Empty)
                {
                    throw new ArgumentNullException(nameof(GroupId), "GroupId may not be empty.");
                }

                if (SinnerId == Guid.Empty)
                {
                    throw new ArgumentNullException(nameof(SinnerId), "SinnerId may not be empty.");
                }

                var groupset = await(from a in context.SINnerGroups.Include(a => a.MySettings)
                                     where a.Id == GroupId
                                     select a).ToListAsync();
                if (!groupset.Any())
                {
                    throw new ArgumentException("GroupId not found", nameof(GroupId));
                }

                var group = groupset.FirstOrDefault();

                if ((!String.IsNullOrEmpty(group.PasswordHash)) &&
                    (group.PasswordHash != pwhash))
                {
                    throw new NoUserRightException("PW is wrong!");
                }

                if (!String.IsNullOrEmpty(group.MyAdminIdentityRole))
                {
                    if (!userroles.Contains(group.MyAdminIdentityRole))
                    {
                        throw new NoUserRightException("User " + user.UserName + " has not the role " + group.MyAdminIdentityRole + ".");
                    }
                }

                var sinnerseq = await(from a in context.SINners
                                      .Include(a => a.MyGroup)
                                      .Include(a => a.SINnerMetaData)
                                      .Include(a => a.SINnerMetaData.Visibility)
                                      .Include(a => a.SINnerMetaData.Visibility.UserRights)
                                      where a.Id == SinnerId
                                      select a).ToListAsync();
                SINner sin = null;
                if (!sinnerseq.Any())
                {
                    throw new ArgumentException("SinnerId not found", nameof(SinnerId));
                }
                else
                {
                    sin = sinnerseq.FirstOrDefault();
                    if (sin != null)
                    {
                        sin.MyGroup = group;
                    }
                }

                await context.SaveChangesAsync();

                return(sin);
            }
            catch (Exception e)
            {
                try
                {
                    var tc = new Microsoft.ApplicationInsights.TelemetryClient();
                    Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry telemetry =
                        new Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry(e);
                    telemetry.Properties.Add("User", user?.Email);
                    telemetry.Properties.Add("GroupId", GroupId.ToString());
                    tc.TrackException(telemetry);
                }
                catch (Exception ex)
                {
                    logger?.LogError(ex.ToString());
                }

                HubException hue = new HubException("Exception in PutSiNerInGroupInternal: " + e.Message, e);
                throw hue;
            }
        }
Example #23
0
        public async Task <string> PrepareModel()
        {
            string zipPath = Path.Combine(Path.GetTempPath(), "SINner", MySINnerFile.Id + ".chum5z");

            if (PluginHandler.MySINnerLoading != null)
            {
                if (MySINnerIds.ContainsKey(MyCharacter.Alias))
                {
                    MySINnerIds.Remove(MyCharacter.Alias);
                }
            }
            if (MySINnerIds.TryGetValue(MyCharacter.Alias, out var singuid))
            {
                MySINnerFile.Id = singuid;
            }
            else
            {
                if (PluginHandler.MySINnerLoading != null)
                {
                    _MySINnerFile = PluginHandler.MySINnerLoading;
                    MySINnerIds.Add(MyCharacter.Alias, MySINnerFile.Id.Value);
                    return(zipPath);
                }
                else
                {
                    if (String.IsNullOrEmpty(MySINnerFile.Alias))
                    {
                        MySINnerFile.Alias = MyCharacter.Alias;
                        if (String.IsNullOrEmpty(MySINnerFile.Alias))
                        {
                            MySINnerFile.Alias = MyCharacter.Name;
                        }
                    }
                    var client = await StaticUtils.GetClient();

                    var res = await client.GetOwnedSINByAliasWithHttpMessagesAsync(MySINnerFile.Alias);

                    if (res.Response.StatusCode == HttpStatusCode.NotFound)
                    {
                        MySINnerFile.Id = Guid.NewGuid();
                    }
                    else if (res.Response.StatusCode == HttpStatusCode.OK)
                    {
                        string message = MySINnerFile.Alias +
                                         " is already available online, but the current client uses a local version of that file." +
                                         Environment.NewLine + Environment.NewLine;
                        message += "Do you want to use only one version and update it through SINner?" +
                                   Environment.NewLine + Environment.NewLine;
                        message += "YES:\tuse the same (= only one) version and get" +
                                   Environment.NewLine;
                        message += "\tupdates on this client when you save" + Environment.NewLine;
                        message += "\tthe chummer on another client(recommended)" + Environment.NewLine
                                   + Environment.NewLine;
                        message +=
                            "NO:\tgenerate a new \"Fork\" of this character," +
                            Environment.NewLine;
                        message += "\tthat is not linked to the online one" + Environment.NewLine;
                        message +=
                            "\tand use this new version from now on," + Environment.NewLine;
                        message += "but only on this client (NOT recommended)."
                                   + Environment.NewLine + Environment.NewLine;
                        var result = MessageBox.Show(message, "SIN already found online", MessageBoxButtons.YesNoCancel,
                                                     MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
                        if (result == DialogResult.Cancel)
                        {
                            throw new ArgumentException("User aborted perparation for upload!");
                        }
                        else if (result == DialogResult.No)
                        {
                            MySINnerFile.Id = Guid.NewGuid();
                        }
                        else
                        {
                            foreach (var sin in res.Body)
                            {
                                if (sin.Id != null)
                                {
                                    MySINnerFile.Id = sin.Id;
                                    break;
                                }
                            }
                        }
                    }
                }

                MySINnerIds.Add(MyCharacter.Alias, MySINnerFile.Id.Value);
                MySINnerIds = MySINnerIds; //Save it!
            }
            zipPath = Path.Combine(Path.GetTempPath(), "SINner", MySINnerFile.Id.Value + ".chum5z");
            MySINnerFile.UploadDateTime = DateTime.Now;



            MySINnerFile.Alias      = MyCharacter.CharacterName;
            MySINnerFile.LastChange = MyCharacter.FileLastWriteTime;
            if (MySINnerFile.SiNnerMetaData.Visibility?.UserRights == null)
            {
                MySINnerFile.SiNnerMetaData.Visibility =
                    new SINnerVisibility
                {
                    Id             = Guid.NewGuid(),
                    IsGroupVisible = SINnersOptions.SINnerVisibility.IsGroupVisible,
                    IsPublic       = SINnersOptions.SINnerVisibility.IsPublic,
                    UserRights     = SINnersOptions.SINnerVisibility.UserRights
                };
            }
            if (MySINnerFile.SiNnerMetaData.Visibility.Id == SINnersOptions.SINnerVisibility.Id)
            {
                //make the visibility your own and dont reuse the id from the general options!
                MySINnerFile.SiNnerMetaData.Visibility.Id = Guid.NewGuid();
            }
            foreach (var visnow in SINnersOptions.SINnerVisibility.UserRights)
            {
                if (!MySINnerFile.SiNnerMetaData.Visibility.UserRights.Any(a => a.EMail.ToLowerInvariant() == visnow.EMail.ToLowerInvariant()))
                {
                    MySINnerFile.SiNnerMetaData.Visibility.UserRights.Add(visnow);
                }
            }

            foreach (var ur in MySINnerFile.SiNnerMetaData.Visibility.UserRights)
            {
                if (SINnersOptions.SINnerVisibility.UserRights.Any(a => a.Id == ur.Id))
                {
                    ur.Id = Guid.NewGuid();
                }
            }

            if (!File.Exists(MyCharacter.FileName))
            {
                return(null);
            }

            var tempDir = Path.Combine(Path.GetTempPath(), "SINner", MySINnerFile.Id.Value.ToString());

            if (!Directory.Exists(tempDir))
            {
                Directory.CreateDirectory(tempDir);
            }
            foreach (var file in Directory.GetFiles(tempDir))
            {
                FileInfo fi = new FileInfo(file);
                if (fi.LastWriteTimeUtc < MyCharacter.FileLastWriteTime)
                {
                    File.Delete(file);
                }
            }
            var summary = new frmCharacterRoster.CharacterCache(MyCharacter.FileName);

            MySINnerFile.MyExtendedAttributes.JsonSummary = JsonConvert.SerializeObject(summary);
            MySINnerFile.LastChange = MyCharacter.FileLastWriteTime;
            var tempfile = Path.Combine(tempDir, summary.FileName);

            if (File.Exists(tempfile))
            {
                File.Delete(tempfile);
            }

            MyCharacter.OnSaveCompleted -= Chummer.Plugins.PluginHandler.MyOnSaveUpload;
            MyCharacter.Save();
            MyCharacter.OnSaveCompleted += Chummer.Plugins.PluginHandler.MyOnSaveUpload;


            if (!File.Exists(tempfile))
            {
                File.Copy(MyCharacter.FileName, tempfile);
            }

            ;
            if (File.Exists(zipPath))
            {
                ZipFilePath = zipPath;
                FileInfo fi = new FileInfo(zipPath);
                if (fi.LastWriteTimeUtc < MyCharacter.FileLastWriteTime)
                {
                    File.Delete(zipPath);
                }
            }

            if (!File.Exists(zipPath))
            {
                ZipFile.CreateFromDirectory(tempDir, zipPath);
                ZipFilePath = zipPath;
            }

            return(zipPath);
        }
Example #24
0
        public CharacterExtended(Character character, string fileElement = null)
        {
            MyCharacter = character;
            if (PluginHandler.MyCharExtendedDic.ContainsKey(character.FileName))
            {
                throw new ArgumentException(
                          "CharacterExtended already exists for this char - dont create a new instantce!", nameof(character));
            }

            PluginHandler.MyCharExtendedDic.Add(character.FileName, this);

            _MySINnerFile = new SINner
            {
                MyExtendedAttributes = new SINnerExtended(),
                SiNnerMetaData       = new SINnerMetaData(),
                Language             = GlobalOptions.Language
            };
            if (string.IsNullOrEmpty(fileElement))
            {
                MySINnerFile.SiNnerMetaData = new SINnerMetaData
                {
                    Id         = Guid.NewGuid(),
                    Tags       = new List <Tag>(),
                    Visibility = new SINnerVisibility()
                };
            }
            else
            {
                try
                {
                    MySINnerFile.SiNnerMetaData = JsonConvert.DeserializeObject <SINnerMetaData>(fileElement);
                }
                catch (Exception e)
                {
                    System.Diagnostics.Trace.TraceWarning(e.ToString());
                }
            }

            if (MySINnerFile.SiNnerMetaData.Visibility != null)
            {
                if (MySINnerFile.SiNnerMetaData.Visibility.Id == null)
                {
                    MySINnerFile.SiNnerMetaData.Visibility.Id = Guid.NewGuid();
                }
            }

            if (!string.IsNullOrEmpty(Properties.Settings.Default.SINnerVisibility))
            {
                MySINnerFile.SiNnerMetaData.Visibility =
                    JsonConvert.DeserializeObject <SINnerVisibility>(Properties.Settings.Default.SINnerVisibility);
            }

            if (MySINnerFile.SiNnerMetaData.Visibility?.Id == null)
            {
                MySINnerFile.SiNnerMetaData.Visibility.Id = Guid.NewGuid();
            }

            var cache = new frmCharacterRoster.CharacterCache(character.FileName);

            this.MySINnerFile.LastChange = MyCharacter.FileLastWriteTime;

            if (MySINnerIds.TryGetValue(MyCharacter.Alias, out var singuid))
            {
                MySINnerFile.Id = singuid;
            }
            else
            {
                MySINnerFile.Id = Guid.NewGuid();
                MySINnerIds.Add(MyCharacter.Alias, MySINnerFile.Id.Value);
                MySINnerIds = MySINnerIds; //Save it!
            }
            this.MySINnerFile.MyExtendedAttributes.JsonSummary = JsonConvert.SerializeObject(cache);
        }
        private async Task <ActionResult <SINSearchGroupResult> > GetSearchGroupsInternal(string Groupname, string UsernameOrEmail, string sINnerName, string language)
        {
            ApplicationUser user = null;

            try
            {
                if (!ModelState.IsValid)
                {
                    var errors = ModelState.Select(x => x.Value.Errors)
                                 .Where(y => y.Count > 0)
                                 .ToList();
                    string msg = "ModelState is invalid: ";
                    foreach (var err in errors)
                    {
                        foreach (var singleerr in err)
                        {
                            msg += Environment.NewLine + "\t" + singleerr.ToString();
                        }
                    }

                    return(BadRequest(new HubException(msg)));
                }

                SINSearchGroupResult result = new SINSearchGroupResult();
                var groupfoundseq           = await(from a in _context.SINnerGroups
                                                    where a.Groupname.ToLowerInvariant().Contains(Groupname.ToLowerInvariant()) &&
                                                    (a.Language == language || String.IsNullOrEmpty(language))
                                                    select a.Id).ToListAsync();
                if (!groupfoundseq.Any())
                {
                    return(NotFound(Groupname));
                }

                foreach (var groupid in groupfoundseq)
                {
                    var ssg = await GetSinSearchGroupResultById(groupid);

                    result.SINGroups.Add(ssg);
                }

                if (!String.IsNullOrEmpty(UsernameOrEmail))
                {
                    List <SINner>   byUser     = new List <SINner>();
                    ApplicationUser bynameuser = await _userManager.FindByNameAsync(UsernameOrEmail);

                    if (bynameuser != null)
                    {
                        var usersinners = await SINner.GetSINnersFromUser(bynameuser, _context, true);

                        byUser.AddRange(usersinners);
                    }

                    ApplicationUser byemailuser = await _userManager.FindByEmailAsync(UsernameOrEmail);

                    if ((byemailuser != null) && (byemailuser != bynameuser))
                    {
                        var usersinners = await SINner.GetSINnersFromUser(byemailuser, _context, true);

                        byUser.AddRange(usersinners);
                    }


                    foreach (var sin in byUser)
                    {
                        if (sin.MyGroup != null)
                        {
                            SINnerSearchGroup ssg = null;
                            var foundseq          = (from a in result.SINGroups
                                                     where a.Groupname?.ToLowerInvariant() == sin.MyGroup?.Groupname.ToLowerInvariant()
                                                     select a).ToList();
                            if (foundseq.Any())
                            {
                                ssg = foundseq.FirstOrDefault();
                            }

                            if (ssg == null)
                            {
                                ssg = new SINnerSearchGroup(sin.MyGroup);
                            }
                            ssg.Id = sin.MyGroup?.Id;
                            SINnerSearchGroupMember ssgm = new SINnerSearchGroupMember();
                            ssgm.MySINner = sin;
                            if (byemailuser != null)
                            {
                                ssgm.Username = byemailuser?.UserName;
                            }
                            if (bynameuser != null)
                            {
                                ssgm.Username = bynameuser?.UserName;
                            }
                            ssg.MyMembers.Add(ssgm);
                        }
                    }
                }
                result.SINGroups = RemovePWHashRecursive(result.SINGroups);

                return(Ok(result));
            }
            catch (Exception e)
            {
                try
                {
                    var tc = new Microsoft.ApplicationInsights.TelemetryClient();
                    Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry telemetry = new Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry(e);
                    telemetry.Properties.Add("User", user?.Email);
                    telemetry.Properties.Add("Groupname", Groupname?.ToString());
                    tc.TrackException(telemetry);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.ToString());
                }
                if (e is HubException)
                {
                    return(BadRequest(e));
                }
                HubException hue = new HubException("Exception in GetSearchGroups: " + e.Message, e);
                return(BadRequest(hue));
            }
        }
Example #26
0
 public void SetSINner(SINner sinner)
 {
     _MySINnerFile = sinner;
     _MySINnerFile.DownloadedFromSINnersTime = DateTime.Now;
 }
        public async Task <ActionResult <SINSearchResult> > GetSINnersByAuthorization()
        {
            SINSearchResult ret = new SINSearchResult();

            try
            {
                var user = await _signInManager.UserManager.GetUserAsync(User);

                if (user == null)
                {
                    ret.ErrorText = "Unauthorized";
                    throw new AuthenticationException("User is not authenticated.");
                }
                //get all from visibility
                SINnersList   list      = new SINnersList();
                List <SINner> mySinners = await SINner.GetSINnersFromUser(user, _context, true);

                foreach (var sin in mySinners)
                {
                    SINnerList owndSINner = new SINnerList
                    {
                        SINner = sin
                    };
                    if (sin.MyGroup != null)
                    {
                        //add all members of his group
                        var members = await sin.MyGroup.GetGroupMembers(_context);

                        foreach (var member in members)
                        {
                            if (member.Id == sin.Id)
                            {
                                continue;
                            }
                            if ((member.SINnerMetaData.Visibility.IsGroupVisible == true) ||
                                (member.SINnerMetaData.Visibility.IsPublic)
                                )
                            {
                                member.MyGroup          = sin.MyGroup;
                                member.MyGroup.MyGroups = new List <SINnerGroup>();
                                SINnerList memberlist = new SINnerList();
                                memberlist.SINner = member;
                                owndSINner.SINList.Add(memberlist);
                            }
                        }
                        sin.MyGroup.MyGroups = new List <SINnerGroup>();
                        ;
                    }
                    list.MySINnersList.Add(owndSINner);
                }

                ret.SINLists.Add(list);
                return(Ok(ret));
            }
            catch (Exception e)
            {
                if (e is HubException)
                {
                    return(BadRequest(e));
                }
                HubException hue = new HubException(e.Message, e);
                return(BadRequest(hue));
            }
        }
Example #28
0
        public string PrepareModel()
        {
            string zipPath = Path.Combine(Path.GetTempPath(), "SINner", MySINnerFile.Id + ".chum5z");

            if (PluginHandler.MySINnerLoading != null)
            {
                if (MySINnerIds.ContainsKey(MyCharacter.Alias))
                {
                    MySINnerIds.Remove(MyCharacter.Alias);
                }
            }
            if (MySINnerIds.TryGetValue(MyCharacter.Alias, out var singuid))
            {
                MySINnerFile.Id = singuid;
            }
            else
            {
                if (PluginHandler.MySINnerLoading != null)
                {
                    _MySINnerFile = PluginHandler.MySINnerLoading;
                    MySINnerIds.Add(MyCharacter.Alias, MySINnerFile.Id.Value);
                    return(zipPath);
                }
                else
                {
                    MySINnerFile.Id = Guid.NewGuid();
                }
                MySINnerIds.Add(MyCharacter.Alias, MySINnerFile.Id.Value);
                MySINnerIds = MySINnerIds; //Save it!
            }
            zipPath = Path.Combine(Path.GetTempPath(), "SINner", MySINnerFile.Id.Value + ".chum5z");
            MySINnerFile.UploadDateTime = DateTime.Now;



            MySINnerFile.Alias      = MyCharacter.CharacterName;
            MySINnerFile.LastChange = MyCharacter.FileLastWriteTime;
            if (MySINnerFile.SiNnerMetaData.Visibility?.UserRights == null)
            {
                MySINnerFile.SiNnerMetaData.Visibility =
                    new SINnerVisibility
                {
                    Id             = Guid.NewGuid(),
                    IsGroupVisible = SINnersOptions.SINnerVisibility.IsGroupVisible,
                    IsPublic       = SINnersOptions.SINnerVisibility.IsPublic,
                    UserRights     = SINnersOptions.SINnerVisibility.UserRights
                };
            }
            if (MySINnerFile.SiNnerMetaData.Visibility.Id == SINnersOptions.SINnerVisibility.Id)
            {
                //make the visibility your own and dont reuse the id from the general options!
                MySINnerFile.SiNnerMetaData.Visibility.Id = Guid.NewGuid();
            }
            foreach (var ur in MySINnerFile.SiNnerMetaData.Visibility.UserRights)
            {
                if (SINnersOptions.SINnerVisibility.UserRights.Any(a => a.Id == ur.Id))
                {
                    ur.Id = Guid.NewGuid();
                }
            }

            if (!File.Exists(MyCharacter.FileName))
            {
                return(null);
            }

            var tempDir = Path.Combine(Path.GetTempPath(), "SINner", MySINnerFile.Id.Value.ToString());

            if (!Directory.Exists(tempDir))
            {
                Directory.CreateDirectory(tempDir);
            }
            foreach (var file in Directory.GetFiles(tempDir))
            {
                FileInfo fi = new FileInfo(file);
                if (fi.LastWriteTimeUtc < MyCharacter.FileLastWriteTime)
                {
                    File.Delete(file);
                }
            }

            var summary = new frmCharacterRoster.CharacterCache(MyCharacter.FileName);

            MySINnerFile.JsonSummary = JsonConvert.SerializeObject(summary);
            MySINnerFile.LastChange  = MyCharacter.FileLastWriteTime;
            var tempfile = Path.Combine(tempDir, summary.FileName);

            if (!File.Exists(tempfile))
            {
                File.Copy(MyCharacter.FileName, tempfile);
            }

            ;
            if (File.Exists(zipPath))
            {
                ZipFilePath = zipPath;
                FileInfo fi = new FileInfo(zipPath);
                if (fi.LastWriteTimeUtc < MyCharacter.FileLastWriteTime)
                {
                    File.Delete(zipPath);
                }
            }

            if (!File.Exists(zipPath))
            {
                ZipFile.CreateFromDirectory(tempDir, zipPath);
                ZipFilePath = zipPath;
            }

            return(zipPath);
        }
Example #29
0
 public void SetSINner(SINner sinner)
 {
     MySINnerFile = sinner;
     MySINnerFile.DownloadedFromSINnersTime = DateTime.Now.ToUniversalTime();
 }
Example #30
0
        public CharacterExtended(Character character, string fileElement = null, frmCharacterRoster.CharacterCache myCharacterCache = null)
        {
            MyCharacter      = character;
            MyCharacterCache = myCharacterCache;
            if (!string.IsNullOrEmpty(fileElement))
            {
                try
                {
                    MySINnerFile = JsonConvert.DeserializeObject <SINner>(fileElement);
                }
                catch (Exception e)
                {
                    Log.Error(e);
                }
            }

            if (MySINnerFile == null)
            {
                MySINnerFile = new SINner
                {
                    Language = GlobalOptions.Language
                };

                //MySINnerFile.MyExtendedAttributes = new SINnerExtended(MySINnerFile);
            }
            if (MySINnerFile.SiNnerMetaData == null)
            {
                MySINnerFile.SiNnerMetaData = new SINnerMetaData
                {
                    Id         = Guid.NewGuid(),
                    Tags       = new List <Tag>(),
                    Visibility = new SINners.Models.SINnerVisibility()
                    {
                        IsGroupVisible = true,
                        IsPublic       = true
                    }
                };
            }

            if (!string.IsNullOrEmpty(Properties.Settings.Default.SINnerVisibility))
            {
                MySINnerFile.SiNnerMetaData.Visibility =
                    JsonConvert.DeserializeObject <SINners.Models.SINnerVisibility>(Properties.Settings.Default.SINnerVisibility);
            }

            if (MySINnerFile.SiNnerMetaData.Visibility?.Id == null)
            {
                if (MySINnerFile.SiNnerMetaData.Visibility != null)
                {
                    MySINnerFile.SiNnerMetaData.Visibility.Id = Guid.NewGuid();
                }
            }

            var cache = new frmCharacterRoster.CharacterCache(character.FileName);

            MySINnerFile.LastChange = MyCharacter.FileLastWriteTime;

            if (MySINnerIds.TryGetValue(MyCharacter.FileName, out var singuid))
            {
                MySINnerFile.Id = singuid;
            }
            else
            {
                MySINnerFile.Id = Guid.NewGuid();
                MySINnerIds.Add(MyCharacter.FileName, MySINnerFile.Id.Value);
                MySINnerIds = MySINnerIds; //Save it!
            }
        }