Skip to content

Commit

Permalink
Fix Attachment Content Type ~
Browse files Browse the repository at this point in the history
  • Loading branch information
bifeldy committed Mar 2, 2024
1 parent 40accfe commit caaabf6
Show file tree
Hide file tree
Showing 15 changed files with 80 additions and 64 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ export class AttachmentController {
const tempAttachment = this.tempAttachmentRepo.new();
tempAttachment.name = file.id;
tempAttachment.orig = file.originalName;
tempAttachment.ext = file.originalName.split('.').pop().toLowerCase();
tempAttachment.ext = file.originalName.includes('.') && !file.originalName.endsWith('.') ? file.originalName.split('.').pop().toLowerCase() : null;
tempAttachment.size = file.size;
tempAttachment.mime = file.metadata.mimeType;
tempAttachment.user_ = user;
Expand Down Expand Up @@ -274,20 +274,20 @@ export class AttachmentController {
resSaveAttachment.aws_s3,
user,
expiredSeconds,
resSaveAttachment.orig,
resSaveAttachment.orig || `${resSaveAttachment.name}${resSaveAttachment.ext ? `.${resSaveAttachment.ext}` : ''}`,
resSaveAttachment.mime
);
res.redirect(301, ddl.toString());
} else {
const files = readdirSync(`${environment.uploadFolder}`, { withFileTypes: true });
const fIdx = files.findIndex(f => f.name === attachment.name || f.name === `${attachment.name}.${attachment.ext}`);
const fIdx = files.findIndex(f => f.name === attachment.name || f.name === `${attachment.name}${attachment.ext ? `.${attachment.ext}` : ''}`);
if (fIdx < 0) {
throw new Error('Lampiran Tidak Ditemukan!');
}
res.setHeader('content-type', attachment.mime);
res.download(
`${environment.uploadFolder}/${files[fIdx].name}`,
`${attachment.orig || attachment.name + '.' + attachment.ext}`,
attachment.orig || `${attachment.name}${attachment.ext ? `.${attachment.ext}` : ''}`,
async (e) => {
if (e) {
this.gs.log('[RES_DOWNLOAD_ATTACHMENT-ERROR] 🔻', e, 'error');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ export class BerkasController {
});
await this.tempAttachmentRepo.remove(tempAttachment);
const files = readdirSync(`${environment.uploadFolder}`, { withFileTypes: true });
const fIdx = files.findIndex(f => f.name === tempAttachment.name || f.name === `${tempAttachment.name}.${tempAttachment.ext}`);
const fIdx = files.findIndex(f => f.name === tempAttachment.name || f.name === `${tempAttachment.name}${tempAttachment.ext ? `.${tempAttachment.ext}` : ''}`);
if (fIdx >= 0) {
const attachment = this.attachmentRepo.new();
attachment.name = tempAttachment.name;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,7 @@ export class DdlSeekController {
res_raw_headers.delete('Content-Range');
res_raw_headers.set('Content-Range', `bytes ${target}-${res_raw_headers_content_length_minus_1}/${attachment.size}`);
res_raw_headers.delete('Content-Disposition');
// Biar Nama File Gak Bisa Di Tebak ~
res_raw_headers.set('Content-Disposition', `attachment; filename="${attachment.name}.${attachment.ext}"`);
res_raw_headers.delete('Content-Type');
res_raw_headers.set('Content-Type', attachment.mime);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -164,13 +164,14 @@ export class MailWebhookController {
}
this.ms.webhook[req.body['Message-Id']].col.attachment_ = [];
for (const file of req.files as Express.Multer.File[]) {
const fileExt = file.originalname.split('.').pop().toLowerCase();
const fileExt = file.originalname.includes('.') && !file.originalname.endsWith('.') ? file.originalname.split('.').pop().toLowerCase() : null;
const files = readdirSync(`${environment.uploadFolder}`, { withFileTypes: true });
const fIdx = files.findIndex(f => f.name === file.filename || f.name === `${file.filename}.${fileExt}`);
const fIdx = files.findIndex(f => f.name === file.filename || f.name === `${file.filename}${fileExt ? `.${fileExt}` : ''}`);
if (fIdx >= 0) {
const attachment = this.attachmentRepo.new();
attachment.pending = true;
attachment.name = file.filename;
attachment.orig = file.originalname;
attachment.ext = fileExt;
attachment.size = file.size;
attachment.mime = file.mimetype;
Expand All @@ -181,7 +182,7 @@ export class MailWebhookController {
this.gcs.gDrive(true).then(async (gdrive) => {
const dfile = await gdrive.files.create({
requestBody: {
name: `${resAttachmentSave.name}.${resAttachmentSave.ext}`,
name: resAttachmentSave.orig || `${resAttachmentSave.name}${resAttachmentSave.ext ? `.${resAttachmentSave.ext}` : ''}`,
parents: [environment.gCloudPlatform.gDrive.folder_id],
mimeType: resAttachmentSave.mime
},
Expand Down Expand Up @@ -231,9 +232,9 @@ export class MailWebhookController {
}
if ((req.files as Express.Multer.File[])?.length > 0) {
for (const file of req.files as Express.Multer.File[]) {
const fileExt = file.originalname.split('.').pop().toLowerCase();
const fileExt = file.originalname.includes('.') && !file.originalname.endsWith('.') ? file.originalname.split('.').pop().toLowerCase() : null;
const files = readdirSync(`${environment.uploadFolder}`, { withFileTypes: true });
const fIdx = files.findIndex(f => f.name === file.filename || f.name === `${file.filename}.${fileExt}`);
const fIdx = files.findIndex(f => f.name === file.filename || f.name === `${file.filename}${fileExt ? `.${fileExt}` : ''}`);
if (fIdx >= 0) {
this.gs.deleteAttachment(files[fIdx].name);
}
Expand Down
2 changes: 1 addition & 1 deletion projects/main-site/src/api/entities/Attachment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export class Attachment implements AttachmentModel {
@Column({ type: 'text', nullable: true })
orig: string;

@Column({ type: 'text' })
@Column({ type: 'text', nullable: true })
ext: string;

@Column({ type: 'bigint', transformer: new ColumnNumberBigIntTransformer() })
Expand Down
2 changes: 1 addition & 1 deletion projects/main-site/src/api/entities/TempAttachment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export class TempAttachment implements TempAttachmentModel {
@Column({ type: 'text', nullable: true })
orig: string;

@Column({ type: 'text' })
@Column({ type: 'text', nullable: true })
ext: string;

@Column({ type: 'bigint', transformer: new ColumnNumberBigIntTransformer() })
Expand Down
16 changes: 9 additions & 7 deletions projects/main-site/src/api/scheduler/upload-task.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,19 +41,19 @@ export class UploadService {

async uploadSubtitleAndFont(mkvAttachment: AttachmentModel): Promise<void> {
const files = readdirSync(`${environment.uploadFolder}`, { withFileTypes: true });
const fIdx = files.findIndex(f => f.name === mkvAttachment.name || f.name === `${mkvAttachment.name}.${mkvAttachment.ext}`);
const fIdx = files.findIndex(f => f.name === mkvAttachment.name || f.name === `${mkvAttachment.name}${mkvAttachment.ext ? `.${mkvAttachment.ext}` : ''}`);
if (fIdx >= 0) {
try {
const gdrive = await this.gcs.gDrive(true);
const dfile = await gdrive.files.create({
requestBody: {
name: `${mkvAttachment.name}.${mkvAttachment.ext}`,
name: mkvAttachment.orig || `${mkvAttachment.name}${mkvAttachment.ext ? `.${mkvAttachment.ext}` : ''}`,
parents: [environment.gCloudPlatform.gDrive.folder_id],
mimeType: mkvAttachment.mime
},
media: {
mimeType: mkvAttachment.mime,
body: createReadStream(`${environment.uploadFolder}/${mkvAttachment.name}.${mkvAttachment.ext}`)
body: createReadStream(`${environment.uploadFolder}/${files[fIdx].name}`)
},
fields: 'id'
}, {
Expand All @@ -76,7 +76,7 @@ export class UploadService {
oa.pending = false;
}
await this.attachmentRepo.save(otherAttachment2);
this.gs.deleteAttachment(`${mkvAttachment.name}.${mkvAttachment.ext}`);
this.gs.deleteAttachment(`${mkvAttachment.name}${mkvAttachment.ext ? `.${mkvAttachment.ext}` : ''}`);
} catch (e3) {
this.gs.log('[GDRIVE-ERROR] 💽', e3, 'error');
mkvAttachment.pending = false;
Expand All @@ -95,18 +95,19 @@ export class UploadService {

async extractAndUploadVideoAndZip(attachment: AttachmentModel): Promise<void> {
const files = readdirSync(`${environment.uploadFolder}`, { withFileTypes: true });
const fIdx = files.findIndex(f => f.name === attachment.name || f.name === `${attachment.name}.${attachment.ext}`);
const fIdx = files.findIndex(f => f.name === attachment.name || f.name === `${attachment.name}${attachment.ext ? `.${attachment.ext}` : ''}`);
if (fIdx >= 0) {
if (attachment.ext === 'mkv') {
try {
const extractedFiles = await this.mkv.mkvExtract(attachment.name, `${environment.uploadFolder}/${files[fIdx].name}`);
for (const ef of extractedFiles) {
const fileNameExt = ef.name.split('.');
const fileExt = fileNameExt.pop().toLowerCase();
const fileName = fileNameExt.join('.').toLowerCase();
const fileExt = fileNameExt.length > 1 ? fileNameExt.pop().toLowerCase() : null;
const fileName = fileNameExt.length > 1 ? fileNameExt.join('.').toLowerCase() : fileNameExt[0];
try {
const mkvAttachment = this.attachmentRepo.new();
mkvAttachment.name = fileName;
mkvAttachment.orig = ef.name;
mkvAttachment.ext = fileExt;
mkvAttachment.size = ef.size;
mkvAttachment.pending = environment.production;
Expand Down Expand Up @@ -139,6 +140,7 @@ export class UploadService {
const fileExist = existsSync(`${environment.uploadFolder}/${fileName}.${fileExt}`);
if (mkvAttachmentDuplicate) {
mkvAttachment.name = mkvAttachmentDuplicate.name;
mkvAttachment.orig = mkvAttachmentDuplicate.orig;
mkvAttachment.ext = mkvAttachmentDuplicate.ext;
mkvAttachment.size = mkvAttachmentDuplicate.size;
mkvAttachment.mime = mkvAttachmentDuplicate.mime;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ export class AdminListDdlComponent implements OnInit, OnDestroy {
'Upload Ulang ?',
`
Id: ${data.id} <br />
Filename: ${data.name}.${data.ext} <br />
Filename: ${data.name}${data.name}${data.ext ? `.${data.ext}` : ''} <br />
Size: ${data.size} Bytes <br />
Mime: ${data.mime} <br />
Pemilik: ${data.user_.username}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ export class AdminListEmailComponent implements OnInit, OnDestroy {
}
lampiran += `
<a href="${environment.apiUrl}/attachment/${a.id}?ngsw-bypass=true" target="_blank">
${a.name}.${a.ext} (${a.size} Bytes)
${a.name}${a.ext ? `.${a.ext}` : ''} (${a.size} Bytes)
</a>
`;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,19 +91,19 @@ <h2 class="border-bottom-dotted">
<div class="col-12 text-center" *ngIf="isHaveDDL">
<div class="px-3">
<button type="button" class="m-1 w-100 {{ isAwsS3 ? '' : 'shiny' }}" mat-stroked-button color="accent" (click)="ddl(berkasData.attachment_.id)"
matTooltip="{{ lampiran.orig || lampiran.name + '.' + lampiran.ext }} :: {{ lampiran.download_count }}x Unduhan" *ngIf="!lampiran.data && !lampiran.isDownloading && !lampiran.isCompleted">
matTooltip="{{ lampiran.orig || lampiran.name + (lampiran.ext ? '.' + lampiran.ext : '') }} :: {{ lampiran.download_count }}x Unduhan" *ngIf="!lampiran.data && !lampiran.isDownloading && !lampiran.isCompleted">
<mat-icon fontIcon="movie" class="me-1"></mat-icon>
{{ lampiran.orig?.split('.')[0] || lampiran.name | slice:0:5 }}.....{{ lampiran.ext }} ({{ lampiran.size | bytes }})
{{ lampiran.orig?.split('.')[0] || lampiran.name | slice:0:5 }}.....{{ (lampiran.ext ? '.' + lampiran.ext : '') }} ({{ lampiran.size | bytes }})
</button>
<button type="button" class="m-1 w-100" mat-stroked-button color="accent" (click)="cancel_dl(berkasData.attachment_.id)"
matTooltip="{{ lampiran.orig || lampiran.name + '.' + lampiran.ext }} :: {{ lampiran.download_count }}x Unduhan" *ngIf="!lampiran.data && lampiran.isDownloading">
matTooltip="{{ lampiran.orig || lampiran.name + (lampiran.ext ? '.' + lampiran.ext : '') }} :: {{ lampiran.download_count }}x Unduhan" *ngIf="!lampiran.data && lampiran.isDownloading">
<mat-icon fontIcon="close" class="me-1"></mat-icon>
Batal Unduh
</button>
<button type="button" class="m-1 w-100 {{ isAwsS3 ? '' : 'shiny' }}" mat-stroked-button color="accent" (click)="saveFileAs(berkasData.attachment_.id)" *ngIf="lampiran.data"
matTooltip="{{ lampiran.orig || lampiran.name + '.' + lampiran.ext }} :: {{ lampiran.download_count }}x Unduhan">
matTooltip="{{ lampiran.orig || lampiran.name + (lampiran.ext ? '.' + lampiran.ext : '') }} :: {{ lampiran.download_count }}x Unduhan">
<mat-icon fontIcon="save" class="me-1"></mat-icon>
{{ lampiran.orig?.split('.')[0] || lampiran.name | slice:0:5 }}.....{{ lampiran.ext }} ({{ lampiran.size | bytes }})
{{ lampiran.orig?.split('.')[0] || lampiran.name | slice:0:5 }}.....{{ (lampiran.ext ? '.' + lampiran.ext : '') }} ({{ lampiran.size | bytes }})
</button>
<div class="col">
<div class="px-3" *ngIf="lampiran.isDownloading && !lampiran.isCompleted">
Expand All @@ -123,14 +123,14 @@ <h2 class="border-bottom-dotted">
<hr class="my-3 border-bottom-dotted" style="height: 4px; background: url('/assets/img/stripe.png');" />
</div>
<button type="button" class="m-1 w-100" mat-stroked-button color="accent" *ngFor="let s of berkasData.attachment_.subtitles_"
(click)="standardDdlSubsFont(s.id)" matTooltip="{{ s.orig || s.name + '.' + s.ext }} :: {{ s.download_count }}x Unduhan">
(click)="standardDdlSubsFont(s.id)" matTooltip="{{ s.orig || s.name + (s.ext ? '.' + s.ext : '') }} :: {{ s.download_count }}x Unduhan">
<mat-icon fontIcon="notes" class="me-1"></mat-icon>
{{ s.orig?.split('.')[0] || s.name | slice:0:5 }}.....{{ s.ext }} ({{ s.size | bytes }})
{{ s.orig?.split('.')[0] || s.name | slice:0:5 }}.....{{ (s.ext ? '.' + s.ext : '') }} ({{ s.size | bytes }})
</button>
<button type="button" class="m-1 w-100" mat-stroked-button color="accent" *ngFor="let f of berkasData.attachment_.fonts_"
(click)="standardDdlSubsFont(f.id)" matTooltip="{{ f.orig || f.name + '.' + f.ext }} :: {{ f.download_count }}x Unduhan">
(click)="standardDdlSubsFont(f.id)" matTooltip="{{ f.orig || f.name + (f.ext ? '.' + f.ext : '') }} :: {{ f.download_count }}x Unduhan">
<mat-icon fontIcon="font_download" class="me-1"></mat-icon>
{{ f.orig?.split('.')[0] || f.name | slice:0:5 }}.....{{ f.ext }} ({{ f.size | bytes }})
{{ f.orig?.split('.')[0] || f.name | slice:0:5 }}.....{{ (f.ext ? '.' + f.ext : '') }} ({{ f.size | bytes }})
</button>
</div>
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ <h2 class="pt-3 border-bottom-dotted">
<div mat-subheader class="text-warning">Berkas yang terlampir tidak boleh diubah.</div>
<mat-list-item>
<mat-icon fontIcon="attach_file" mat-list-icon></mat-icon>
<div mat-line>{{ attachmentFile.name }}.{{ attachmentFile.ext }}</div>
<div mat-line>{{ attachmentFile.name }}{{ attachmentFile.ext ? '.' + attachmentFile.ext : '' }}</div>
<div mat-line>{{ attachmentFile.size | bytes }}</div>
</mat-list-item>
<p class="py-3 m-0" *ngIf="attachmentFontSubtitle.length > 0">{{ attachmentFontSubtitle.join(', ').toLowerCase() }}</p>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ export class BerkasEditComponent implements OnInit, OnDestroy {
}

get fileTypeAttachmentAllowed(): string {
return CONSTANTS.fileTypeAttachmentAllowed.join(', ');
return CONSTANTS.fileTypeAttachmentAllowed.filter(mime => mime != 'application/octet-stream').join(', ');
}

ngOnInit(): void {
Expand Down Expand Up @@ -243,20 +243,25 @@ export class BerkasEditComponent implements OnInit, OnDestroy {
this.uploadService.disconnect();
try {
if (file.size <= CONSTANTS.fileSizeAttachmentTotalLimit) {
this.uploadService.handleFiles(file);
this.subsDialog = (await this.ds.openKonfirmasiDialog(
'Saran Penamaan Berkas',
'Apakah Ingin Mengganti Penamaan Berkas Sesuai Dengan Nama Lampiran Yang Di Unggah ?'
)).afterClosed().subscribe({
next: re => {
this.gs.log('[INFO_DIALOG_CLOSED]', re);
if (re === true) {
this.fg.controls['name'].patchValue(file.name);
this.fg.controls['name'].markAsDirty();
if (!file.name.includes('.') || file.name.endsWith('.')) {
this.attachmentErrorText = 'Ekstensi Nama Lampiran Tidak Valid!';
this.ddl.clear(event);
} else {
this.uploadService.handleFiles(file);
this.subsDialog = (await this.ds.openKonfirmasiDialog(
'Saran Penamaan Berkas',
'Apakah Ingin Mengganti Penamaan Berkas Sesuai Dengan Nama Lampiran Yang Di Unggah ?'
)).afterClosed().subscribe({
next: re => {
this.gs.log('[INFO_DIALOG_CLOSED]', re);
if (re === true) {
this.fg.controls['name'].patchValue(file.name);
this.fg.controls['name'].markAsDirty();
}
this.subsDialog.unsubscribe();
}
this.subsDialog.unsubscribe();
}
});
});
}
} else {
this.attachmentLimitExceeded = CONSTANTS.fileSizeAttachmentTotalLimit;
this.ddl.clear(event);
Expand Down Expand Up @@ -427,12 +432,12 @@ export class BerkasEditComponent implements OnInit, OnDestroy {
this.attachmentFile = data.attachment_;
if (data.attachment_.fonts_) {
data.attachment_.fonts_.forEach(f => {
this.attachmentFontSubtitle.push(`${f.name}.${f.ext}`);
this.attachmentFontSubtitle.push(`${f.name}${f.ext ? `.${f.ext}` : ''}`);
});
}
if (data.attachment_.subtitles_) {
data.attachment_.subtitles_.forEach(s => {
this.attachmentFontSubtitle.push(`${s.name}.${s.ext}`);
this.attachmentFontSubtitle.push(`${s.name}${s.ext ? `.${s.ext}` : ''}`);
});
}
}
Expand Down
Loading

0 comments on commit caaabf6

Please sign in to comment.