Skip to content

Commit

Permalink
OMKR-1 | Added file upload fetaure and celebration card updated
Browse files Browse the repository at this point in the history
  • Loading branch information
keshavsingh4522 committed Dec 31, 2023
1 parent 20ee419 commit d8c8f89
Show file tree
Hide file tree
Showing 18 changed files with 365 additions and 324 deletions.
369 changes: 64 additions & 305 deletions package-lock.json

Large diffs are not rendered by default.

16 changes: 13 additions & 3 deletions src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,13 @@ import { CelebrationCardComponent } from './components/general/celebration-card/
import { MatCardModule } from '@angular/material/card';
import { CelebrationCardDialogComponent } from './components/general/celebration-card-dialog/celebration-card-dialog.component';
import { MatDialogModule } from '@angular/material/dialog';
import { NgxConfettiModule } from 'angular-confetti';
import { ConfettiComponent } from './components/general/confetti/confetti.component';
import { FileUploadComponent } from './components/general/file/file-upload/file-upload.component';
import { MatInputModule } from '@angular/material/input';
import { MatButtonModule } from '@angular/material/button';
import { ConfirmDialogComponent } from './components/general/dialog/confirm-dialog/confirm-dialog.component';
import { MatSnackBarModule } from '@angular/material/snack-bar';
import { MatProgressBarModule } from '@angular/material/progress-bar';

// AOT compilation support
export function HttpLoaderFactory(http: HttpClient) {
Expand Down Expand Up @@ -65,7 +70,9 @@ export function HttpLoaderFactory(http: HttpClient) {
OtherActivityComponent,
CelebrationCardComponent,
CelebrationCardDialogComponent,
ConfettiComponent
ConfettiComponent,
FileUploadComponent,
ConfirmDialogComponent
],
imports: [
BrowserModule,
Expand All @@ -86,7 +93,10 @@ export function HttpLoaderFactory(http: HttpClient) {
MatIconModule,
MatCardModule,
MatDialogModule,
NgxConfettiModule
MatInputModule,
MatButtonModule,
MatSnackBarModule,
MatProgressBarModule
],
providers: [],
bootstrap: [AppComponent]
Expand Down
4 changes: 3 additions & 1 deletion src/app/components/admin/admin-routing.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { OrganizationComponent } from './organization/organization.component';
import { VisitorComponent } from './visitor/visitor.component';
import { ChatComponent } from './chat/chat.component';
import { MarkdownRendererComponent } from './markdown-renderer/markdown-renderer.component';
import { FileUploadComponent } from '../general/file/file-upload/file-upload.component';

const routes: Routes = [{
path: "", component: AdminComponent, children: [
Expand All @@ -15,7 +16,8 @@ const routes: Routes = [{
{ path: "organization", component: OrganizationComponent },
{ path: "visitor", component: VisitorComponent },
{ path: "chat", component: ChatComponent },
{ path:"markdown-renderer", component: MarkdownRendererComponent }
{ path: "markdown-renderer", component: MarkdownRendererComponent },
{ path: "file", component: FileUploadComponent }
]
}];

Expand Down
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<h1 mat-dialog-title>Confirm Upload</h1>
<div mat-dialog-content>
<p>Are you sure you want to upload this file?</p>
</div>
<div mat-dialog-actions>
<button mat-button [mat-dialog-close]="false">Cancel</button>
<button mat-button color="primary" [mat-dialog-close]="true">Upload</button>
</div>
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';

import { ConfirmDialogComponent } from './confirm-dialog.component';

describe('ConfirmDialogComponent', () => {
let component: ConfirmDialogComponent;
let fixture: ComponentFixture<ConfirmDialogComponent>;

beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ConfirmDialogComponent]
});
fixture = TestBed.createComponent(ConfirmDialogComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});

it('should create', () => {
expect(component).toBeTruthy();
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Component } from '@angular/core';
import { MatDialogRef } from '@angular/material/dialog';

@Component({
selector: 'app-confirm-dialog',
templateUrl: './confirm-dialog.component.html',
styleUrls: ['./confirm-dialog.component.css']
})
export class ConfirmDialogComponent {
constructor(public dialogRef: MatDialogRef<ConfirmDialogComponent>) { }
}
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<div class="file-upload-container">
<mat-form-field class="example-full-width" appearance="fill">
<mat-label>File name</mat-label>
<input matInput placeholder="Enter file name" [(ngModel)]="fileName">
</mat-form-field>

<div class="file-input-wrapper">
<input type="file" #fileInput (change)="onFileSelected($event)" hidden>
<button mat-raised-button (click)="fileInput.click()">Choose file</button>
<span class="file-name">{{ selectedFile?.name || 'No file selected' }}</span>
</div>
</div>
<button mat-raised-button color="primary" (click)="onUpload()">Upload</button>
<br>
<mat-progress-bar *ngIf="uploadInProgress" mode="determinate" [value]="uploadProgress"></mat-progress-bar>
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';

import { FileUploadComponent } from './file-upload.component';

describe('FileUploadComponent', () => {
let component: FileUploadComponent;
let fixture: ComponentFixture<FileUploadComponent>;

beforeEach(() => {
TestBed.configureTestingModule({
declarations: [FileUploadComponent]
});
fixture = TestBed.createComponent(FileUploadComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});

it('should create', () => {
expect(component).toBeTruthy();
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import { Component } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { ConfirmDialogComponent } from '../../dialog/confirm-dialog/confirm-dialog.component';
import { FileService } from 'src/app/services/general/file/file.service';
import { MatSnackBar } from '@angular/material/snack-bar';
import { HttpEventType } from '@angular/common/http';

@Component({
selector: 'app-file-upload',
templateUrl: './file-upload.component.html',
styleUrls: ['./file-upload.component.css']
})
export class FileUploadComponent {
_fileName = '';
selectedFile: File | null = null;
uploadProgress = 0;
uploadInProgress = false;

constructor(public dialog: MatDialog, private fileService: FileService,
private snackBar: MatSnackBar) {

}
onUpload() {
if (this.selectedFile) {
const dialogRef = this.dialog.open(ConfirmDialogComponent);

dialogRef.afterClosed().subscribe(result => {
if (result) {
console.log('Confirmed upload:', this.selectedFile);

// Set upload in progress and reset progress value
this.uploadInProgress = true;
this.uploadProgress = 4;

if (this.selectedFile) {
this.fileService.uploadFile(this.selectedFile, this._fileName).subscribe(event => {

if (event.type === HttpEventType.UploadProgress) {
// Calculate and update the upload progress
this.uploadProgress = event.total ? (event.loaded / event.total) * 100 : 0;
} else if (event.type === HttpEventType.Response) {
// Handle the response from the server for a successful upload
console.log('Upload successful', event.body);

// Reset the progress bar and indicate that upload is complete
this.uploadInProgress = false;
this.uploadProgress = 0;

// Display a success message
this.snackBar.open('File uploaded successfully!', 'Close', {
duration: 5000,
horizontalPosition: 'center',
verticalPosition: 'bottom',
});
}
}, error => {
console.error('Upload failed', error);

// Reset the progress bar and indicate that upload is complete
this.uploadInProgress = false;
this.uploadProgress = 0;

// Display an error message
this.snackBar.open('Failed to upload file!', 'Close', {
duration: 5000,
horizontalPosition: 'center',
verticalPosition: 'bottom',
});
});
}
}
});
}
}

onFileSelected(event: Event): void {
const input = event.target as HTMLInputElement;
if (input.files && input.files.length) {
this.selectedFile = input.files[0];
this.fileName = this.selectedFile.name; // Update the filename input if a file is selected
}
}

set fileName(value: string) {
this._fileName = value;
if (this.selectedFile) {
this.selectedFile = new File([this.selectedFile], this._fileName, { type: this.selectedFile.type });
}
}

get fileName(): string {
return this._fileName;
}
}
23 changes: 17 additions & 6 deletions src/app/components/home/home.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@ import { Router } from '@angular/router';
import { PageViewService } from 'src/app/services/PageView/page-view.service';
import { CelebrationCardDialogService } from 'src/app/services/general/celebration/celebration-card-dialog.service';
import { CelebrationCardDialogComponent } from '../general/celebration-card-dialog/celebration-card-dialog.component';
import { FileService } from 'src/app/services/general/file/file.service';

@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit,OnChanges {
export class HomeComponent implements OnInit, OnChanges {

pageUrl = '';
currentEvent: unknown = null;
Expand All @@ -20,7 +21,8 @@ export class HomeComponent implements OnInit,OnChanges {
*
*/
constructor(private renderer2: Renderer2, private pageViewService: PageViewService, private router: Router,
private celebrationDialogService: CelebrationCardDialogService, private dialog: MatDialog) {
private celebrationDialogService: CelebrationCardDialogService, private dialog: MatDialog,
private fileService: FileService) {

}
ngOnChanges(changes: SimpleChanges): void {
Expand All @@ -47,10 +49,19 @@ export class HomeComponent implements OnInit,OnChanges {

this.celebrationDialogService.getEventForCurrentDate().subscribe(event => {
if (event) {
console.log('opening dialog');
this.dialog.open(CelebrationCardDialogComponent, {
data: event,
width: '400px'

console.log('Retrieving file URL');
this.fileService.getUrl2(event.imageUrl).subscribe(fileUrl => {
// Now you have the additional URL (fileUrl), you can modify the event object or pass it separately
console.log('Opening dialog with file URL');
event.imageUrl = fileUrl;
this.dialog.open(CelebrationCardDialogComponent, {
data: event, // Pass the additional URL as part of the data
width: '400px'
});
}, fileServiceError => {
console.error('Error retrieving file URL:', fileServiceError);
// Handle errors from file service here
});
}
}, error => {
Expand Down
14 changes: 6 additions & 8 deletions src/app/models/admin/navbar/menu.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,11 @@ export const menu: NavItem[] = [
{
displayName: 'Markdown Renderer',
iconName: 'text_format',
route: 'markdown-renderer',
// children: [
// {
// displayName: 'Account Info',
// iconName: 'account_box',
// route: '/admin/organization'
// }
// ]
route: 'markdown-renderer'
},
{
displayName: 'Files',
iconName: 'cloud_upload',
route: 'file'
}
];
12 changes: 12 additions & 0 deletions src/app/models/general/file-details.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
export interface FileDetails {
name: string;
extension: string;
url: string;
key: string;
size: string;
mimeType: string;
description: string;
category: string;
subCategory: string;
tags: string;
}
16 changes: 16 additions & 0 deletions src/app/services/general/file/file.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';

import { FileService } from './file.service';

describe('FileService', () => {
let service: FileService;

beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(FileService);
});

it('should be created', () => {
expect(service).toBeTruthy();
});
});
59 changes: 59 additions & 0 deletions src/app/services/general/file/file.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { HttpClient, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, switchMap } from 'rxjs';
import { environment } from 'src/environments/environment';

@Injectable({
providedIn: 'root'
})
export class FileService {

private apiUrl = ``;
private url = ``;

constructor(private http: HttpClient) { }

getUrl(fileName: string): Observable<string> {

this.apiUrl = `${environment.awsUserApiBaseUrl}${environment.fileApiEndpoints.getUrl}`;
this.apiUrl = this.apiUrl.replace('{key}', fileName);
console.log('get file Url endpoint: ' + this.apiUrl);
return this.http.get<string>(this.apiUrl, { responseType: 'text' as 'json' });
}

getUrl2(url: string): Observable<string> {
console.log('get file Url endpoint: ' + url);
return this.http.get<string>(url, { responseType: 'text' as 'json' });
}


generateUrl(fileName: string): Observable<string> {
const apiUrl = `${environment.awsUserApiBaseUrl}${environment.fileApiEndpoints.generateUrl}`;
const urlWithFileName = apiUrl.replace('{key}', fileName);
console.log('generate file Url endpoint: ' + urlWithFileName);
return this.http.get<string>(urlWithFileName, { responseType: 'text' as 'json' });
}

uploadFile(file: File, fileName: string): Observable<any> {
if (!fileName) {
fileName = file.name;
}

// Use switchMap to use the URL from generateUrl to make the PUT request
return this.generateUrl(fileName).pipe(
switchMap((url: string) => {
console.log('generatedUrl: ' + url);

const req = new HttpRequest('PUT', url, file, {
reportProgress: true, // Enable progress reporting
responseType: 'json'
});

// Make the PUT request directly with the file in the request body
// Note: Do not set Content-Type header as it is automatically set by the browser
// when passing a File object as the body, which is required for pre-signed S3 URLs
return this.http.request(req);
})
);
}
}
Loading

0 comments on commit d8c8f89

Please sign in to comment.