diff --git a/BlazorMovie/Client/BlazorMovie.Client.csproj b/BlazorMovie/Client/BlazorMovie.Client.csproj index 4279661a..ebbe908b 100644 --- a/BlazorMovie/Client/BlazorMovie.Client.csproj +++ b/BlazorMovie/Client/BlazorMovie.Client.csproj @@ -1,41 +1,34 @@ - - - ESNext - - - - ESNext - - - - net7.0 - enable - enable - service-worker-assets.js - false - false - enable - true - True - 2f0b7cb7-4db2-420e-b6d4-dfd9b437d531 - AnyCPU - preview - - - - - - - - - - - - - - - - - - + + ESNext + + + ESNext + + + net8.0 + enable + enable + service-worker-assets.js + false + false + enable + true + True + 2f0b7cb7-4db2-420e-b6d4-dfd9b437d531 + AnyCPU + preview + + + + + + + + + + + + + + \ No newline at end of file diff --git a/BlazorMovie/Maui/App.xaml b/BlazorMovie/Maui/App.xaml index 9acab757..6057ead5 100644 --- a/BlazorMovie/Maui/App.xaml +++ b/BlazorMovie/Maui/App.xaml @@ -1,4 +1,4 @@ - + - - - net7.0-android;net7.0-ios;net7.0-maccatalyst - $(TargetFrameworks);net7.0-windows10.0.19041.0 - - - Exe - Maui - true - true - enable - false - 2f0b7cb7-4db2-420e-b6d4-dfd9b437d531 - True - True - preview - - - Maui - - - com.companyname.maui - 41307AD0-1D5C-493C-A98D-272C8BA6EA6D - - - 1.0 - 1 - - 14.2 - 14.0 - 24.0 - 10.0.17763.0 - 10.0.17763.0 - 6.5 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + net8.0-android;net8.0-ios;net8.0-maccatalyst + $(TargetFrameworks);net8.0-windows10.0.19041.0 + + + Exe + Maui + true + true + enable + false + 2f0b7cb7-4db2-420e-b6d4-dfd9b437d531 + True + True + preview + + Maui + + com.companyname.maui + 41307AD0-1D5C-493C-A98D-272C8BA6EA6D + + 1.0 + 1 + 14.2 + 14.0 + 24.0 + 10.0.17763.0 + 10.0.17763.0 + 6.5 + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/BlazorMovie/Maui/Platforms/Android/MainActivity.cs b/BlazorMovie/Maui/Platforms/Android/MainActivity.cs index 28cfd840..147cf574 100644 --- a/BlazorMovie/Maui/Platforms/Android/MainActivity.cs +++ b/BlazorMovie/Maui/Platforms/Android/MainActivity.cs @@ -1,5 +1,6 @@ using Android.App; using Android.Content.PM; +using Microsoft.Maui; namespace Maui.Platforms.Android; diff --git a/BlazorMovie/Maui/Platforms/MacCatalyst/AppDelegate.cs b/BlazorMovie/Maui/Platforms/MacCatalyst/AppDelegate.cs index a93c6d41..c8537d9f 100644 --- a/BlazorMovie/Maui/Platforms/MacCatalyst/AppDelegate.cs +++ b/BlazorMovie/Maui/Platforms/MacCatalyst/AppDelegate.cs @@ -1,4 +1,5 @@ using Foundation; +using Microsoft.Maui; namespace Maui; diff --git a/BlazorMovie/Maui/Platforms/Windows/App.xaml b/BlazorMovie/Maui/Platforms/Windows/App.xaml index 97b8ab10..1db5104f 100644 --- a/BlazorMovie/Maui/Platforms/Windows/App.xaml +++ b/BlazorMovie/Maui/Platforms/Windows/App.xaml @@ -1,4 +1,4 @@ - - - - net7.0 - enable - enable - 2f0b7cb7-4db2-420e-b6d4-dfd9b437d531 - true - True - 5.0 - 5.0.0.* - false - preview - - - - - - - - - - - - - - - - + + net8.0 + enable + enable + 2f0b7cb7-4db2-420e-b6d4-dfd9b437d531 + true + True + 5.0 + 5.0.0.* + false + preview + + + + + + + + + + + \ No newline at end of file diff --git a/BlazorMovie/MovieClient/Pages/AdminAccountManagement.razor.cs b/BlazorMovie/MovieClient/Pages/AdminAccountManagement.razor.cs index f0a7b632..64ab9bce 100644 --- a/BlazorMovie/MovieClient/Pages/AdminAccountManagement.razor.cs +++ b/BlazorMovie/MovieClient/Pages/AdminAccountManagement.razor.cs @@ -21,14 +21,14 @@ public partial class AdminAccountManagement /// /// It's an async function that calls an API to get a list of accounts, then sorts them by name /// - private async Task NameSortParm() - { - index = 0; - sort = sort == "name" ? "nameDesc" : "name"; - accs = (await _httpClient.GetFromJsonAsync>($"Admin/AccountManagement/ /{sort}/{index}"))!; - isSearch = false; - searchString = string.Empty; - } + //private async Task NameSortParm() + //{ + // index = 0; + // sort = sort == "name" ? "nameDesc" : "name"; + // accs = (await _httpClient.GetFromJsonAsync>($"Admin/AccountManagement/ /{sort}/{index}"))!; + // isSearch = false; + // searchString = string.Empty; + //} /// /// It's an async function that gets a list of AccountManagementModel objects from a web api, and diff --git a/BlazorMovie/MovieClient/Pages/EditMovieAdmin.razor b/BlazorMovie/MovieClient/Pages/EditMovieAdmin.razor index 7ac505e1..012fdad2 100644 --- a/BlazorMovie/MovieClient/Pages/EditMovieAdmin.razor +++ b/BlazorMovie/MovieClient/Pages/EditMovieAdmin.razor @@ -128,7 +128,7 @@ Upload Movie File @@ -138,7 +138,7 @@ Upload Picture File diff --git a/BlazorMovie/MovieClient/Pages/EditMovieStudio.razor b/BlazorMovie/MovieClient/Pages/EditMovieStudio.razor index fa9fb2d8..e1940a82 100644 --- a/BlazorMovie/MovieClient/Pages/EditMovieStudio.razor +++ b/BlazorMovie/MovieClient/Pages/EditMovieStudio.razor @@ -115,7 +115,7 @@ Upload Movie File @@ -125,7 +125,7 @@ Upload Picture File diff --git a/BlazorMovie/MovieClient/Pages/EditMovieStudio.razor.cs b/BlazorMovie/MovieClient/Pages/EditMovieStudio.razor.cs index 2958758c..9c0ce1bc 100644 --- a/BlazorMovie/MovieClient/Pages/EditMovieStudio.razor.cs +++ b/BlazorMovie/MovieClient/Pages/EditMovieStudio.razor.cs @@ -31,7 +31,7 @@ public partial class EditMovieStudio /// protected override async Task OnInitializedAsync() { - movie = await _httpClient.GetFromJsonAsync($"Studio/EditMovie/{Id}"); + movie = await _httpClient.GetFromJsonAsync($"Studio/EditMovie/{Id}") ?? new(); } /// diff --git a/BlazorMovie/MovieClient/Pages/Home.razor.cs b/BlazorMovie/MovieClient/Pages/Home.razor.cs index 0f0b8993..e4fcb74c 100644 --- a/BlazorMovie/MovieClient/Pages/Home.razor.cs +++ b/BlazorMovie/MovieClient/Pages/Home.razor.cs @@ -18,12 +18,12 @@ protected override async Task OnInitializedAsync() { Task? movieTask = Task.Run(async () => { - movies = await _httpClient.GetFromJsonAsync>("user/Trending"); + movies = await _httpClient.GetFromJsonAsync>("user/Trending") ?? new(); }); char[] tokena = { }; Task? tokenaTask = Task.Run(async () => { - tokena = await _httpClient.GetFromJsonAsync("User/GetToken"); + tokena = await _httpClient.GetFromJsonAsync("User/GetToken") ?? []; }); await Task.WhenAll(movieTask, tokenaTask); string token = new(tokena); diff --git a/BlazorMovie/MovieClient/Pages/MovieAdmin.razor.cs b/BlazorMovie/MovieClient/Pages/MovieAdmin.razor.cs index 4ff30dfa..c42c6dc7 100644 --- a/BlazorMovie/MovieClient/Pages/MovieAdmin.razor.cs +++ b/BlazorMovie/MovieClient/Pages/MovieAdmin.razor.cs @@ -6,7 +6,7 @@ namespace MovieClient.Pages; public partial class MovieAdmin { /* Initializing the movies variable to an empty list. */ - private List? movies = new(); + private List? movies = new(); /* Used to keep track of the page number. */ private int index = 0; /* Initializing the searchString variable to an empty string. */ @@ -88,15 +88,15 @@ private async Task LoadMore() index++; if (isSearch) { - movies.AddRange(await _httpClient.GetFromJsonAsync>($"admin/Movie/{searchString}//{index}")); + movies?.AddRange(await _httpClient.GetFromJsonAsync>($"admin/Movie/{searchString}//{index}")); } else if (sort != null) { - movies.AddRange(await _httpClient.GetFromJsonAsync>($"admin/Movie/ /{sort}/{index}")); + movies?.AddRange(await _httpClient.GetFromJsonAsync>($"admin/Movie/ /{sort}/{index}")); } else { - movies.AddRange(await _httpClient.GetFromJsonAsync>($"admin/Movie/ / /{index}")); + movies?.AddRange(await _httpClient.GetFromJsonAsync>($"admin/Movie/ / /{index}")); } } } diff --git a/BlazorMovie/MovieClient/Pages/MovieCustomer.razor b/BlazorMovie/MovieClient/Pages/MovieCustomer.razor index 9745a47c..23beca03 100644 --- a/BlazorMovie/MovieClient/Pages/MovieCustomer.razor +++ b/BlazorMovie/MovieClient/Pages/MovieCustomer.razor @@ -42,7 +42,7 @@ {
- @if(DicImageLink.ContainsKey(item.MovieId)) + @if(DicImageLink.ContainsKey(item?.MovieId)) { Unsplash } diff --git a/BlazorMovie/MovieClient/Pages/MovieCustomer.razor.cs b/BlazorMovie/MovieClient/Pages/MovieCustomer.razor.cs index 5d2d1c0f..7c2d36ea 100644 --- a/BlazorMovie/MovieClient/Pages/MovieCustomer.razor.cs +++ b/BlazorMovie/MovieClient/Pages/MovieCustomer.razor.cs @@ -25,7 +25,7 @@ private async Task NameSortParm() { index = 0; sort = sort == "name" ? "nameDesc" : "name"; - movies = await _httpClient.GetFromJsonAsync>($"Customer/Movie/ /{sort}/{index}"); + movies = await _httpClient.GetFromJsonAsync>($"Customer/Movie/ /{sort}/{index}") ?? new(); isSearch = false; searchString = string.Empty; await LoadImg(); @@ -38,7 +38,7 @@ private async Task DateSortParm() { index = 0; sort = sort == "date" ? "dateDesc" : "date"; - movies = await _httpClient.GetFromJsonAsync>($"Customer/Movie/ /{sort}/{index}"); + movies = await _httpClient.GetFromJsonAsync>($"Customer/Movie/ /{sort}/{index}") ?? new(); isSearch = false; searchString = string.Empty; await LoadImg(); @@ -51,7 +51,7 @@ private async Task GenreSortParm() { index = 0; sort = sort == "genre" ? "genreDesc" : "genre"; - movies = await _httpClient.GetFromJsonAsync>($"Customer/Movie/ /{sort}/{index}"); + movies = await _httpClient.GetFromJsonAsync>($"Customer/Movie/ /{sort}/{index}") ?? new(); isSearch = false; searchString = string.Empty; await LoadImg(); @@ -65,7 +65,7 @@ protected override async Task OnInitializedAsync() { Task? moviesTask = Task.Run(async () => { - movies = await _httpClient.GetFromJsonAsync>($"Customer/Movie/ / /{index}"); + movies = await _httpClient.GetFromJsonAsync>($"Customer/Movie/ / /{index}") ?? new(); }); char[] tokena = { }; Task? tokenaTask = Task.Run(async () => @@ -86,18 +86,14 @@ private Task LoadImg() { _ = Parallel.ForEach(movies, async item => { - try - { - if (!DicImageLink.ContainsKey(item.MovieId)) - { - string ImageLink = await new FirebaseStorage("movie2-e3c7b.appspot.com", new FirebaseStorageOptions { AuthTokenAsyncFactory = async () => await Task.FromResult(await Task.FromResult(token)), ThrowOnCancel = true }).Child(item.StudioId).Child(item.MovieId).Child("Image").GetDownloadUrlAsync(); - DicImageLink.Add(item.MovieId, ImageLink); - StateHasChanged(); - } - } - catch + + if (!DicImageLink.ContainsKey(item.MovieId)) { + string ImageLink = await new FirebaseStorage("movie2-e3c7b.appspot.com", new FirebaseStorageOptions { AuthTokenAsyncFactory = async () => await Task.FromResult(await Task.FromResult(token)), ThrowOnCancel = true }).Child(item.StudioId).Child(item.MovieId).Child("Image").GetDownloadUrlAsync(); + DicImageLink.Add(item.MovieId, ImageLink); + StateHasChanged(); } + }); return Task.CompletedTask; } @@ -110,12 +106,12 @@ private async Task Search() index = 0; if (!string.IsNullOrWhiteSpace(searchString)) { - movies = await _httpClient.GetFromJsonAsync>($"Customer/Movie/{searchString}/ /{index}"); + movies = await _httpClient.GetFromJsonAsync>($"Customer/Movie/{searchString}/ /{index}") ?? new(); isSearch = true; } else { - movies = await _httpClient.GetFromJsonAsync>($"Customer/Movie/ / /{index}"); + movies = await _httpClient.GetFromJsonAsync>($"Customer/Movie/ / /{index}") ?? new(); isSearch = false; } @@ -131,15 +127,15 @@ private async Task LoadMore() index++; if (isSearch) { - movies.AddRange(await _httpClient.GetFromJsonAsync>($"Customer/Movie/{searchString}//{index}")); + movies.AddRange(await _httpClient.GetFromJsonAsync>($"Customer/Movie/{searchString}//{index}") ?? new()); } else if (sort != null) { - movies.AddRange(await _httpClient.GetFromJsonAsync>($"Customer/Movie/ /{sort}/{index}")); + movies.AddRange(await _httpClient.GetFromJsonAsync>($"Customer/Movie/ /{sort}/{index}") ?? new()); } else { - movies.AddRange(await _httpClient.GetFromJsonAsync>($"Customer/Movie/ / /{index}")); + movies.AddRange(await _httpClient.GetFromJsonAsync>($"Customer/Movie/ / /{index}") ?? new()); } await LoadImg(); } diff --git a/BlazorMovie/MovieClient/Pages/MovieStudio.razor b/BlazorMovie/MovieClient/Pages/MovieStudio.razor index 91d04cda..dace9745 100644 --- a/BlazorMovie/MovieClient/Pages/MovieStudio.razor +++ b/BlazorMovie/MovieClient/Pages/MovieStudio.razor @@ -50,9 +50,9 @@ else {
- @if(DicImageLink.ContainsKey(item.MovieId)) + @if(DicImageLink.ContainsKey(item?.MovieId)) { - ... + ... } else { diff --git a/BlazorMovie/MovieClient/Pages/MovieStudio.razor.cs b/BlazorMovie/MovieClient/Pages/MovieStudio.razor.cs index c3a2560c..ffda8165 100644 --- a/BlazorMovie/MovieClient/Pages/MovieStudio.razor.cs +++ b/BlazorMovie/MovieClient/Pages/MovieStudio.razor.cs @@ -17,7 +17,7 @@ public partial class MovieStudio /* Used to sort the movies by name, date, or genre. */ private string? sort = null; /* A dictionary that is used to store the image links. */ - private readonly Dictionary DicImageLink = new(); + private readonly Dictionary DicImageLink = new(); /// /// This function is called when the user clicks on the Name column header. It sorts the movies by /// name @@ -26,7 +26,7 @@ private async Task NameSortParm() { index = 0; sort = sort == "name" ? "nameDesc" : "name"; - movies = await _httpClient.GetFromJsonAsync>($"Studio/Index/ /{sort}/{index}"); + movies = await _httpClient.GetFromJsonAsync>($"Studio/Index/ /{sort}/{index}") ?? new(); isSearch = false; searchString = string.Empty; await LoadImg(); @@ -39,7 +39,7 @@ private async Task DateSortParm() { index = 0; sort = sort == "date" ? "dateDesc" : "date"; - movies = await _httpClient.GetFromJsonAsync>($"Studio/Index/ /{sort}/{index}"); + movies = await _httpClient.GetFromJsonAsync>($"Studio/Index/ /{sort}/{index}") ?? new(); isSearch = false; searchString = string.Empty; await LoadImg(); @@ -58,7 +58,7 @@ private async Task GenreSortParm() { index = 0; sort = sort == "genre" ? "genreDesc" : "genre"; - movies = await _httpClient.GetFromJsonAsync>($"Studio/Index/ /{sort}/{index}"); + movies = await _httpClient.GetFromJsonAsync>($"Studio/Index/ /{sort}/{index}") ?? new(); isSearch = false; searchString = string.Empty; await LoadImg(); @@ -71,12 +71,12 @@ protected override async Task OnInitializedAsync() { Task? moviesTask = Task.Run(async () => { - movies = await _httpClient.GetFromJsonAsync>($"Studio/Index/ / /{index}"); + movies = await _httpClient.GetFromJsonAsync>($"Studio/Index/ / /{index}") ?? new(); }); char[] tokena = { }; Task? tokenaTask = Task.Run(async () => { - tokena = await _httpClient.GetFromJsonAsync("User/GetToken"); + tokena = await _httpClient.GetFromJsonAsync("User/GetToken") ?? []; }); await Task.WhenAll(moviesTask, tokenaTask); token = new string(tokena); @@ -92,20 +92,15 @@ private Task LoadImg() { _ = Parallel.ForEach(movies, async item => { - try - { - if (!DicImageLink.ContainsKey(item.MovieId)) - { - string ImageLink = await new FirebaseStorage("movie2-e3c7b.appspot.com", new FirebaseStorageOptions { AuthTokenAsyncFactory = async () => await Task.FromResult(await Task.FromResult(token)), ThrowOnCancel = true }).Child(item.StudioId).Child(item.MovieId).Child("Image").GetDownloadUrlAsync(); - DicImageLink.Add(item.MovieId, ImageLink); - StateHasChanged(); - } - } - catch + if (!DicImageLink.ContainsKey(item.MovieId)) { + string ImageLink = await new FirebaseStorage("movie2-e3c7b.appspot.com", new FirebaseStorageOptions { AuthTokenAsyncFactory = async () => await Task.FromResult(await Task.FromResult(token)), ThrowOnCancel = true }).Child(item.StudioId).Child(item.MovieId).Child("Image").GetDownloadUrlAsync(); + DicImageLink.Add(item.MovieId, ImageLink); + StateHasChanged(); } + }); return Task.CompletedTask; } @@ -118,12 +113,12 @@ private async Task Search() index = 0; if (!string.IsNullOrWhiteSpace(searchString)) { - movies = await _httpClient.GetFromJsonAsync>($"Studio/Index/{searchString}/ /{index}"); + movies = await _httpClient.GetFromJsonAsync>($"Studio/Index/{searchString}/ /{index}") ?? new(); isSearch = true; } else { - movies = await _httpClient.GetFromJsonAsync>($"Studio/Index/ / /{index}"); + movies = await _httpClient.GetFromJsonAsync>($"Studio/Index/ / /{index}") ?? new(); isSearch = false; } @@ -139,15 +134,15 @@ private async Task LoadMore() index++; if (isSearch) { - movies.AddRange(await _httpClient.GetFromJsonAsync>($"Studio/Index/{searchString}//{index}")); + movies.AddRange(await _httpClient.GetFromJsonAsync>($"Studio/Index/{searchString}//{index}") ?? new()); } else if (sort != null) { - movies.AddRange(await _httpClient.GetFromJsonAsync>($"Studio/Index/ /{sort}/{index}")); + movies.AddRange(await _httpClient.GetFromJsonAsync>($"Studio/Index/ /{sort}/{index}") ?? new()); } else { - movies.AddRange(await _httpClient.GetFromJsonAsync>($"Studio/Index/ / /{index}")); + movies.AddRange(await _httpClient.GetFromJsonAsync>($"Studio/Index/ / /{index}") ?? new()); } await LoadImg(); } diff --git a/BlazorMovie/MovieClient/Pages/Profile.razor.cs b/BlazorMovie/MovieClient/Pages/Profile.razor.cs index c08a561c..8be36c11 100644 --- a/BlazorMovie/MovieClient/Pages/Profile.razor.cs +++ b/BlazorMovie/MovieClient/Pages/Profile.razor.cs @@ -19,7 +19,7 @@ private async Task ChangeEmail() HttpResponseMessage? response = await _httpClient.PostAsJsonAsync("User/ChangeEmail", changeEmail); alertService.ShowAlert(response.IsSuccessStatusCode, await response.Content.ReadAsStringAsync()); _accountService.checkAuthentication(); - accountManagementModel = await _httpClient.GetFromJsonAsync("user/Profile"); + accountManagementModel = await _httpClient.GetFromJsonAsync("user/Profile") ?? new(); } /// @@ -39,7 +39,7 @@ private Task ChangePass() /// protected override async Task OnInitializedAsync() { - accountManagementModel = await _httpClient.GetFromJsonAsync("user/Profile"); + accountManagementModel = await _httpClient.GetFromJsonAsync("user/Profile") ?? new(); } /// diff --git a/BlazorMovie/MovieClient/Pages/ReadFeedBack.razor.cs b/BlazorMovie/MovieClient/Pages/ReadFeedBack.razor.cs index b5289c17..bdfba417 100644 --- a/BlazorMovie/MovieClient/Pages/ReadFeedBack.razor.cs +++ b/BlazorMovie/MovieClient/Pages/ReadFeedBack.razor.cs @@ -16,7 +16,12 @@ protected override async Task OnInitializedAsync() { try { - feedbacks.AddRange(await _httpClient.GetFromJsonAsync>($"admin/ReadFeedBack/{index}")); + var newFeedbacks = await _httpClient.GetFromJsonAsync>($"admin/ReadFeedBack/{index}"); + if (newFeedbacks?.Any() is true) + { + feedbacks.AddRange(newFeedbacks); + } + } catch (Exception ex) { @@ -29,8 +34,9 @@ protected override async Task OnInitializedAsync() /// private async Task LoadMore() { + index++; - feedbacks.AddRange(await _httpClient.GetFromJsonAsync>($"admin/ReadFeedBack/{index}")); + await this.OnInitializedAsync(); } } \ No newline at end of file diff --git a/BlazorMovie/MovieClient/Pages/SalaryStudio.razor.cs b/BlazorMovie/MovieClient/Pages/SalaryStudio.razor.cs index 9e9ad146..07e3d967 100644 --- a/BlazorMovie/MovieClient/Pages/SalaryStudio.razor.cs +++ b/BlazorMovie/MovieClient/Pages/SalaryStudio.razor.cs @@ -1,5 +1,6 @@ using MudBlazor; using System.Net.Http.Json; +using System.Net.Mail; namespace MovieClient.Pages; @@ -19,11 +20,11 @@ public partial class SalaryStudio /// /// A boolean value. /// - private bool isMail(string Email) + private bool isMail(string? Email) { try { - System.Net.Mail.MailAddress addr = new(Email); + _ = new MailAddress(Email ?? string.Empty); return true; } catch @@ -50,7 +51,7 @@ private async Task Submit() else { HttpResponseMessage? response = await _httpClient.PostAsJsonAsync("Studio/Salary", new Dictionary() - {{"Email", Email}, {"Cash", Cash.ToString()}}); + {{"Email", Email ?? string.Empty}, {"Cash", Cash.ToString()}}); alertService.ShowAlert(response.IsSuccessStatusCode, await response.Content.ReadAsStringAsync()); } } diff --git a/BlazorMovie/MovieClient/Pages/StatusStudio.razor b/BlazorMovie/MovieClient/Pages/StatusStudio.razor index 5f71a323..a5964cb2 100644 --- a/BlazorMovie/MovieClient/Pages/StatusStudio.razor +++ b/BlazorMovie/MovieClient/Pages/StatusStudio.razor @@ -84,7 +84,7 @@
@try { - foreach (var status in fullStatus) + foreach (var status in fullStatus ?? new()) { double[] data = { Double.Parse(status["Positive"]), Double.Parse(status["Negative"]) }; string[] labels = { "Positive", "Negative" }; diff --git a/BlazorMovie/MovieClient/Pages/StatusStudio.razor.cs b/BlazorMovie/MovieClient/Pages/StatusStudio.razor.cs index 97924392..3a94bfc3 100644 --- a/BlazorMovie/MovieClient/Pages/StatusStudio.razor.cs +++ b/BlazorMovie/MovieClient/Pages/StatusStudio.razor.cs @@ -41,7 +41,7 @@ private void CloseAlert() ///
private async Task Salary() { - content = await (await _httpClient.PostAsJsonAsync($"Studio/SalaryMovie", new List { { Id }, { month.ToString("MM-dd-yyyy") } })).Content.ReadAsStringAsync(); + content = await (await _httpClient.PostAsJsonAsync($"Studio/SalaryMovie", new List { { Id }, { month.ToString("MM-dd-yyyy") } })).Content.ReadAsStringAsync(); showAlert = true; } @@ -51,7 +51,7 @@ private async Task Salary() /// private async Task Check() { - content = await (await _httpClient.PostAsJsonAsync($"Studio/Check", new List { { Id }, { check.ToString("MM-dd-yyyy") } })).Content.ReadAsStringAsync(); + content = await (await _httpClient.PostAsJsonAsync($"Studio/Check", new List { { Id }, { check.ToString("MM-dd-yyyy") } })).Content.ReadAsStringAsync(); showAlert = true; } @@ -95,12 +95,12 @@ private Task Submit() _ = Parallel.ForEach(dateToCheck, async date => { commentStatus = await _httpClient.GetFromJsonAsync>($"Studio/CommentStatus/{Id}/{date:MM-dd-yyyy}"); - List getInfor = await _httpClient.GetFromJsonAsync>($"Studio/PayCheck/{Id}/{date:MM-dd-yyyy}"); + List getInfor = await _httpClient.GetFromJsonAsync>($"Studio/PayCheck/{Id}/{date:MM-dd-yyyy}") ?? new(); Dictionary dic = new() { { "Date", date.ToString() }, - { "Positive", commentStatus[0].ToString() }, - { "Negative", commentStatus[1].ToString() }, + { "Positive", commentStatus?[0].ToString() ?? string.Empty }, + { "Negative", commentStatus?[1].ToString() ?? string.Empty}, { "View", getInfor[0].ToString() }, { "Buy", getInfor[1].ToString() } }; diff --git a/BlazorMovie/Server/BlazorMovie.Server.csproj b/BlazorMovie/Server/BlazorMovie.Server.csproj index 3a393672..c7388119 100644 --- a/BlazorMovie/Server/BlazorMovie.Server.csproj +++ b/BlazorMovie/Server/BlazorMovie.Server.csproj @@ -6,7 +6,7 @@ ESNext - net7.0 + net8.0 enable enable 2f0b7cb7-4db2-420e-b6d4-dfd9b437d531 @@ -17,23 +17,22 @@ - - - + + + - - - - - - - - - + + + + + + + + diff --git a/BlazorMovie/Server/Censor.cs b/BlazorMovie/Server/Censor.cs index 41de1420..3fa14609 100644 --- a/BlazorMovie/Server/Censor.cs +++ b/BlazorMovie/Server/Censor.cs @@ -3,16 +3,16 @@ namespace BlazorMovie.Server; public class Censor { - public IList CensoredWords { get; private set; } = new List(); + public IList CensoredWords { get; private set; } = new List(); /* Reading the csv file and adding the words to the list. */ public Censor() { - StreamReader reader = new(Path.GetFullPath(Path.Combine("wwwroot/Bad Words/base-list-of-bad-words_csv-file_2021_01_18.csv"))); + using StreamReader reader = new(Path.GetFullPath(Path.Combine("wwwroot/Bad Words/base-list-of-bad-words_csv-file_2021_01_18.csv"))); while (!reader.EndOfStream) { - string line = reader.ReadLine(); - string[] values = line.Split(','); + string? line = reader.ReadLine(); + string?[] values = line?.Split(',') ?? []; CensoredWords.Add(values[0]); } } @@ -43,7 +43,7 @@ public Censor() /// /// The censored text. /// - public string CensorText(string text) + public string CensorText(string? text) { if (text == null) { @@ -52,14 +52,18 @@ public string CensorText(string text) string censoredText = text; - foreach (string censoredWord in CensoredWords) + foreach (string? censoredWord in CensoredWords) { - string regularExpression = ToRegexPattern(censoredWord); + string? regularExpression = ToRegexPattern(censoredWord); - censoredText = Regex.Replace(censoredText, regularExpression, StarCensoredMatch, - RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + if (regularExpression != null) + { + censoredText = Regex.Replace(censoredText, regularExpression, StarCensoredMatch, + RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + } } + return censoredText; } /// @@ -85,8 +89,12 @@ private static string StarCensoredMatch(Match m) /// /// A string that is a regex pattern. /// - private string ToRegexPattern(string wildcardSearch) + private string? ToRegexPattern(string? wildcardSearch) { + if (wildcardSearch is null) + { + return wildcardSearch; + } string regexPattern = Regex.Escape(wildcardSearch); regexPattern = regexPattern.Replace(@"\*", ".*?"); diff --git a/BlazorMovie/Server/Controllers/AdminController.cs b/BlazorMovie/Server/Controllers/AdminController.cs index 20b405f6..c5e12e08 100644 --- a/BlazorMovie/Server/Controllers/AdminController.cs +++ b/BlazorMovie/Server/Controllers/AdminController.cs @@ -17,21 +17,12 @@ namespace BlazorMovie.Server.Controllers; [Authorize(Roles = "Admin")] public class AdminController : Controller { - /* Creating a private readonly variable called env. */ - private readonly IWebHostEnvironment env; /* Creating a new instance of the FirestoreDb class. */ private readonly FirestoreDb db; - /* Creating a new instance of the FirebaseAuthClient class. */ - private readonly FirebaseAuthClient client; - /* Creating a private readonly variable called config. */ - private readonly FirebaseAuthConfig config; /* The above code is creating a new instance of the FirebaseAuthClient class. */ public AdminController(IWebHostEnvironment env, FirestoreDb db, FirebaseAuthConfig config) { - this.env = env; this.db = db; - this.config = config; - client = new FirebaseAuthClient(config); } /// @@ -49,7 +40,7 @@ public async Task>> AccountManagement( { try { - List myFoo = new(); + List myFoo = []; Query usersRef = db.Collection("Account"); @@ -137,24 +128,25 @@ public async Task> EditAccount([FromBody] A if (account.Role is "Admin" or "Studio" or "Customer" or "Admin") { - } - else - { - return BadRequest("Don't edit role"); - } - Query collection = db.Collection("Account").WhereEqualTo("Id", account.Id); - QuerySnapshot snapshot = await collection.GetSnapshotAsync(); - Dictionary update = new() + + Query collection = db.Collection("Account").WhereEqualTo("Id", account.Id); + QuerySnapshot snapshot = await collection.GetSnapshotAsync(); + Dictionary update = new() { { "Name", account.Name }, { "Role", account.Role }, { "DateOfBirth", account.DateOfBirth.ToUniversalTime() } }; - _ = Parallel.ForEach(snapshot.Documents, async snapshotDocument => + _ = Parallel.ForEach(snapshot.Documents, async snapshotDocument => + { + _ = await snapshotDocument.Reference.UpdateAsync(update); + }); + return Ok("Success"); + } + else { - _ = await snapshotDocument.Reference.UpdateAsync(update); - }); - return Ok("Success"); + return BadRequest("Don't edit role"); + } } catch (Exception ex) { @@ -173,7 +165,6 @@ public async Task Ban([FromBody] string Id) { try { - string path = Path.GetFullPath(Path.Combine("movie2-e3c7b-firebase-adminsdk-dk3zo-cbfa735233.json")); UserRecordArgs userRecordArgs = new() { Uid = Id, Disabled = true }; _ = await FirebaseAuth.DefaultInstance.UpdateUserAsync(userRecordArgs); return Ok("Success"); @@ -195,7 +186,6 @@ public async Task UnBan([FromBody] string Id) { try { - string path = Path.GetFullPath(Path.Combine("movie2-e3c7b-firebase-adminsdk-dk3zo-cbfa735233.json")); UserRecordArgs userRecordArgs = new() { Uid = Id, Disabled = false }; _ = await FirebaseAuth.DefaultInstance.UpdateUserAsync(userRecordArgs); return Ok("Success"); @@ -246,7 +236,7 @@ public async Task>> Movie(string? sortOrder, strin usersRef = usersRef.OrderByDescending("MovieGenre"); break; } - List myFoo = new(); + List myFoo = []; usersRef = usersRef.Offset(index * 5).Limit(5); QuerySnapshot snapshot = await usersRef.GetSnapshotAsync(); foreach (DocumentSnapshot document in snapshot.Documents) @@ -303,9 +293,10 @@ public async Task EditMoviePost([FromBody] MovieModel movie) Query collection = db.Collection("Movie").WhereEqualTo("MovieId", movie.MovieId); QuerySnapshot snapshot = await collection.GetSnapshotAsync(); movie.PremiereDate = movie.PremiereDate.ToUniversalTime(); - Dictionary dictionary = movie.GetType() + Dictionary dictionary = movie.GetType() .GetProperties(BindingFlags.Instance | BindingFlags.Public) .ToDictionary(prop => prop.Name, prop => prop.GetValue(movie, null)); + _ = Parallel.ForEach(snapshot.Documents, async snapshotDocument => { _ = await snapshotDocument.Reference.UpdateAsync(dictionary); @@ -327,7 +318,7 @@ public async Task EditMoviePost([FromBody] MovieModel movie) /// The MovieUpload view is being returned. /// [HttpGet("MovieUpload/{MovieId}")] - public async Task MovieUpload(string MovieId) + public async Task MovieIdUpload(string MovieId) { Query collection = db.Collection("Movie").WhereEqualTo("MovieId", MovieId); QuerySnapshot snapshot = await collection.GetSnapshotAsync(); @@ -366,8 +357,8 @@ public async Task MovieUpload(string StudioId, string MovieId, IFo { if (ImageFileUp != null) { - List list = new() - { + List list = + [ "image/bmp", "image/gif", "image/jpeg", @@ -375,29 +366,29 @@ public async Task MovieUpload(string StudioId, string MovieId, IFo "image/svg+xml", "image/tiff", "image/webp" - }; + ]; if (list.Contains(ImageFileUp.ContentType)) { using Stream fileStream = ImageFileUp.OpenReadStream(); - { - FirebaseStorageTask task = new FirebaseStorage("movie2-e3c7b.appspot.com", - new FirebaseStorageOptions - { - AuthTokenAsyncFactory = async () => await Task.FromResult(User.FindFirstValue("Token")), - ThrowOnCancel = true, - HttpClientTimeout = TimeSpan.FromHours(2) - }).Child(StudioId).Child(MovieId).Child("Image") - .PutAsync(fileStream); - _ = await task; - fileStream.Close(); - } + FirebaseStorageTask task = new FirebaseStorage("movie2-e3c7b.appspot.com", + new FirebaseStorageOptions + { + AuthTokenAsyncFactory = async () => await Task.FromResult(User.FindFirstValue("Token")), + ThrowOnCancel = true, + HttpClientTimeout = TimeSpan.FromHours(2) + }).Child(StudioId).Child(MovieId).Child("Image") + .PutAsync(fileStream); + _ = await task; + + fileStream.Close(); + } } if (MovieFileUp != null) { - List list = new() - { + List list = + [ "video/x-msvideo", "video/mp4", "video/mpeg", @@ -407,30 +398,30 @@ public async Task MovieUpload(string StudioId, string MovieId, IFo "video/3gpp", "video/3gpp2", "video/x-matroska" - }; + ]; if (list.Contains(MovieFileUp.ContentType)) { using Stream fileStream = MovieFileUp.OpenReadStream(); - { - FirebaseStorageTask task = new FirebaseStorage("movie2-e3c7b.appspot.com", - new FirebaseStorageOptions - { - AuthTokenAsyncFactory = async () => await Task.FromResult(User.FindFirstValue("Token")), - ThrowOnCancel = true, - HttpClientTimeout = TimeSpan.FromHours(2) - }).Child(StudioId).Child(MovieId).Child("Movie") - .PutAsync(fileStream); + FirebaseStorageTask task = new FirebaseStorage("movie2-e3c7b.appspot.com", + new FirebaseStorageOptions + { + AuthTokenAsyncFactory = async () => await Task.FromResult(User.FindFirstValue("Token")), + ThrowOnCancel = true, + HttpClientTimeout = TimeSpan.FromHours(2) + }).Child(StudioId).Child(MovieId).Child("Movie") + .PutAsync(fileStream); - task.Progress.ProgressChanged += (s, e) => - { - }; + task.Progress.ProgressChanged += (s, e) => + { + + }; + + _ = await task; - _ = await task; + fileStream.Close(); - fileStream.Close(); - } } } @@ -464,32 +455,21 @@ public async Task DeleteMovie([FromBody] MovieModel movie) }).Child(movie.StudioId).Child(movie.MovieId).Child("Image") .DeleteAsync(); await delete; - } - catch - { - - - } - - try - { - Task delete = new FirebaseStorage("movie2-e3c7b.appspot.com", - new FirebaseStorageOptions - { - AuthTokenAsyncFactory = async () => await Task.FromResult(User.FindFirstValue("Token")) - }).Child(movie.StudioId).Child(movie.MovieId).Child("Movie") - .DeleteAsync(); + delete = new FirebaseStorage("movie2-e3c7b.appspot.com", + new FirebaseStorageOptions + { + AuthTokenAsyncFactory = async () => await Task.FromResult(User.FindFirstValue("Token")) + }).Child(movie.StudioId).Child(movie.MovieId).Child("Movie") + .DeleteAsync(); await delete; + await snapshotDocument.Reference.DeleteAsync(); } catch { - - - } - _ = await snapshotDocument.Reference.DeleteAsync(); - return Ok("Success"); + return BadRequest("Not success"); + } } - return BadRequest("Not success"); + return Ok("Success"); } /// /// It takes an index, and returns the next 5 feedback messages from the database, ordered by time, @@ -503,7 +483,7 @@ public async Task DeleteMovie([FromBody] MovieModel movie) public async Task>> ReadFeedBack(int index) { index--; - List myFoo = new(); + List myFoo = []; Query usersRef = db.Collection("Feedback"); usersRef = usersRef.OrderByDescending("Time").Offset(index * 5).Limit(5); QuerySnapshot snapshot = await usersRef.GetSnapshotAsync(); diff --git a/BlazorMovie/Server/Controllers/CustomerController.cs b/BlazorMovie/Server/Controllers/CustomerController.cs index b12fb177..da8b5165 100644 --- a/BlazorMovie/Server/Controllers/CustomerController.cs +++ b/BlazorMovie/Server/Controllers/CustomerController.cs @@ -216,7 +216,8 @@ public async Task DoCard([FromBody] List d) } else { - foreach (ValidationError error in result.Errors.DeepAll()) + var error = result.Errors.DeepAll(); + if (error.Any()) { //ModelState.AddModelError(string.Empty, "Attribute: " + error.Attribute); //ModelState.AddModelError(string.Empty, " Code: " + error.Code); @@ -225,7 +226,7 @@ public async Task DoCard([FromBody] List d) //string hostname = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host}"; //return Redirect($"{hostname}/Deposit/{error.Message}"); - return BadRequest(error.Message); + return BadRequest(string.Join(", ", error)); } } @@ -310,7 +311,8 @@ public async Task DoPaypal([FromBody] List d) } else { - foreach (ValidationError error in result.Errors.DeepAll()) + var error = result.Errors.DeepAll(); + if (error.Any()) { //ModelState.AddModelError(string.Empty, "Attribute: " + error.Attribute); //ModelState.AddModelError(string.Empty, " Code: " + error.Code); @@ -318,8 +320,7 @@ public async Task DoPaypal([FromBody] List d) //string hostname = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host}"; //return Redirect($"{hostname}/Deposit/{error.Message}"); - - return BadRequest(error.Message); + return BadRequest(string.Join(", ", error)); } } return Ok(); @@ -335,11 +336,18 @@ public async Task DoPaypal([FromBody] List d) public async Task> VipCheck() { QuerySnapshot vipCheck = await db.Collection("Vip").WhereEqualTo("User", User.FindFirstValue(ClaimTypes.Sid)).GetSnapshotAsync(); - return vipCheck.Documents.Count == 0 + if (vipCheck.Documents[0].GetValue("Time") < DateTime.UtcNow) + { + return vipCheck.Documents.Count == 0 ? (ActionResult)await Task.FromResult("Not Vip".ToCharArray()) - : vipCheck.Documents[0].GetValue("Time") < DateTime.UtcNow - ? (ActionResult)await Task.FromResult("Expires Vip".ToCharArray()) - : (ActionResult)await Task.FromResult(vipCheck.Documents[0].GetValue("Time").ToString().ToCharArray()); + : (ActionResult)await Task.FromResult("Expires Vip".ToCharArray()); + } + else + { + return vipCheck.Documents.Count == 0 + ? (ActionResult)await Task.FromResult("Not Vip".ToCharArray()) + : (ActionResult)await Task.FromResult(vipCheck.Documents[0].GetValue("Time").ToString().ToCharArray()); + } } /// /// If the user chooses to buy a movie, check if the user has enough money, if the user has already @@ -358,7 +366,7 @@ public async Task> VipCheck() public async Task BuyVip([FromBody] VipModel vip) { - CollectionReference collection = db.Collection("Buy"); + //CollectionReference collection = db.Collection("Buy"); if (vip.Choose == 0 && vip.Id != null) { if ((await db.Collection("Account"). @@ -370,7 +378,7 @@ public async Task BuyVip([FromBody] VipModel vip) { return BadRequest("Already buy this movie"); } - Task? buyTask = Task.Run(async () => await db.Collection("Buy").AddAsync(new Dictionary() { { "MovieId", vip.Id }, { "User", User.FindFirstValue(ClaimTypes.Sid) }, { "Time", DateTime.UtcNow } })); + Task? buyTask = Task.Run(async () => await db.Collection("Buy").AddAsync(new Dictionary() { { "MovieId", vip.Id }, { "User", User.FindFirstValue(ClaimTypes.Sid) }, { "Time", DateTime.UtcNow } })); Task? cashTask = Task.Run(async () => await (await db.Collection("Account").WhereEqualTo("Id", User.FindFirstValue(ClaimTypes.Sid)).GetSnapshotAsync()).Documents[0].Reference.UpdateAsync(new Dictionary { { "Wallet", (await db.Collection("Account").WhereEqualTo("Id", User.FindFirstValue(ClaimTypes.Sid)).GetSnapshotAsync()).Documents[0].GetValue("Wallet") - 4.99 } })); Task addMoneyMovie = Task.Run(async () => @@ -410,7 +418,7 @@ public async Task BuyVip([FromBody] VipModel vip) QuerySnapshot vipCheck = await db.Collection("Vip").WhereEqualTo("User", User.FindFirstValue(ClaimTypes.Sid)).GetSnapshotAsync(); if (vipCheck.Documents.Count == 0) { - Task? buyTask = Task.Run(async () => await db.Collection("Vip").AddAsync(new Dictionary() { { "User", User.FindFirstValue(ClaimTypes.Sid) }, { "Time", DateTime.UtcNow.AddMonths(vip.Choose) } })); + Task? buyTask = Task.Run(async () => await db.Collection("Vip").AddAsync(new Dictionary() { { "User", User.FindFirstValue(ClaimTypes.Sid) }, { "Time", DateTime.UtcNow.AddMonths(vip.Choose) } })); Task? cashTask = Task.Run(async () => await (await db.Collection("Account").WhereEqualTo("Id", User.FindFirstValue(ClaimTypes.Sid)).GetSnapshotAsync()). Documents[0].Reference.UpdateAsync(new Dictionary{{"Wallet", (await db.Collection("Account"). WhereEqualTo("Id", User.FindFirstValue(ClaimTypes.Sid)).GetSnapshotAsync()).Documents[0].GetValue("Wallet") - minus} })); @@ -483,17 +491,17 @@ public async Task Viewing([FromBody] string Id) { return BadRequest(); } - DateTime time = new(DateTime.UtcNow.Year, DateTime.UtcNow.Month, timeVip.Day); + DateTime time = new(DateTime.UtcNow.Year, DateTime.UtcNow.Month, timeVip.Day, 0, 0, 0, DateTimeKind.Utc); collectionView = await db.Collection("View").WhereGreaterThanOrEqualTo("Time", time.ToUniversalTime()).WhereLessThan("Time", time.AddMonths(1).ToUniversalTime()).GetSnapshotAsync(); - _ = await db.Collection("View").AddAsync(new Dictionary() { { "Id", Id }, { "Viewer", User.FindFirstValue(ClaimTypes.Sid) }, { "Time", DateTime.UtcNow } }); + _ = await db.Collection("View").AddAsync(new Dictionary() { { "Id", Id }, { "Viewer", User.FindFirstValue(ClaimTypes.Sid) }, { "Time", DateTime.UtcNow } }); List movie = new(); foreach (DocumentSnapshot? item in collectionView.Documents) { movie.Add(item.GetValue("Id")); } - double oldCash = movie.Count == 0 ? 0 : 8 / (movie.Count() * 1.0); - double newCash = 8 / ((movie.Count() * 1.0) + 1.0); + double oldCash = movie.Count == 0 ? 0 : 8 / (movie.Count * 1.0); + double newCash = 8 / ((movie.Count * 1.0) + 1.0); QuerySnapshot? newUP = await db.Collection("Movie").WhereEqualTo("MovieId", Id).GetSnapshotAsync(); double newUPCash = 0; try @@ -646,14 +654,14 @@ public async Task Ac([FromBody] string ac, string Id) { if (ac == "Like") { - Task? Task1 = Task.Run(async () => await db.Collection("CommentAcction").AddAsync(new Dictionary() { { "Action", "Like" }, { "CommentId", Id }, { "User", User.FindFirstValue(ClaimTypes.Sid) } })); + Task? Task1 = Task.Run(async () => await db.Collection("CommentAcction").AddAsync(new Dictionary() { { "Action", "Like" }, { "CommentId", Id }, { "User", User.FindFirstValue(ClaimTypes.Sid) } })); QuerySnapshot? temp = await db.Collection("Comment").WhereEqualTo("Id", Id).GetSnapshotAsync(); Task? Task2 = Task.Run(async () => await temp.Documents[0].Reference.UpdateAsync("Like", temp.Documents[0].ConvertTo().Like + 1)); await Task.WhenAll(Task1, Task2); } if (ac == "DisLike") { - Task? Task1 = Task.Run(async () => await db.Collection("CommentAcction").AddAsync(new Dictionary() { { "Action", "DisLike" }, { "CommentId", Id }, { "User", User.FindFirstValue(ClaimTypes.Sid) } })); + Task? Task1 = Task.Run(async () => await db.Collection("CommentAcction").AddAsync(new Dictionary() { { "Action", "DisLike" }, { "CommentId", Id }, { "User", User.FindFirstValue(ClaimTypes.Sid) } })); QuerySnapshot? temp = await db.Collection("Comment").WhereEqualTo("Id", Id).GetSnapshotAsync(); Task? Task2 = Task.Run(async () => await temp.Documents[0].Reference.UpdateAsync("DisLike", temp.Documents[0].ConvertTo().DisLike + 1)); await Task.WhenAll(Task1, Task2); @@ -678,7 +686,7 @@ public async Task Ac([FromBody] string ac, string Id) { if (ac == "Like") { - Task? Task1 = Task.Run(async () => await item.Reference.UpdateAsync(new Dictionary() { { "Action", "Like" } })); + Task? Task1 = Task.Run(async () => await item.Reference.UpdateAsync(new Dictionary() { { "Action", "Like" } })); QuerySnapshot? temp = await db.Collection("Comment").WhereEqualTo("Id", Id).GetSnapshotAsync(); Task? Task2 = Task.Run(async () => await temp.Documents[0].Reference.UpdateAsync("Like", temp.Documents[0].ConvertTo().Like + 1)); Task? Task3 = Task.Run(async () => await temp.Documents[0].Reference.UpdateAsync("DisLike", temp.Documents[0].ConvertTo().DisLike - 1)); @@ -686,7 +694,7 @@ public async Task Ac([FromBody] string ac, string Id) } if (ac == "DisLike") { - Task? Task1 = Task.Run(async () => await item.Reference.UpdateAsync(new Dictionary() { { "Action", "DisLike" } })); + Task? Task1 = Task.Run(async () => await item.Reference.UpdateAsync(new Dictionary() { { "Action", "DisLike" } })); QuerySnapshot? temp = await db.Collection("Comment").WhereEqualTo("Id", Id).GetSnapshotAsync(); Task? Task2 = Task.Run(async () => await temp.Documents[0].Reference.UpdateAsync("Like", temp.Documents[0].ConvertTo().Like - 1)); Task? Task3 = Task.Run(async () => await temp.Documents[0].Reference.UpdateAsync("DisLike", temp.Documents[0].ConvertTo().DisLike + 1)); diff --git a/BlazorMovie/Server/Controllers/StudioController.cs b/BlazorMovie/Server/Controllers/StudioController.cs index 0a0e094f..4ea4b4f4 100644 --- a/BlazorMovie/Server/Controllers/StudioController.cs +++ b/BlazorMovie/Server/Controllers/StudioController.cs @@ -6,6 +6,7 @@ using Microsoft.AspNetCore.Mvc; using PayoutsSdk.Core; using PayoutsSdk.Payouts; +using System.Globalization; using System.Reflection; using System.Security.Claims; @@ -141,7 +142,7 @@ public async Task EditMovie([FromBody] MovieModel movie) Query collection = db.Collection("Movie").WhereEqualTo("MovieId", movie.MovieId); QuerySnapshot snapshot = await collection.GetSnapshotAsync(); movie.PremiereDate = movie.PremiereDate.ToUniversalTime(); - Dictionary dictionary = movie.GetType() + Dictionary dictionary = movie.GetType() .GetProperties(BindingFlags.Instance | BindingFlags.Public) .ToDictionary(prop => prop.Name, prop => prop.GetValue(movie, null)); @@ -186,19 +187,19 @@ public async Task MovieUpload(string MovieId) /// It takes a movie id and a studio id, and uploads an image and a movie to firebase storage. /// /// The id of the studio that the movie belongs to. - /// The ID of the movie that is being uploaded. + /// The ID of the movie that is being uploaded. /// The file that is being uploaded. /// The file that is being uploaded. /// /// The code is returning a redirect to the hostname. /// - [HttpPost("MovieUpload/{MovieId}/{StudioId}")] + [HttpPost("MovieUpload/{MovieId}")] [RequestSizeLimit(long.MaxValue)] [RequestFormLimits(MultipartBodyLengthLimit = long.MaxValue)] - public async Task MovieUpload(string StudioId, string MovieId, IFormFile ImageFileUp, IFormFile MovieFileUp) + public async Task MovieUpload(string movieId, IFormFile imageFileUp, IFormFile movieFileUp) { - StudioId = User.FindFirstValue(ClaimTypes.Sid); - if (ImageFileUp != null) + string? studioId = User.FindFirstValue(ClaimTypes.Sid); + if (imageFileUp != null) { List list = new() { @@ -210,35 +211,34 @@ public async Task MovieUpload(string StudioId, string MovieId, IFo "image/tiff", "image/webp" }; - if (list.Contains(ImageFileUp.ContentType)) + if (list.Contains(imageFileUp.ContentType)) { - using Stream fileStream = ImageFileUp.OpenReadStream(); - { + using Stream fileStream = imageFileUp.OpenReadStream(); - FirebaseStorageTask task = new FirebaseStorage("movie2-e3c7b.appspot.com", - new FirebaseStorageOptions - { - AuthTokenAsyncFactory = async () => await Task.FromResult(User.FindFirstValue("Token")), - ThrowOnCancel = true, - HttpClientTimeout = TimeSpan.FromHours(2) - }).Child(StudioId).Child(MovieId).Child("Image") - .PutAsync(fileStream); + FirebaseStorageTask task = new FirebaseStorage("movie2-e3c7b.appspot.com", + new FirebaseStorageOptions + { + AuthTokenAsyncFactory = async () => await Task.FromResult(User.FindFirstValue("Token")), + ThrowOnCancel = true, + HttpClientTimeout = TimeSpan.FromHours(2) + }).Child(studioId).Child(movieId).Child("Image") + .PutAsync(fileStream); - task.Progress.ProgressChanged += (s, e) => - { - }; + task.Progress.ProgressChanged += (s, e) => + { - _ = await task; + }; - fileStream.Close(); - } + _ = await task; + + fileStream.Close(); } } - if (MovieFileUp != null) + if (movieFileUp != null) { List list = new() { @@ -253,29 +253,29 @@ public async Task MovieUpload(string StudioId, string MovieId, IFo "video/x-matroska" }; - if (list.Contains(MovieFileUp.ContentType)) + if (list.Contains(movieFileUp.ContentType)) { - using Stream fileStream = MovieFileUp.OpenReadStream(); - { - FirebaseStorageTask task = new FirebaseStorage("movie2-e3c7b.appspot.com", - new FirebaseStorageOptions - { - AuthTokenAsyncFactory = async () => await Task.FromResult(User.FindFirstValue("Token")), - ThrowOnCancel = true, - HttpClientTimeout = TimeSpan.FromHours(2) - }).Child(StudioId).Child(MovieId).Child("Movie") - .PutAsync(fileStream); + using Stream fileStream = movieFileUp.OpenReadStream(); + FirebaseStorageTask task = new FirebaseStorage("movie2-e3c7b.appspot.com", + new FirebaseStorageOptions + { + AuthTokenAsyncFactory = async () => await Task.FromResult(User.FindFirstValue("Token")), + ThrowOnCancel = true, + HttpClientTimeout = TimeSpan.FromHours(2) + }).Child(studioId).Child(movieId).Child("Movie") + .PutAsync(fileStream); - task.Progress.ProgressChanged += (s, e) => - { - }; + task.Progress.ProgressChanged += (s, e) => + { - _ = await task; + }; + + _ = await task; + + fileStream.Close(); - fileStream.Close(); - } } } @@ -338,17 +338,18 @@ public async Task>> Comment(string Id) /// A list of doubles /// [HttpGet("PayCheck/{Id}/{Start}")] - public async Task>> PayCheck(string Id, string Start) + public async Task>> PayCheck(string id, string start) { - DateTime StartDate = DateTime.Parse(Start).AddHours(12).ToUniversalTime(); - DateTime EndDate = StartDate.AddDays(1); + DateTime startDate = DateTime.Parse(start, new CultureInfo("en-US")).AddHours(12).ToUniversalTime(); + + DateTime endDate = startDate.AddDays(1); try { - double viewCount = (await db.Collection("View").WhereGreaterThanOrEqualTo("Time", StartDate).WhereLessThanOrEqualTo("Time", EndDate).GetSnapshotAsync()).Documents.Count; - if (viewCount == 0) + double viewCount = (await db.Collection("View").WhereGreaterThanOrEqualTo("Time", startDate).WhereLessThanOrEqualTo("Time", endDate).GetSnapshotAsync()).Documents.Count; + if (viewCount is 0) { - double buy0 = (await db.Collection("Buy").WhereEqualTo("MovieId", Id).WhereGreaterThanOrEqualTo("Time", StartDate).WhereLessThanOrEqualTo("Time", EndDate).GetSnapshotAsync()).Documents.Count; - double m0 = buy0 * 4.49; + double buy0 = (await db.Collection("Buy").WhereEqualTo("MovieId", id).WhereGreaterThanOrEqualTo("Time", startDate).WhereLessThanOrEqualTo("Time", endDate).GetSnapshotAsync()).Documents.Count; + //double m0 = buy0 * 4.49; List result0 = new() { 0, @@ -356,9 +357,9 @@ public async Task>> PayCheck(string Id, string Start) }; return result0; } - double viewt = (await db.Collection("View").WhereEqualTo("Id", Id).WhereGreaterThanOrEqualTo("Time", StartDate).WhereLessThanOrEqualTo("Time", EndDate).GetSnapshotAsync()).Documents.Count; - double buy = (await db.Collection("Buy").WhereEqualTo("MovieId", Id).WhereGreaterThanOrEqualTo("Time", StartDate).WhereLessThanOrEqualTo("Time", EndDate).GetSnapshotAsync()).Documents.Count; - double vip = (await db.Collection("Vip").WhereGreaterThanOrEqualTo("Time", StartDate).GetSnapshotAsync()).Documents.Count; + double viewt = (await db.Collection("View").WhereEqualTo("Id", id).WhereGreaterThanOrEqualTo("Time", startDate).WhereLessThanOrEqualTo("Time", endDate).GetSnapshotAsync()).Documents.Count; + double buy = (await db.Collection("Buy").WhereEqualTo("MovieId", id).WhereGreaterThanOrEqualTo("Time", startDate).WhereLessThanOrEqualTo("Time", endDate).GetSnapshotAsync()).Documents.Count; + //double vip = (await db.Collection("Vip").WhereGreaterThanOrEqualTo("Time", startDate).GetSnapshotAsync()).Documents.Count; List result = new() { @@ -388,7 +389,7 @@ public async Task>> CommentStatus(string Id, string Start { try { - DateTime StartDate = DateTime.Parse(Start).AddHours(12); + DateTime StartDate = DateTime.Parse(Start, new CultureInfo("en-US")).AddHours(12); DateTime EndDate = StartDate.AddDays(1); @@ -454,13 +455,13 @@ public async Task>> CommentStatus(string Id, string Start public async Task SalaryMovie([FromBody] List ss) { - if (DateTime.Parse(ss[1]).Month > DateTime.UtcNow.Month - 1) + if (DateTime.Parse(ss[1], new CultureInfo("en-US")).Month > DateTime.UtcNow.Month - 1) { return BadRequest("Cant Salary In lower than month now -1"); } try { - ss[1] = DateTime.Parse(ss[1]).ToString("MM yyyy"); + ss[1] = DateTime.Parse(ss[1], new CultureInfo("en-US")).ToString("MM yyyy"); QuerySnapshot? snapshot = await db.Collection("Movie").WhereEqualTo("MovieId", ss[0]).WhereEqualTo("StudioId", User.FindFirstValue(ClaimTypes.Sid)).GetSnapshotAsync(); double cash = snapshot.Documents[0].GetValue(ss[1]); @@ -477,7 +478,7 @@ public async Task SalaryMovie([FromBody] List ss) } catch { - + return BadRequest("Salary Failed"); } return Ok("Done check your Wallet"); @@ -495,7 +496,7 @@ public async Task Check([FromBody] List ss) { try { - ss[1] = DateTime.Parse(ss[1]).ToString("MM yyyy"); + ss[1] = DateTime.Parse(ss[1], new CultureInfo("en-US")).ToString("MM yyyy"); double snapshot = (await db.Collection("Movie").WhereEqualTo("MovieId", ss[0]).WhereEqualTo("StudioId", User.FindFirstValue(ClaimTypes.Sid)).GetSnapshotAsync()).Documents[0].GetValue(ss[1]); return Ok($"Cash for {ss[1]} is {snapshot}"); @@ -561,10 +562,10 @@ public async Task Salary([FromBody] Dictionary dic PayoutsPostRequest request = new(); _ = request.RequestBody(createPayoutRequest); - PayPalHttp.HttpResponse response = await client.Execute(request); + await client.Execute(request); - CreatePayoutResponse result = response.Result(); + //CreatePayoutResponse result = response.Result(); return Ok("Success"); } @@ -606,7 +607,7 @@ public async Task DeleteMovie([FromBody] MovieModel movie) } catch { - + return BadRequest("Not success"); } @@ -622,13 +623,12 @@ public async Task DeleteMovie([FromBody] MovieModel movie) } catch { - + return BadRequest("Not success"); } - _ = await snapshotDocument.Reference.DeleteAsync(); - return Ok("Success"); + _ = await snapshotDocument.Reference.DeleteAsync(); } - return BadRequest("Not success"); + return Ok("Success"); } } diff --git a/BlazorMovie/Server/Controllers/UserController.cs b/BlazorMovie/Server/Controllers/UserController.cs index 17f488e2..876bd51b 100644 --- a/BlazorMovie/Server/Controllers/UserController.cs +++ b/BlazorMovie/Server/Controllers/UserController.cs @@ -17,15 +17,13 @@ public class UserController : Controller private readonly FirestoreDb db; private readonly FirebaseAuthClient client; - private readonly FirebaseAuthConfig config; public UserController(FirestoreDb db, FirebaseAuthConfig config) { this.db = db; client = new FirebaseAuthClient(config); - this.config = config; } - private static UserCredential? userCredential; + private UserCredential? userCredential; /// /// It takes in a user's email and password, checks if the user exists in the database, if the user @@ -57,10 +55,10 @@ public async Task LogIn([FromBody] LogInModel logIn) acc = document.ConvertTo(); } ClaimsIdentity claimsIdentity = new(new[] { - new Claim(ClaimTypes.Email, logIn.Email), - new Claim(ClaimTypes.Sid, user.Uid), - new Claim(ClaimTypes.Name, acc.Name), - new Claim(ClaimTypes.Role, acc.Role), + new Claim(ClaimTypes.Email, logIn.Email?? string.Empty), + new Claim(ClaimTypes.Sid, user.Uid?? string.Empty), + new Claim(ClaimTypes.Name, acc.Name?? string.Empty), + new Claim(ClaimTypes.Role, acc.Role?? string.Empty), new Claim(ClaimTypes.DateOfBirth, acc.DateOfBirth.ToShortDateString()), new Claim("Token", await client.User.GetIdTokenAsync(true)) @@ -96,9 +94,9 @@ public async Task LogOut() public async Task> GetCurrentUser() { AccountManagementModel acc = new(); - if (User.Identity.IsAuthenticated) + if (User.Identity is not null && User.Identity.IsAuthenticated) { - string Id = User.FindFirst(ClaimTypes.Sid).Value; + string? Id = User.FindFirst(ClaimTypes.Sid)?.Value; Query usersRef = db.Collection("Account").WhereEqualTo("Id", Id); QuerySnapshot snapshot = await usersRef.GetSnapshotAsync(); foreach (DocumentSnapshot VARIABLE in snapshot.Documents) @@ -120,25 +118,25 @@ public async Task> GetCurrentUser() [HttpPost("ChangeEmail")] public async Task ChangeEmail([FromBody] ChangeEmailModel changeEmailModel) { - changeEmailModel.Email = changeEmailModel.Email.ToLower(); + changeEmailModel.Email = changeEmailModel.Email?.ToLower(); try { userCredential = - await client.SignInWithEmailAndPasswordAsync(User.FindFirst(ClaimTypes.Email).Value, + await client.SignInWithEmailAndPasswordAsync(User.FindFirst(ClaimTypes.Email)?.Value, changeEmailModel.Password); UserCredential newUserCredentiall = userCredential; newUserCredentiall.AuthCredential = EmailProvider.GetCredential(changeEmailModel.Email, changeEmailModel.Password); _ = await newUserCredentiall.User.LinkWithCredentialAsync(userCredential.AuthCredential); QuerySnapshot snapshot = await db.Collection("Account").WhereEqualTo("Id", userCredential.User.Uid) .GetSnapshotAsync(); - Dictionary update = new() { { "Email", changeEmailModel.Email } }; + Dictionary update = new() { { "Email", changeEmailModel.Email } }; foreach (DocumentSnapshot document in snapshot.Documents) { _ = await document.Reference.UpdateAsync(update); } ClaimsIdentity identity = new(User.Identity); identity.RemoveClaim(identity.FindFirst(ClaimTypes.Email)); - identity.AddClaim(new Claim(ClaimTypes.Email, changeEmailModel.Email)); + identity.AddClaim(new Claim(ClaimTypes.Email, changeEmailModel.Email ?? string.Empty)); await HttpContext.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity)); @@ -177,20 +175,20 @@ public async Task ResetPassword([FromBody] ResetPasswordModel rese /// [Authorize] [HttpGet("Profile")] - public async Task> Profile() + public Task> Profile() { - AccountManagementModel acc = new(); - if (User.Identity.IsAuthenticated) - { - string Id = User.FindFirst(ClaimTypes.Sid).Value; - Query usersRef = db.Collection("Account").WhereEqualTo("Id", Id); - QuerySnapshot snapshot = await usersRef.GetSnapshotAsync(); - foreach (DocumentSnapshot VARIABLE in snapshot.Documents) - { - acc = VARIABLE.ConvertTo(); - } - } - return await Task.FromResult(acc); + //AccountManagementModel acc = new(); + //if (User.Identity is not null && User.Identity.IsAuthenticated) + //{ + // string? Id = User.FindFirst(ClaimTypes.Sid)?.Value; + // Query usersRef = db.Collection("Account").WhereEqualTo("Id", Id); + // QuerySnapshot snapshot = await usersRef.GetSnapshotAsync(); + // foreach (DocumentSnapshot VARIABLE in snapshot.Documents) + // { + // acc = VARIABLE.ConvertTo(); + // } + //} + return GetCurrentUser(); } /// /// It takes in a model, queries the database for the user's account, updates the account with the @@ -208,7 +206,7 @@ public async Task EditProfile([FromBody] AccountManagementModel ac { QuerySnapshot snapshot = await db.Collection("Account") .WhereEqualTo("Id", User.FindFirstValue(ClaimTypes.Sid)).GetSnapshotAsync(); - Dictionary update = new() + Dictionary update = new() { { "Name", accountManagementModel.Name }, { "DateOfBirth", accountManagementModel.DateOfBirth.AddDays(1).ToUniversalTime() } @@ -239,55 +237,56 @@ public async Task SignUp([FromBody] SignUpModel signUpModel) if (signUpModel.Role is "Customer" or "Studio") { - } - else - { - return BadRequest("Check role"); - } - if (signUpModel.ConfirmPassword != signUpModel.Password) - { - return BadRequest("Password and Confirm Password are different"); - } - signUpModel.Email = signUpModel.Email!.ToLower(); - try - { - try + + if (signUpModel.ConfirmPassword != signUpModel.Password) { - userCredential = - await client.CreateUserWithEmailAndPasswordAsync(signUpModel.Email, signUpModel.Password, signUpModel.Name); + return BadRequest("Password and Confirm Password are different"); } - catch (FirebaseAuthException ex) + signUpModel.Email = signUpModel.Email!.ToLower(); + try { + try + { + userCredential = + await client.CreateUserWithEmailAndPasswordAsync(signUpModel.Email, signUpModel.Password, signUpModel.Name); + } + catch (FirebaseAuthException ex) + { - return BadRequest(ex.Reason.ToString()); - } - User user = userCredential.User; - CollectionReference docRef = db.Collection("Account"); - AccountManagementModel account = new() - { - DateOfBirth = signUpModel.DateOfBirth.AddDays(1).ToUniversalTime(), - Email = signUpModel.Email, - Id = user.Uid, - Name = signUpModel.Name, - Role = signUpModel.Role, - Wallet = 0.0 - }; - _ = await docRef.AddAsync(account); - ClaimsIdentity claimsIdentity = new(new[] { + return BadRequest(ex.Reason.ToString()); + } + User user = userCredential.User; + CollectionReference docRef = db.Collection("Account"); + AccountManagementModel account = new() + { + DateOfBirth = signUpModel.DateOfBirth.AddDays(1).ToUniversalTime(), + Email = signUpModel.Email, + Id = user.Uid, + Name = signUpModel.Name, + Role = signUpModel.Role, + Wallet = 0.0 + }; + _ = await docRef.AddAsync(account); + ClaimsIdentity claimsIdentity = new(new[] { new Claim(ClaimTypes.Email, account.Email), new Claim(ClaimTypes.Sid, user.Uid), - new Claim(ClaimTypes.Name, account.Name), + new Claim(ClaimTypes.Name, account.Name ?? string.Empty), new Claim(ClaimTypes.Role, account.Role), new Claim(ClaimTypes.DateOfBirth, account.DateOfBirth.ToString()), new Claim("Token", await user.GetIdTokenAsync()) }, "serverAuth"); - ClaimsPrincipal claimsPrincipal = new(claimsIdentity); - await HttpContext.SignInAsync(claimsPrincipal); - return Ok(); + ClaimsPrincipal claimsPrincipal = new(claimsIdentity); + await HttpContext.SignInAsync(claimsPrincipal); + return Ok(); + } + catch (Exception ex) + { + return BadRequest(ex.Message); + } } - catch (Exception ex) + else { - return BadRequest(ex.Message); + return BadRequest("Check role"); } } @@ -300,11 +299,11 @@ public async Task SignUp([FromBody] SignUpModel signUpModel) [HttpGet("GetToken")] public async Task> GetToken() { - if (User.Identity.IsAuthenticated) + if (User.Identity is not null && User.Identity.IsAuthenticated) { - string token = User.FindFirstValue("Token"); - char[] ch = new char[token.Length]; - for (int i = 0; i < token.Length; i++) + string? token = User.FindFirstValue("Token"); + char[] ch = new char[token?.Length ?? 0]; + for (int i = 0; i < token?.Length; i++) { ch[i] = token[i]; } @@ -383,16 +382,8 @@ public async Task>> Trending() { for (int i = 0; i <= 10; i++) { - try - { movies.Add((await db.Collection("Movie").WhereEqualTo("MovieId", view.ElementAt(i).Key).GetSnapshotAsync()).Documents[0].ConvertTo()); - } - catch - { - - - } } } else @@ -400,16 +391,7 @@ public async Task>> Trending() foreach (KeyValuePair item in view) { - try - { - movies.Add((await db.Collection("Movie").WhereEqualTo("MovieId", item.Key).GetSnapshotAsync()).Documents[0].ConvertTo()); - } - catch - { - - - - } + movies.Add((await db.Collection("Movie").WhereEqualTo("MovieId", item.Key).GetSnapshotAsync()).Documents[0].ConvertTo()); } } return await Task.FromResult(movies); diff --git a/BlazorMovie/Server/MLModel.consumption.cs b/BlazorMovie/Server/MLModel.consumption.cs index d1ee9a72..ebc52911 100644 --- a/BlazorMovie/Server/MLModel.consumption.cs +++ b/BlazorMovie/Server/MLModel.consumption.cs @@ -17,11 +17,11 @@ public class ModelInput { [LoadColumn(0)] [ColumnName(@"review")] - public string Review { get; set; } + public string? Review { get; set; } [LoadColumn(1)] [ColumnName(@"sentiment")] - public string Sentiment { get; set; } + public string? Sentiment { get; set; } } @@ -34,19 +34,19 @@ public class ModelInput public class ModelOutput { [ColumnName(@"review")] - public float[] Review { get; set; } + public float[]? Review { get; set; } [ColumnName(@"sentiment")] public uint Sentiment { get; set; } [ColumnName(@"Features")] - public float[] Features { get; set; } + public float[]? Features { get; set; } [ColumnName(@"PredictedLabel")] - public string PredictedLabel { get; set; } + public string? PredictedLabel { get; set; } [ColumnName(@"Score")] - public float[] Score { get; set; } + public float[]? Score { get; set; } } diff --git a/BlazorMovie/Shared/BlazorMovie.Shared.csproj b/BlazorMovie/Shared/BlazorMovie.Shared.csproj index c35ea9b6..0950464b 100644 --- a/BlazorMovie/Shared/BlazorMovie.Shared.csproj +++ b/BlazorMovie/Shared/BlazorMovie.Shared.csproj @@ -1,39 +1,34 @@ - - - net7.0 - enable - enable - true - True - 2f0b7cb7-4db2-420e-b6d4-dfd9b437d531 - preview - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + net8.0 + enable + enable + true + True + 2f0b7cb7-4db2-420e-b6d4-dfd9b437d531 + preview + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file