improve chat

This commit is contained in:
Peter Maquiran
2022-02-03 21:01:53 +01:00
parent 33a2982805
commit 61de7b937b
13 changed files with 1147 additions and 668 deletions
@@ -26,6 +26,13 @@ import { ViewEventPage } from 'src/app/modals/view-event/view-event.page';
import { HttpEventType } from '@angular/common/http';
import { SqliteService } from 'src/app/services/sqlite.service';
import { WsChatMethodsService } from 'src/app/services/chat/ws-chat-methods.service';
import { AttachmentsService } from 'src/app/services/attachments.service';
import { FileType } from 'src/app/models/fileType';
import { Storage } from '@ionic/storage';
import { FileSystemService } from 'src/app/services/file-system.service';
import { CameraService } from 'src/app/services/camera.service';
import { SearchPage } from 'src/app/pages/search/search.page';
import { ProcessesService } from 'src/app/services/processes.service';
@Component({
selector: 'app-group-messages',
@@ -87,7 +94,12 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
private changeDetectorRef: ChangeDetectorRef,
private sqlservice: SqliteService,
private platform: Platform,
public wsChatMethodsService: WsChatMethodsService
public wsChatMethodsService: WsChatMethodsService,
private AttachmentsService: AttachmentsService,
private storage: Storage,
private processesService: ProcessesService,
private FileSystemService: FileSystemService,
private CameraService: CameraService,
) {
this.loggedUserChat = authService.ValidatedUserChat['data'];
this.isGroupCreated = true;
@@ -481,8 +493,150 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
}
}
async takePicture() {
const roomId = this.roomId
const image = await this.CameraService.takePicture();
await this.FileSystemService.saveImage(image, roomId)
const lastphoto: any = await this.FileSystemService.loadFiles(roomId);
const { capturedImage, capturedImageTitle} = await this.FileSystemService.loadFileData(lastphoto, roomId);
const base64 = await fetch(capturedImage);
const blob = await base64.blob();
const formData = new FormData();
formData.append("blobFile", blob);
console.log('ALL IMAGE', formData)
let guid: any = await this.AttachmentsService.uploadFile(formData).toPromise()
console.log(guid.path);
this.AttachmentsService.downloadFile(guid.path).subscribe(async (event) => {
if (event.type === HttpEventType.DownloadProgress) {
//this.downloadProgess = Math.round((100 * event.loaded) / event.total);
//console.log('FILE TYPE 33', msg.file.type)
} else if (event.type === HttpEventType.Response) {
var fileImage = 'data:image/jpeg;base64,' + btoa(new Uint8Array(event.body).reduce((data, byte) => data + String.fromCharCode(byte), ''));
console.log('add picture to chat',fileImage);
await this.storage.set(guid.path, fileImage).then(() => {
console.log('add picture to chat IMAGE SAVED')
this.wsChatMethodsService.getDmRoom(this.roomId).sendFile({
file: {
"type": "application/img",
"guid": guid.path,
"image_url": fileImage
},
attachments: [{
//"title": this.capturedImageTitle ,
//"text": "description",
"title_link_download": false,
//"image_url": this.capturedImage,
}]
})
});
}
});
}
async addImage() {
this.addFileToChat(['image/apng', 'image/jpeg', 'image/png'])
}
async addFile() {
this.addFileToChat(['.doc', '.docx', '.pdf'])
}
async addFileWebtrix() {
const modal = await this.modalController.create({
component: SearchPage,
cssClass: 'group-messages modal-desktop search-modal search-modal-to-desktop',
componentProps: {
type: 'AccoesPresidenciais & ArquivoDespachoElect',
select: true,
showSearchInput: true,
}
});
await modal.present();
modal.onDidDismiss().then(async res=>{
const data = res.data;
if(data.selected){
const loader = this.toastService.loading();
let url = await this.processesService.GetDocumentUrl(res.data.selected.Id, res.data.selected.ApplicationType).toPromise();
let url_no_options: string = url.replace("webTRIX.Viewer","webTRIX.Viewer.Branch1");
console.log(url_no_options);
this.wsChatMethodsService.getDmRoom(this.roomId).sendFile({
alias: "documento",
file:{
"name": res.data.selected.Assunto,
"type": "application/webtrix",
"ApplicationId": res.data.selected.ApplicationType,
"DocId": res.data.selected.Id,
"Assunto": res.data.selected.Assunto,
},
attachments: [{
"title": res.data.selected.Assunto,
"description": res.data.selected.DocTypeDesc,
"title_link": url_no_options,
"title_link_download": true,
//"thumb_url": "assets/images/webtrix-logo.png",
"message_link": url_no_options,
"type": "webtrix"
}]
})
loader.remove();
}
});
}
async addFileToChat(types: typeof FileType[] ) {
const file = await this.fileService.getFileFromDevice(types);
const formData = new FormData();
formData.append("blobFile", file);
let guid: any = await this.AttachmentsService.uploadFile(formData).toPromise()
this.AttachmentsService.downloadFile(guid.path).subscribe(async (event) => {
if (event.type === HttpEventType.DownloadProgress) {
//this.downloadProgess = Math.round((100 * event.loaded) / event.total);
//console.log('FILE TYPE 33', msg.file.type)
} else if (event.type === HttpEventType.Response) {
var fileImage = 'data:image/jpeg;base64,' + btoa(new Uint8Array(event.body).reduce((data, byte) => data + String.fromCharCode(byte), ''));
console.log('add picture to chat',fileImage);
await this.storage.set(guid.path, fileImage).then(() => {
console.log('add picture to chat IMAGE SAVED')
this.wsChatMethodsService.getDmRoom(this.roomId).sendFile({
file: {
"type": "application/img",
"guid": guid.path,
"image_url": fileImage
},
attachments: [{
//"title": this.capturedImageTitle ,
//"text": "description",
"title_link_download": false,
//"image_url": this.capturedImage,
}]
})
});
}
});
}
async openChatOptions(ev?: any) {
console.log(this.members);
const roomId = this.roomId;
const popover = await this.popoverController.create({
component: ChatOptionsPopoverPage,
@@ -496,27 +650,65 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {
translucent: true
});
await popover.present();
await popover.onDidDismiss().then((res)=>{
await popover.onDidDismiss().then( async(res)=>{
console.log(res['data']);
if(res['data'] == 'meeting'){
this.bookMeeting();
}
else if(res['data'] == 'take-picture'){
this.fileService.addCameraPictureToChat(this.roomId);
//this.loadPicture();
else if(res['data'] == 'take-picture') {
const image = await this.CameraService.takePicture();
await this.FileSystemService.saveImage(image, roomId)
const lastphoto: any = await this.FileSystemService.loadFiles(roomId);
const { capturedImage, capturedImageTitle} = await this.FileSystemService.loadFileData(lastphoto, roomId);
const base64 = await fetch(capturedImage);
const blob = await base64.blob();
const formData = new FormData();
formData.append("blobFile", blob);
console.log('ALL IMAGE', formData)
let guid: any = await this.AttachmentsService.uploadFile(formData).toPromise()
console.log(guid.path);
this.AttachmentsService.downloadFile(guid.path).subscribe(async (event) => {
if (event.type === HttpEventType.DownloadProgress) {
//this.downloadProgess = Math.round((100 * event.loaded) / event.total);
//console.log('FILE TYPE 33', msg.file.type)
} else if (event.type === HttpEventType.Response) {
var fileImage = 'data:image/jpeg;base64,' + btoa(new Uint8Array(event.body).reduce((data, byte) => data + String.fromCharCode(byte), ''));
console.log('add picture to chat',fileImage);
await this.storage.set(guid.path, fileImage).then(() => {
console.log('add picture to chat IMAGE SAVED')
this.wsChatMethodsService.getDmRoom(this.roomId).sendFile({
file: {
"type": "application/img",
"guid": guid.path,
"image_url": fileImage
},
attachments: [{
//"title": this.capturedImageTitle ,
//"text": "description",
"title_link_download": false,
//"image_url": this.capturedImage,
}]
})
});
}
});
}
else if(res['data'] == 'add-picture'){
this.fileService.addPictureToChatMobile(this.roomId);
//this.loadPicture();
this.addImage()
}
else if(res['data'] == 'add-document'){
this.fileService.addDocumentToChat(this.roomId);
//this.loadDocument();
this.addFile()
}
else if(res['data'] == 'documentoGestaoDocumental'){
this.fileService.addDocGestaoDocumentalToChat(this.roomId);
//this.addDocGestaoDocumental();
this.addFileWebtrix()
}
this.loadGroupMessages(this.roomId);
});
@@ -742,7 +934,7 @@ downloadFileMsg(msg) {
console.log('FILE TYPE', msg.file.type)
this.downloadFile = "";
if (msg.file.type == "application/img") {
this.fileService.downloadFile(msg.file.guid).subscribe(async (event) => {
this.AttachmentsService.downloadFile(msg.file.guid).subscribe(async (event) => {
console.log('FILE TYPE 22', msg.file.guid)
var name = msg.file.guid;
+201 -110
View File
@@ -31,6 +31,13 @@ import { HttpEventType } from '@angular/common/http';
import { ViewEventPage } from 'src/app/modals/view-event/view-event.page';
import { WsChatMethodsService } from 'src/app/services/chat/ws-chat-methods.service'
import { MessageService } from 'src/app/services/chat/message.service';
import { AttachmentsService } from 'src/app/services/attachments.service';
import { FileSystemService } from 'src/app/services/file-system.service';
import { CameraService } from 'src/app/services/camera.service';
import { element } from 'protractor';
import { FileType } from 'src/app/models/fileType';
import { SearchPage } from 'src/app/pages/search/search.page';
import { Storage } from '@ionic/storage';
const IMAGE_DIR = 'stored-images';
@@ -98,7 +105,12 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
private changeDetectorRef: ChangeDetectorRef,
private platform: Platform,
private sqlservice: SqliteService,
public wsChatMethodsService: WsChatMethodsService
public wsChatMethodsService: WsChatMethodsService,
private AttachmentsService: AttachmentsService,
private FileSystemService: FileSystemService,
private CameraService: CameraService,
private processesService: ProcessesService,
private storage: Storage,
) {
this.loggedUser = authService.ValidatedUserChat['data'];
this.roomId = this.navParams.get('roomId');
@@ -121,8 +133,6 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
}
ngOnInit() {
//this.load();
this.setStatus('online');
//this.loadFiles();
VoiceRecorder.requestAudioRecordingPermission();
@@ -253,15 +263,6 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
this.selectedMsgId = "";
}
setStatus(status: string) {
let body = {
message: '',
status: status,
}
this.chatService.setUserStatus(body).subscribe(res => {
console.log(res);
})
}
notImplemented() {
this.alertService.presentAlert('Funcionalidade em desenvolvimento');
@@ -272,7 +273,6 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
}
load() {
this.serverLongPull();
this.getChatMembers();
}
@@ -515,6 +515,146 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
}
}
async takePicture() {
const roomId = this.roomId
const image = await this.CameraService.takePicture();
await this.FileSystemService.saveImage(image, roomId)
const lastphoto: any = await this.FileSystemService.loadFiles(roomId);
const { capturedImage, capturedImageTitle} = await this.FileSystemService.loadFileData(lastphoto, roomId);
const base64 = await fetch(capturedImage);
const blob = await base64.blob();
const formData = new FormData();
formData.append("blobFile", blob);
console.log('ALL IMAGE', formData)
let guid: any = await this.AttachmentsService.uploadFile(formData).toPromise()
console.log(guid.path);
this.AttachmentsService.downloadFile(guid.path).subscribe(async (event) => {
if (event.type === HttpEventType.DownloadProgress) {
//this.downloadProgess = Math.round((100 * event.loaded) / event.total);
//console.log('FILE TYPE 33', msg.file.type)
} else if (event.type === HttpEventType.Response) {
var fileImage = 'data:image/jpeg;base64,' + btoa(new Uint8Array(event.body).reduce((data, byte) => data + String.fromCharCode(byte), ''));
console.log('add picture to chat',fileImage);
await this.storage.set(guid.path, fileImage).then(() => {
console.log('add picture to chat IMAGE SAVED')
this.wsChatMethodsService.getDmRoom(this.roomId).sendFile({
file: {
"type": "application/img",
"guid": guid.path,
"image_url": fileImage
},
attachments: [{
//"title": this.capturedImageTitle ,
//"text": "description",
"title_link_download": false,
//"image_url": this.capturedImage,
}]
})
});
}
});
}
async addImage() {
this.addFileToChat(['image/apng', 'image/jpeg', 'image/png'])
}
async addFile() {
this.addFileToChat(['.doc', '.docx', '.pdf'])
}
async addFileWebtrix() {
const modal = await this.modalController.create({
component: SearchPage,
cssClass: 'group-messages modal-desktop search-modal search-modal-to-desktop',
componentProps: {
type: 'AccoesPresidenciais & ArquivoDespachoElect',
select: true,
showSearchInput: true,
}
});
await modal.present();
modal.onDidDismiss().then(async res=>{
const data = res.data;
if(data.selected){
const loader = this.toastService.loading();
let url = await this.processesService.GetDocumentUrl(res.data.selected.Id, res.data.selected.ApplicationType).toPromise();
let url_no_options: string = url.replace("webTRIX.Viewer","webTRIX.Viewer.Branch1");
console.log(url_no_options);
this.wsChatMethodsService.getDmRoom(this.roomId).sendFile({
alias: "documento",
file:{
"name": res.data.selected.Assunto,
"type": "application/webtrix",
"ApplicationId": res.data.selected.ApplicationType,
"DocId": res.data.selected.Id,
"Assunto": res.data.selected.Assunto,
},
attachments: [{
"title": res.data.selected.Assunto,
"description": res.data.selected.DocTypeDesc,
"title_link": url_no_options,
"title_link_download": true,
//"thumb_url": "assets/images/webtrix-logo.png",
"message_link": url_no_options,
"type": "webtrix"
}]
})
loader.remove();
}
});
}
async addFileToChat(types: typeof FileType[] ) {
const file = await this.fileService.getFileFromDevice(types);
const formData = new FormData();
formData.append("blobFile", file);
let guid: any = await this.AttachmentsService.uploadFile(formData).toPromise()
this.AttachmentsService.downloadFile(guid.path).subscribe(async (event) => {
if (event.type === HttpEventType.DownloadProgress) {
//this.downloadProgess = Math.round((100 * event.loaded) / event.total);
//console.log('FILE TYPE 33', msg.file.type)
} else if (event.type === HttpEventType.Response) {
var fileImage = 'data:image/jpeg;base64,' + btoa(new Uint8Array(event.body).reduce((data, byte) => data + String.fromCharCode(byte), ''));
console.log('add picture to chat',fileImage);
await this.storage.set(guid.path, fileImage).then(() => {
console.log('add picture to chat IMAGE SAVED')
this.wsChatMethodsService.getDmRoom(this.roomId).sendFile({
file: {
"type": "application/img",
"guid": guid.path,
"image_url": fileImage
},
attachments: [{
//"title": this.capturedImageTitle ,
//"text": "description",
"title_link_download": false,
//"image_url": this.capturedImage,
}]
})
});
}
});
}
async openChatOptions(ev?: any) {
const roomId = this.roomId
console.log(this.members);
@@ -531,66 +671,71 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
translucent: true
});
await popover.present();
popover.onDidDismiss().then((res) => {
popover.onDidDismiss().then( async (res) => {
console.log(res['data']);
if (res['data'] == 'meeting') {
this.bookMeeting();
}
else if (res['data'] == 'take-picture') {
this.fileService.addCameraPictureToChat(roomId);
//this.loadPicture();
const image = await this.CameraService.takePicture();
await this.FileSystemService.saveImage(image, roomId)
const lastphoto: any = await this.FileSystemService.loadFiles(roomId);
const { capturedImage, capturedImageTitle} = await this.FileSystemService.loadFileData(lastphoto, roomId);
const base64 = await fetch(capturedImage);
const blob = await base64.blob();
const formData = new FormData();
formData.append("blobFile", blob);
console.log('ALL IMAGE', formData)
let guid: any = await this.AttachmentsService.uploadFile(formData).toPromise()
console.log(guid.path);
this.AttachmentsService.downloadFile(guid.path).subscribe(async (event) => {
if (event.type === HttpEventType.DownloadProgress) {
//this.downloadProgess = Math.round((100 * event.loaded) / event.total);
//console.log('FILE TYPE 33', msg.file.type)
} else if (event.type === HttpEventType.Response) {
var fileImage = 'data:image/jpeg;base64,' + btoa(new Uint8Array(event.body).reduce((data, byte) => data + String.fromCharCode(byte), ''));
console.log('add picture to chat',fileImage);
await this.storage.set(guid.path, fileImage).then(() => {
console.log('add picture to chat IMAGE SAVED')
this.wsChatMethodsService.getDmRoom(this.roomId).sendFile({
file: {
"type": "application/img",
"guid": guid.path,
"image_url": fileImage
},
attachments: [{
//"title": this.capturedImageTitle ,
//"text": "description",
"title_link_download": false,
//"image_url": this.capturedImage,
}]
})
});
}
});
}
else if (res['data'] == 'add-picture') {
this.fileService.addPictureToChatMobile(roomId);
//this.loadPicture();
this.addImage()
}
else if (res['data'] == 'add-document') {
this.fileService.addDocumentToChat(this.roomId);
//this.loadDocument();
this.addFile()
}
else if (res['data'] == 'documentoGestaoDocumental') {
this.fileService.addDocGestaoDocumentalToChat(this.roomId);
//this.addDocGestaoDocumental();
this.addFileWebtrix()
}
});
}
/*
this.fileService.downloadFile(element.file.guid).subscribe(async (event) => {
var name = element.file.guid;
if (event.type === HttpEventType.DownloadProgress) {
} else if (event.type === HttpEventType.Response) {
var base64 = btoa(new Uint8Array(event.body).reduce((data, byte) => data + String.fromCharCode(byte), '')
);
console.log('TRY ARRAY BUFFER NAME', name);
console.log('TRY ARRAY BUFFER', base64);
await Filesystem.writeFile({
path: `${IMAGE_DIR}/${name}`,
data: base64,
directory: Directory.Data
}).then((foo) => {
console.log('LSKE FS FILE SAVED', foo)
}).catch((error) => {
console.log('error LAKE FS FILE', error)
});
const readFile = await Filesystem.readFile({
path: `${IMAGE_DIR}/${name}`,
directory: Directory.Data,
});
});*/
getRoomMessageDB(roomId) {
if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
@@ -666,60 +811,6 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
}
async serverLongPull() {
const roomId = this.roomId
/* this.chatService.getRoomMessages(roomId).subscribe(res=>{
console.log(res);
}) */
this.chatService.getRoomMessages(roomId).subscribe(async res => {
console.log("Chat message", res)
this.transformDataMSG(res['messages'])
this.getRoomMessageDB(this.roomId);
if (res == 502) {
// Connection timeout
// happens when the synchro was pending for too long
// let's reconnect
await this.serverLongPull();
}
else if (res != 200) {
// Show Error
//showMessage(response.statusText);
//this.loadMessages()
if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
}
//console.log(this.messages);
// Reconnect in one second
if (this.route.url != "/home/chat") {
console.log("Timer message stop")
} else {
//Check if modal is opened
if (document.querySelector('.isMessagesChatOpened')) {
await new Promise(resolve => setTimeout(resolve, 5000));
await this.serverLongPull();
//console.log('Timer message running')
}
}
} else {
// Got message
//let message = await response.text();
//this.loadMessages()
await this.serverLongPull();
}
});
}
sliderOpts = {
zoom: false,
@@ -767,7 +858,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy {
console.log('FILE TYPE', msg.file.type)
this.downloadFile = "";
if (msg.file.type == "application/img") {
this.fileService.downloadFile(msg.file.guid).subscribe(async (event) => {
this.AttachmentsService.downloadFile(msg.file.guid).subscribe(async (event) => {
console.log('FILE TYPE 22', msg.file.guid)
var name = msg.file.guid;
+41
View File
@@ -20,6 +20,47 @@ export class AttachmentsService {
this.headers = this.headers.set('Authorization', this.loggeduser.BasicAuthKey);
}
uploadFile(formData:any) {
console.log('UPLOAD file', formData)
//const geturl = environment.apiURL + 'Tasks/DelegateTask';
const geturl = environment.apiURL + 'ObjectServer/UploadFiles';
let options = {
headers: this.headers
};
return this.http.post(`${geturl}`, formData, options);
}
getFile(guid:any) {
const geturl = environment.apiURL + 'lakefs/StreamFile';
let params = new HttpParams();
params = params.set("path", guid);
this.headers = this.headers.set('responseType', 'blob');
this.headers = this.headers.set('Content-Type', 'application/octet-stream');
let options = {
headers: this.headers,
params: params
};
return this.http.get<any>(`${geturl}`, options);
}
downloadFile(guid:any) {
let downloadUrl = environment.apiURL +'objectserver/streamfiles?path='+guid;
var name = new Date().getTime();
return this.http.get(downloadUrl, {
responseType: "arraybuffer",
reportProgress: true, observe: 'events'
})
}
getAttachmentsBySerial(serialNumber: string): Observable<Attachment[]>{
let geturl = environment.apiURL + 'attachments/GetAttachments';
let params = new HttpParams();
+16
View File
@@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { CameraService } from './camera.service';
describe('CameraService', () => {
let service: CameraService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(CameraService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
+36
View File
@@ -0,0 +1,36 @@
import { Injectable } from '@angular/core';
import { Camera, CameraResultType, CameraSource, Photo} from '@capacitor/camera';
@Injectable({
providedIn: 'root'
})
export class CameraService {
constructor() { }
async takePicture(){
return new Promise<Photo>(async (resolve, reject)=>{
console.log('add camera to picture')
const image = await Camera.getPhoto({
quality: 50,
allowEditing: false,
resultType: CameraResultType.Uri,
source: CameraSource.Camera // Camera, Photos or Prompt!
});
if (image) {
resolve(image)
} else {
reject('Error saving image')
}
//this.capturedImage = this.capturedImage;
})
}
}
+26 -18
View File
@@ -2,6 +2,8 @@ import { Injectable } from '@angular/core';
import { Message } from 'src/app/models/chatMethod';
import { chatHistory, ChatMessage, File } from 'src/app/models/chatMethod'
import { Storage } from '@ionic/storage';
import { SessionStore } from 'src/app/store/session.service';
import { capitalizeTxt } from 'src/plugin/text'
@Injectable({
providedIn: 'root'
@@ -17,28 +19,34 @@ export class MessageService {
u = {}
t = ''
_id =''
_updatedAt = ''
_updatedAt
file
attachments
offline = false
offline = true
constructor(private storage: Storage) {
}
}
setData({customFields, channels, mentions, msg ,rid ,ts, u, t, _id, _updatedAt, file, attachments}:Message) {
this.customFields = customFields
this.channels = channels
this.mentions = mentions
this.msg = msg
this.customFields = customFields
this.channels = channels || []
this.mentions = mentions || []
this.msg = msg || ""
this.rid = rid
this.ts = ts
this.u = u
this.u = u || { name: this.usernameToDisplayName(SessionStore.user.RochetChatUser), username: SessionStore.user.RochetChatUser, _id: ""}
this.t = t
this._id = _id
this._updatedAt = _updatedAt
this._updatedAt = _updatedAt || new Date().getTime()
this.file = file
this.attachments = attachments
if(!this.ts) {
this.offline = true
} else {
this.offline = false
}
if (this.file) {
if (this.file.guid) {
@@ -49,22 +57,22 @@ export class MessageService {
}
}
if(this.rid == 'offline') {
this.offline = true
} else {
this.offline = false
}
}
delete() {}
showDateDuration() {}
resend() {
}
private usernameToDisplayName(username) {
const firstName = capitalizeTxt(username.split('.')[0])
const lastName = capitalizeTxt(username.split('.')[1])
return firstName + ' ' + lastName
}
}
+63 -25
View File
@@ -14,6 +14,7 @@ import { capitalizeTxt } from 'src/plugin/text'
import { SortService } from '../functions/sort.service';
import { chatUser } from 'src/app/models/chatMethod';
import { environment } from 'src/environments/environment';
import { ChatService } from 'src/app/services/chat.service';
@Injectable({
providedIn: 'root'
@@ -62,6 +63,7 @@ export class RoomService {
private sqlservice: SqliteService,
private NativeNotificationService: NativeNotificationService,
private sortService: SortService,
private chatService: ChatService,
) {
this.NativeNotificationService.askForPermission()
}
@@ -88,9 +90,10 @@ export class RoomService {
this.id,
"stream-room-messages",
(ChatMessage) => {
ChatMessage = ChatMessage.fields.args[0]
if(environment.chatOffline == false || this.isSenderIsNotMe(ChatMessage)) {
ChatMessage = ChatMessage.fields.args[0]
ChatMessage = this.fix_updatedAt(ChatMessage)
console.log('recivemessage', ChatMessage)
@@ -211,15 +214,15 @@ export class RoomService {
const offlineChatMessage = {
channels: [],
mentions: [],
rid: 'offline',
rid: this.id,
msg: this.message,
ts: { $date: new Date().getTime() },
u: {
name: this.usernameToDisplayName(SessionStore.user.RochetChatUser),
username: SessionStore.user.RochetChatUser,
_id: ""
},
_updatedAt: new Date().getTime()
_updatedAt: new Date().getTime(),
offline: true
}
this.addMessageDB(offlineChatMessage)
@@ -231,31 +234,60 @@ export class RoomService {
this.lastMessage = message
this.redefinedMessage(message)
this.WsChatService.send(this.id, message.msg).then((data: any) => {
let ChatMessage = data.result
this.redefinedMessage(message, ChatMessage)
})
this.calDateDuration(message._updatedAt)
this.sortRoomList()
this.message= ''
}
}
redefinedMessage = (message: MessageService) => {
this.WsChatService.send(this.id, message.msg).then((data: any) => {
let ChatMessage = data.result
sendFile({file, attachments, alias = 'document'}) {
let offlineChatMessage = {
rid: this.id,
msg: this.message,
attachments,
file,
}
this.addMessageDB(offlineChatMessage)
const message: MessageService = this.prepareMessage(offlineChatMessage)
ChatMessage = this.fix_updatedAt(ChatMessage)
setTimeout(() => {
this.scrollDown()
}, 150)
message.setData(ChatMessage)
this.lastMessage = message
if( new Date(this.lastMessage._updatedAt).getTime() < new Date(message._updatedAt).getTime()) {
this.lastMessage = message
this.calDateDuration(message._updatedAt)
}
this.sortRoomList()
})
this.calDateDuration(message._updatedAt)
this.sortRoomList()
this.chatService.sendMessage({message:offlineChatMessage}).subscribe((res:any) => {
let ChatMessage = res.message
console.log('ChatMessage', ChatMessage)
this.redefinedMessage(message, ChatMessage)
}, (error) => {
});
}
redefinedMessage (message: MessageService, ChatMessage) {
ChatMessage = this.fix_updatedAt(ChatMessage)
message.setData(ChatMessage)
if( new Date(this.lastMessage._updatedAt).getTime() < new Date(message._updatedAt).getTime()) {
this.lastMessage = message
this.calDateDuration(message._updatedAt)
}
this.sortRoomList()
}
@@ -330,11 +362,15 @@ export class RoomService {
let localMessages = []
messages.forEach((message = []) => {
const wewMessage = this.prepareMessage(message)
messages.forEach((ChatMessage, index) => {
const wewMessage = this.prepareMessage(ChatMessage)
if(wewMessage.rid == 'offline') {
this.redefinedMessage(wewMessage)
if(wewMessage.offline == true) {
this.WsChatService.send(this.id, wewMessage.msg).then((data: any) => {
let _ChatMessage = data.result
this.redefinedMessage(wewMessage, _ChatMessage)
this.storage.set('chatmsg' + this.id, messages)
})
}
localMessages.push(wewMessage)
@@ -381,7 +417,7 @@ export class RoomService {
prepareMessage(message) {
prepareMessage(message): MessageService {
message = this.fix_updatedAt(message)
const wewMessage = new MessageService(this.storage)
wewMessage.setData(message)
@@ -412,9 +448,11 @@ export class RoomService {
if (message.result) {
//console.log('FIX UPDATE ', message.result)
message.result._updatedAt = message.result._updatedAt['$date']
} else if(message._updatedAt.hasOwnProperty('$date')) {
// console.log('FIX UPDATE 11', message)
message._updatedAt = message._updatedAt['$date']
} else if(message._updatedAt) {
if(message._updatedAt.hasOwnProperty('$date')) {
// console.log('FIX UPDATE 11', message)
message._updatedAt = message._updatedAt['$date']
}
}
return message
}
@@ -193,7 +193,7 @@ export class WsChatMethodsService {
prepareRoom(roomData) {
let room:RoomService;
room = new RoomService(this.WsChatService, new MessageService(this.storage), this.storage, this.platform, this.sqlservice, this.NativeNotificationService, this.sortService)
room = new RoomService(this.WsChatService, new MessageService(this.storage), this.storage, this.platform, this.sqlservice, this.NativeNotificationService, this.sortService, this.ChatService)
room.setData({
customFields: roomData.customFields,
@@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { FileSystemService } from './file-system.service';
describe('FileSystemService', () => {
let service: FileSystemService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(FileSystemService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
+145
View File
@@ -0,0 +1,145 @@
import { Injectable } from '@angular/core';
import { ModalController, Platform,LoadingController } from '@ionic/angular';
import { Filesystem, Directory } from '@capacitor/filesystem';
import { Camera, CameraResultType, CameraSource, Photo} from '@capacitor/camera';
import { ChatService } from './chat.service';
import { AttachmentsService } from 'src/app/services/attachments.service';
import { ToastService } from './toast.service';
import { environment } from 'src/environments/environment';
import { HttpClient, HttpEventType, HttpHeaders, HttpParams } from '@angular/common/http';
import { Storage } from '@ionic/storage';
const IMAGE_DIR = 'stored-images';
interface LocalFile {
name: string;
path: string;
data: string;
}
@Injectable({
providedIn: 'root'
})
export class FileSystemService {
images: LocalFile[] = [];
constructor(
private platform: Platform,
private loadingCtrl: LoadingController,
private chatService: ChatService,
private AttachmentsService: AttachmentsService,
private toastService: ToastService,
private storage: Storage,) { }
async saveImage(photo: Photo, roomid: any) {
const base64Data = await this.readAsBase64(photo);
const fileName = new Date().getTime() + '.jpeg';
const savedFile = await Filesystem.writeFile({
path: `${IMAGE_DIR}/${fileName}`,
data: base64Data,
directory: Directory.Data
});
}
//new method 3
async loadFiles(roomid) {
this.images = [];
const loading = await this.loadingCtrl.create({
message: 'Loading data...',
});
await loading.present();
return new Promise((resolve, reject)=>{
Filesystem.readdir({
path: IMAGE_DIR,
directory: Directory.Data,
}).then(result => {
console.log('ALL RESULTS', result.files[0])
let lastphoto = result.files[result.files.length - 1]
resolve(lastphoto)
},
async (err) => {
console.log('ERROR FILE DOSENT EXIST', err)
reject('ERROR FILE DOSENT EXIST')
// Folder does not yet exists!
await Filesystem.mkdir({
path: IMAGE_DIR,
directory: Directory.Data,
recursive: true
});
}
).then(_ => {
loading.dismiss();
});
})
}
//new method 2
private async readAsBase64(photo: Photo) {
if (this.platform.is('hybrid')) {
const file = await Filesystem.readFile({
path: photo.path
});
return file.data;
}
else {
// Fetch the photo, read as a blob, then convert to base64 format
const response = await fetch(photo.webPath);
const blob = await response.blob();
return await this.convertBlobToBase64(blob) as string;
}
}
convertBlobToBase64 = (blob: Blob) => new Promise((resolve, reject) => {
const reader = new FileReader;
reader.onerror = reject;
reader.onload = () => {
resolve(reader.result);
};
reader.readAsDataURL(blob);
});
async readFile(filePath) {
return await Filesystem.readFile({
path: filePath,
directory: Directory.Data,
});
}
//new method 4
async loadFileData(fileName: string, roomid: any) {
console.log('ALL PHOTOT FILE', fileName)
// for (let f of fileNames) {
const filePath = `${IMAGE_DIR}/${fileName}`;
const readFile = await this.readFile(filePath)
this.images.push({
name: fileName,
path: filePath,
data: `data:image/jpeg;base64,${readFile.data}`,
});
console.log('ALL IMAGE', this.images)
const capturedImage = this.images[0].data
const capturedImageTitle = new Date().getTime() + '.jpeg';
return { capturedImage, capturedImageTitle}
}
}
+22 -407
View File
@@ -2,18 +2,14 @@ import { Injectable } from '@angular/core';
import { FileLoaderService } from '../file/file-loader.service';
import { FileToBase64Service } from '../file/file-to-base64.service';
import { InAppBrowser } from '@ionic-native/in-app-browser/ngx';
import { ChatService } from '../chat.service';
import { ModalController, Platform,LoadingController } from '@ionic/angular';
import { ModalController } from '@ionic/angular';
import { SearchPage } from 'src/app/pages/search/search.page';
import { SearchList } from 'src/app/models/search-document';
import { ProcessesService } from '../processes.service';
import { ToastService } from '../toast.service';
import { Camera, CameraResultType, CameraSource, Photo} from '@capacitor/camera';
import { Filesystem, Directory } from '@capacitor/filesystem';
import { environment } from 'src/environments/environment';
import { HttpClient, HttpEventType, HttpHeaders, HttpParams } from '@angular/common/http';
import { Storage } from '@ionic/storage';
import { Camera, CameraResultType, CameraSource} from '@capacitor/camera';
import { FileType } from 'src/app/models/fileType';
import { FileSystemService } from 'src/app/services/file-system.service';
const IMAGE_DIR = 'stored-images';
@@ -31,14 +27,12 @@ export class FileService {
images: LocalFile[] = [];
capturedImage:any;
capturedImageTitle:any;
documents:SearchList[] = [];
showLoader: boolean;
files: Set<File>;
photos: any[] = [];
idroom: any;
headers: HttpHeaders;
downloadProgess = 0;
downloadFilename: any;
@@ -50,54 +44,9 @@ export class FileService {
private modalController: ModalController,
private processesService: ProcessesService,
private toastService: ToastService,
private platform: Platform,
private loadingCtrl: LoadingController,
private http: HttpClient,
private storage: Storage
) {
this.headers = new HttpHeaders();
}
private FileSystemService: FileSystemService
) {}
uploadFile(formData:any){
console.log('UPLOAD file', formData)
//const geturl = environment.apiURL + 'Tasks/DelegateTask';
const geturl = environment.apiURL + 'ObjectServer/UploadFiles';
let options = {
headers: this.headers
};
return this.http.post(`${geturl}`, formData, options);
}
getFile(guid:any){
const geturl = environment.apiURL + 'lakefs/StreamFile';
let params = new HttpParams();
params = params.set("path", guid);
this.headers = this.headers.set('responseType', 'blob');
this.headers = this.headers.set('Content-Type', 'application/octet-stream');
let options = {
headers: this.headers,
params: params
};
return this.http.get<any>(`${geturl}`, options);
}
downloadFile(guid:any) {
let downloadUrl = environment.apiURL +'objectserver/streamfiles?path='+guid;
var name = new Date().getTime();
return this.http.get(downloadUrl, {
responseType: "arraybuffer",
reportProgress: true, observe: 'events'
})
}
_arrayBufferToBase64( buffer ) {
var binary = '';
@@ -110,32 +59,6 @@ export class FileService {
}
async takePicture() {
const capturedImage = await Camera.getPhoto({
quality: 90,
// allowEditing: true,
resultType: CameraResultType.Uri,
source: CameraSource.Camera
});
const response = await fetch(capturedImage.webPath!);
const blob = await response.blob();
this.photos.unshift({
filepath: "soon...",
webviewPath: capturedImage.webPath
});
this.capturedImage = await this.convertBlobToBase64(blob);
this.capturedImageTitle = new Date().getTime() + '.jpeg';
let data = {
image:this.capturedImage,
name: this.capturedImageTitle
}
return data;
}
convertBlobToBase64 = (blob: Blob) => new Promise((resolve, reject) => {
const reader = new FileReader;
@@ -169,166 +92,6 @@ export class FileService {
};
}
//new method1
async saveImage(photo: Photo, roomid: any) {
const base64Data = await this.readAsBase64(photo);
const fileName = new Date().getTime() + '.jpeg';
const savedFile = await Filesystem.writeFile({
path: `${IMAGE_DIR}/${fileName}`,
data: base64Data,
directory: Directory.Data
});
this.loadFiles(roomid);
}
//new method 2
private async readAsBase64(photo: Photo) {
if (this.platform.is('hybrid')) {
const file = await Filesystem.readFile({
path: photo.path
});
return file.data;
}
else {
// Fetch the photo, read as a blob, then convert to base64 format
const response = await fetch(photo.webPath);
const blob = await response.blob();
return await this.convertBlobToBase64(blob) as string;
}
}
//new method 3
async loadFiles(roomid) {
this.images = [];
const loading = await this.loadingCtrl.create({
message: 'Loading data...',
});
await loading.present();
Filesystem.readdir({
path: IMAGE_DIR,
directory: Directory.Data,
}).then(result => {
console.log('ALL RESULTS', result.files[0])
let lastphoto = result.files[result.files.length - 1]
this.loadFileData(lastphoto,roomid);
},
async (err) => {
console.log('ERROR FILE DOSENT EXIST', err)
// Folder does not yet exists!
await Filesystem.mkdir({
path: IMAGE_DIR,
directory: Directory.Data,
recursive: true
});
}
).then(_ => {
loading.dismiss();
});
}
//new method 4
async loadFileData(fileName: string, roomid: any) {
console.log('ALL PHOTOT FILE', fileName)
// for (let f of fileNames) {
const filePath = `${IMAGE_DIR}/${fileName}`;
const readFile = await Filesystem.readFile({
path: filePath,
directory: Directory.Data,
});
this.images.push({
name: fileName,
path: filePath,
data: `data:image/jpeg;base64,${readFile.data}`,
});
console.log('ALL IMAGE', this.images)
this.capturedImage = this.images[0].data
this.capturedImageTitle = new Date().getTime() + '.jpeg';
const base64 = await fetch(this.capturedImage);
const blob = await base64.blob();
const formData = new FormData();
formData.append("blobFile", blob);
console.log('ALL IMAGE', formData)
let guid: any = await this.uploadFile(formData).toPromise()
console.log(guid.path);
this.downloadFile(guid.path).subscribe(async (event) => {
if (event.type === HttpEventType.DownloadProgress) {
//this.downloadProgess = Math.round((100 * event.loaded) / event.total);
//console.log('FILE TYPE 33', msg.file.type)
} else if (event.type === HttpEventType.Response) {
var fileImage = 'data:image/jpeg;base64,' + btoa(new Uint8Array(event.body).reduce((data, byte) => data + String.fromCharCode(byte), ''));
console.log('add picture to chat',fileImage);
await this.storage.set(guid.path, fileImage).then(() => {
console.log('add picture to chat IMAGE SAVED')
let body = {
"message":
{
"rid": roomid,
"msg": "",
"attachments": [{
"title": this.capturedImageTitle,
"title_link_download": false,
"image_url": fileImage,
}],
"file":{
"type": "application/img",
"guid": guid.path,
"image_url": fileImage
}
}
}
console.log('BODY TAKE PICTURE CHAT', body)
const loader = this.toastService.loading();
this.chatService.sendMessage(body).subscribe(res=> {
console.log(res);
loader.remove();
},(error) => {
loader.remove();
this.toastService.badRequest("Não foi possível adicionar a fotografia!");
});
});
}
});
}
async addCameraPictureToChat(roomId){
console.log('add camera to picture')
const image = await Camera.getPhoto({
quality: 50,
allowEditing: false,
resultType: CameraResultType.Uri,
source: CameraSource.Camera // Camera, Photos or Prompt!
});
if (image) {
await this.saveImage(image,roomId)
} else {
console.log('Error saving image')
}
//this.capturedImage = this.capturedImage;
}
async addPictureToChatMobile(roomId) {
@@ -341,115 +104,11 @@ export class FileService {
});
if (capturedImage) {
await this.saveImage(capturedImage,roomId)
await this.FileSystemService.saveImage(capturedImage,roomId)
}
}
/* const response = await fetch(capturedImage.webPath!);
const blob = await response.blob();
this.photos.unshift({
filepath: "soon...",
webviewPath: capturedImage.webPath
});
this.capturedImage = await this.convertBlobToBase64(blob);
this.capturedImageTitle = new Date().getTime() + '.jpeg';
//const loader = this.toastService.loading();
let body = {
"message":
{
"rid": roomId,
"msg": "",
"attachments": [{
//"title": this.capturedImageTitle ,
//"text": "description",
"title_link_download": false,
"image_url": this.capturedImage,
}]
}
}
this.chatService.sendMessage(body).subscribe(res=> {
//loader.remove();
//console.log(res);
},(error) => {
//loader.remove();
});
*/ }
addPictureToChat(roomId) {
console.log('add picture to chat')
const input = this.fileLoaderService.createInput({
accept: ['image/apng', 'image/jpeg', 'image/png']
})
input.onchange = async () => {
//alert('Onchange AQUI')
const file = this.fileLoaderService.getFirstFile(input)
console.log('first file',file);
const formData = new FormData();
formData.append("blobFile", file);
let guid: any = await this.uploadFile(formData).toPromise()
console.log('ADD IMAGE FORM DATA', formData)
console.log('add picture to chat', guid.path);
this.downloadFile(guid.path).subscribe(async (event) => {
if (event.type === HttpEventType.DownloadProgress) {
//this.downloadProgess = Math.round((100 * event.loaded) / event.total);
//console.log('FILE TYPE 33', msg.file.type)
} else if (event.type === HttpEventType.Response) {
var fileImage = 'data:image/jpeg;base64,' + btoa(new Uint8Array(event.body).reduce((data, byte) => data + String.fromCharCode(byte), ''));
console.log('add picture to chat',fileImage);
await this.storage.set(guid.path, fileImage).then(() => {
console.log('add picture to chat IMAGE SAVED')
let body = {
"message":
{
"rid": roomId,
"msg": "",
"attachments": [{
//"title": this.capturedImageTitle ,
//"text": "description",
"title_link_download": false,
//"image_url": this.capturedImage,
}],
"file": {
"type": "application/img",
"guid": guid.path,
"image_url": fileImage
}
}
}
console.log('SELECT PICTURE GALLERY', body)
console.log(this.capturedImage)
this.chatService.sendMessage(body).subscribe(res => {
console.log('Msg after send image', res);
}, (error) => {
console.log('Msg after send image error', error);
});
});
}
});
/* const imageData = await this.fileToBase64Service.convert(file)
this.capturedImage = imageData; */
//console.log(this.capturedImage)
};
}
addDocumentToChat(roomId:string) {
const input = this.fileLoaderService.createInput({
@@ -475,67 +134,23 @@ export class FileService {
};
}
async addDocGestaoDocumentalToChat(roomId:string){
const modal = await this.modalController.create({
component: SearchPage,
cssClass: 'group-messages modal-desktop search-modal search-modal-to-desktop',
componentProps: {
type: 'AccoesPresidenciais & ArquivoDespachoElect',
select: true,
showSearchInput: true,
}
});
await modal.present();
modal.onDidDismiss().then(async res=>{
const data = res.data;
if(data.selected){
const loader = this.toastService.loading();
this.documents.push(data.selected);
console.log(res.data.selected);
console.log(res.data.selected.Id);
console.log(res.data.selected.ApplicationType);
let url = await this.processesService.GetDocumentUrl(res.data.selected.Id, res.data.selected.ApplicationType).toPromise();
let url_no_options: string = url.replace("webTRIX.Viewer","webTRIX.Viewer.Branch1");
console.log(url_no_options);
let body = {
"message":
{
"rid": roomId,
"msg": "",
"alias": "documento",
"attachments": [{
"title": res.data.selected.Assunto,
"description": res.data.selected.DocTypeDesc,
"title_link": url_no_options,
"title_link_download": true,
//"thumb_url": "assets/images/webtrix-logo.png",
"message_link": url_no_options,
"type": "webtrix"
}],
"file":{
"name": res.data.selected.Assunto,
"type": "application/webtrix",
"ApplicationId": res.data.selected.ApplicationType,
"DocId": res.data.selected.Id,
"Assunto": res.data.selected.Assunto,
}
}
}
this.chatService.sendMessage(body).subscribe(res=> {
loader.remove();
console.log(res);
},(error) => {
loader.remove();
});
loader.remove();
}
});
getFileFromDevice(types: typeof FileType[]) {
return new Promise<any>((resolve, reject)=>{
const input = this.fileLoaderService.createInput({
accept: types
})
input.onchange = async () => {
const file = this.fileLoaderService.getFirstFile(input)
resolve(file)
};
})
}
viewDocumentByUrl(url) {
const browser = this.iab.create(url,"_parent");
browser.show();
@@ -26,6 +26,12 @@ import { HttpEventType } from '@angular/common/http';
import { Storage } from '@ionic/storage';
import { WsChatMethodsService } from 'src/app/services/chat/ws-chat-methods.service';
import { MessageService } from 'src/app/services/chat/message.service';
import { AttachmentsService } from 'src/app/services/attachments.service';
import { FileSystemService } from 'src/app/services/file-system.service';
import { CameraService } from 'src/app/services/camera.service';
import { element } from 'protractor';
import { FileType } from 'src/app/models/fileType';
import { ToastService } from 'src/app/services/toast.service';
/*
import * as pdfjsLib from 'pdfjs-dist';
@@ -96,6 +102,10 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe
public ThemeService: ThemeService,
private changeDetectorRef: ChangeDetectorRef,
private storage: Storage,
private AttachmentsService: AttachmentsService,
private FileSystemService: FileSystemService,
private CameraService: CameraService,
private toastService: ToastService,
) {
console.log('OnCONSTRUCTOR');
@@ -656,18 +666,145 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe
await modal.present();
}
takePicture() {
this.fileService.addCameraPictureToChat(this.roomId);
async takePicture() {
const roomId = this.roomId
const image = await this.CameraService.takePicture();
await this.FileSystemService.saveImage(image, roomId)
const lastphoto: any = await this.FileSystemService.loadFiles(roomId);
const { capturedImage, capturedImageTitle} = await this.FileSystemService.loadFileData(lastphoto, roomId);
const base64 = await fetch(capturedImage);
const blob = await base64.blob();
const formData = new FormData();
formData.append("blobFile", blob);
console.log('ALL IMAGE', formData)
let guid: any = await this.AttachmentsService.uploadFile(formData).toPromise()
console.log(guid.path);
this.AttachmentsService.downloadFile(guid.path).subscribe(async (event) => {
if (event.type === HttpEventType.DownloadProgress) {
//this.downloadProgess = Math.round((100 * event.loaded) / event.total);
//console.log('FILE TYPE 33', msg.file.type)
} else if (event.type === HttpEventType.Response) {
var fileImage = 'data:image/jpeg;base64,' + btoa(new Uint8Array(event.body).reduce((data, byte) => data + String.fromCharCode(byte), ''));
console.log('add picture to chat',fileImage);
await this.storage.set(guid.path, fileImage).then(() => {
console.log('add picture to chat IMAGE SAVED')
this.wsChatMethodsService.getDmRoom(this.roomId).sendFile({
file: {
"type": "application/img",
"guid": guid.path,
"image_url": fileImage
},
attachments: [{
//"title": this.capturedImageTitle ,
//"text": "description",
"title_link_download": false,
//"image_url": this.capturedImage,
}]
})
});
}
});
}
addImage() {
this.fileService.addPictureToChat(this.roomId);
async addImage() {
this.addFileToChat(['image/apng', 'image/jpeg', 'image/png'])
}
addFile() {
this.fileService.addDocumentToChat(this.roomId);
async addFile() {
this.addFileToChat(['.doc', '.docx', '.pdf'])
}
addFileWebtrix() {
this.fileService.addDocGestaoDocumentalToChat(this.roomId);
async addFileWebtrix() {
const modal = await this.modalController.create({
component: SearchPage,
cssClass: 'group-messages modal-desktop search-modal search-modal-to-desktop',
componentProps: {
type: 'AccoesPresidenciais & ArquivoDespachoElect',
select: true,
showSearchInput: true,
}
});
await modal.present();
modal.onDidDismiss().then(async res=>{
const data = res.data;
if(data.selected){
const loader = this.toastService.loading();
let url = await this.processesService.GetDocumentUrl(res.data.selected.Id, res.data.selected.ApplicationType).toPromise();
let url_no_options: string = url.replace("webTRIX.Viewer","webTRIX.Viewer.Branch1");
console.log(url_no_options);
this.wsChatMethodsService.getDmRoom(this.roomId).sendFile({
alias: "documento",
file:{
"name": res.data.selected.Assunto,
"type": "application/webtrix",
"ApplicationId": res.data.selected.ApplicationType,
"DocId": res.data.selected.Id,
"Assunto": res.data.selected.Assunto,
},
attachments: [{
"title": res.data.selected.Assunto,
"description": res.data.selected.DocTypeDesc,
"title_link": url_no_options,
"title_link_download": true,
//"thumb_url": "assets/images/webtrix-logo.png",
"message_link": url_no_options,
"type": "webtrix"
}]
})
loader.remove();
}
});
}
async addFileToChat(types: typeof FileType[] ) {
const file = await this.fileService.getFileFromDevice(types);
const formData = new FormData();
formData.append("blobFile", file);
let guid: any = await this.AttachmentsService.uploadFile(formData).toPromise()
this.AttachmentsService.downloadFile(guid.path).subscribe(async (event) => {
if (event.type === HttpEventType.DownloadProgress) {
//this.downloadProgess = Math.round((100 * event.loaded) / event.total);
//console.log('FILE TYPE 33', msg.file.type)
} else if (event.type === HttpEventType.Response) {
var fileImage = 'data:image/jpeg;base64,' + btoa(new Uint8Array(event.body).reduce((data, byte) => data + String.fromCharCode(byte), ''));
console.log('add picture to chat',fileImage);
await this.storage.set(guid.path, fileImage).then(() => {
console.log('add picture to chat IMAGE SAVED')
this.wsChatMethodsService.getDmRoom(this.roomId).sendFile({
file: {
"type": "application/img",
"guid": guid.path,
"image_url": fileImage
},
attachments: [{
//"title": this.capturedImageTitle ,
//"text": "description",
"title_link_download": false,
//"image_url": this.capturedImage,
}]
})
});
}
});
}
bookMeeting() {
let data = {
roomId: this.roomId,
@@ -693,7 +830,7 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe
return this.animationController.create()
.addElement(baseEl)
.easing('ease-out')
.duration(5000)
.duration(500)
.addAnimation([backdropAnimation, wrapperAnimation]);
}
@@ -711,10 +848,11 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe
members: this.members,
}
});
await modal.present();
modal.onDidDismiss().then((res) => {
//console.log(res['data']);
modal.onDidDismiss().then( async (res) => {
console.log(res['data']);
const roomId = this.roomId;
if (res['data'] == 'meeting') {
//this.closeAllDesktopComponents.emit();
let data = {
@@ -724,21 +862,67 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe
this.openNewEventPage.emit(data);
}
else if (res['data'] == 'take-picture') {
this.fileService.addCameraPictureToChat(this.roomId);
//this.loadPicture();
const image = await this.CameraService.takePicture();
await this.FileSystemService.saveImage(image, roomId)
const lastphoto: any = await this.FileSystemService.loadFiles(roomId);
const { capturedImage, capturedImageTitle} = await this.FileSystemService.loadFileData(lastphoto, roomId);
const base64 = await fetch(capturedImage);
const blob = await base64.blob();
const formData = new FormData();
formData.append("blobFile", blob);
console.log('ALL IMAGE', formData)
let guid: any = await this.AttachmentsService.uploadFile(formData).toPromise()
console.log(guid.path);
this.AttachmentsService.downloadFile(guid.path).subscribe(async (event) => {
if (event.type === HttpEventType.DownloadProgress) {
//this.downloadProgess = Math.round((100 * event.loaded) / event.total);
//console.log('FILE TYPE 33', msg.file.type)
} else if (event.type === HttpEventType.Response) {
var fileImage = 'data:image/jpeg;base64,' + btoa(new Uint8Array(event.body).reduce((data, byte) => data + String.fromCharCode(byte), ''));
console.log('add picture to chat',fileImage);
await this.storage.set(guid.path, fileImage).then(() => {
console.log('add picture to chat IMAGE SAVED')
this.wsChatMethodsService.getDmRoom(this.roomId).sendFile({
file: {
"type": "application/img",
"guid": guid.path,
"image_url": fileImage
},
attachments: [{
//"title": this.capturedImageTitle ,
//"text": "description",
"title_link_download": false,
//"image_url": this.capturedImage,
}]
})
});
}
});
}
else if (res['data'] == 'add-picture') {
this.fileService.addPictureToChat(this.roomId);
//this.loadPicture();
this.addImage()
}
else if (res['data'] == 'add-document') {
this.loadDocument();
this.addFile()
}
else if (res['data'] == 'documentoGestaoDocumental') {
this.fileService.addDocGestaoDocumentalToChat(this.roomId);
//this.addDocGestaoDocumental();
this.addFileWebtrix()
this.showLoader = false;
}
this.loadGroupMessages(this.roomId);
});
}
@@ -790,7 +974,7 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe
console.log('FILE TYPE', msg.file.type)
this.downloadFile = "";
if (msg.file.type == "application/img") {
this.fileService.downloadFile(msg.file.guid).subscribe(async (event) => {
this.AttachmentsService.downloadFile(msg.file.guid).subscribe(async (event) => {
console.log('FILE TYPE 22', msg.file.guid)
var name = msg.file.guid;
+170 -73
View File
@@ -26,7 +26,12 @@ import { Storage } from '@ionic/storage';
import { WsChatMethodsService } from 'src/app/services/chat/ws-chat-methods.service'
import { WsChatService } from 'src/app/services/chat/ws-chat.service'
import { MessageService } from 'src/app/services/chat/message.service';
import { element } from 'protractor';
import { AttachmentsService } from 'src/app/services/attachments.service';
import { FileSystemService } from 'src/app/services/file-system.service';
import { CameraService } from 'src/app/services/camera.service';
import { FileType } from 'src/app/models/fileType';
import { SearchPage } from 'src/app/pages/search/search.page';
import { ProcessesService } from 'src/app/services/processes.service';
const IMAGE_DIR = 'stored-images';
@Component({
@@ -92,7 +97,11 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
private router: Router,
private storage: Storage,
public wsChatMethodsService: WsChatMethodsService,
public WsChatService: WsChatService
public WsChatService: WsChatService,
private AttachmentsService: AttachmentsService,
private FileSystemService: FileSystemService,
private CameraService: CameraService,
private processesService: ProcessesService,
) {
this.loggedUser = authService.ValidatedUserChat['data'];
@@ -113,7 +122,6 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
ngOnInit() {
this.scrollToBottom();
this.setStatus('online');
}
@@ -133,15 +141,6 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
});
}
setStatus(status: string) {
let body = {
message: '',
status: status,
}
this.chatService.setUserStatus(body).subscribe(res => {
console.log(res);
})
}
notImplemented() {
this.alertService.presentAlert('Funcionalidade em desenvolvimento');
@@ -149,7 +148,6 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
load = () => {
this.checktimeOut = true;
this.serverLongPull();
this.getChatMembers();
}
@@ -204,7 +202,6 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
ngOnDestroy() {
this.checktimeOut = false;
this.setStatus('away');
window.removeEventListener('scroll', this.scrollChangeCallback, true);
}
@@ -250,7 +247,7 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
async viewDocument(msg: any, url?: string) {
if (msg.file.type == "application/img") {
let response: any = await this.fileService.getFile(msg.file.guid).toPromise();
let response: any = await this.AttachmentsService.getFile(msg.file.guid).toPromise();
console.log(response);
alert(response);
@@ -266,7 +263,7 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
//fullUrl = "http://www.africau.edu/images/default/sample.pdf";
this.frameUrl = fullUrl;
//this.fileService.viewDocumentByUrl(fullUrl);
this.chatService.getDocumentDetails(fullUrl);
}
}
@@ -438,22 +435,147 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
takePicture() {
async takePicture() {
const roomId = this.roomId
this.fileService.addCameraPictureToChat(roomId);
const image = await this.CameraService.takePicture();
await this.FileSystemService.saveImage(image, roomId)
const lastphoto: any = await this.FileSystemService.loadFiles(roomId);
const { capturedImage, capturedImageTitle} = await this.FileSystemService.loadFileData(lastphoto, roomId);
const base64 = await fetch(capturedImage);
const blob = await base64.blob();
const formData = new FormData();
formData.append("blobFile", blob);
console.log('ALL IMAGE', formData)
let guid: any = await this.AttachmentsService.uploadFile(formData).toPromise()
console.log(guid.path);
this.AttachmentsService.downloadFile(guid.path).subscribe(async (event) => {
if (event.type === HttpEventType.DownloadProgress) {
//this.downloadProgess = Math.round((100 * event.loaded) / event.total);
//console.log('FILE TYPE 33', msg.file.type)
} else if (event.type === HttpEventType.Response) {
var fileImage = 'data:image/jpeg;base64,' + btoa(new Uint8Array(event.body).reduce((data, byte) => data + String.fromCharCode(byte), ''));
console.log('add picture to chat',fileImage);
await this.storage.set(guid.path, fileImage).then(() => {
console.log('add picture to chat IMAGE SAVED')
});
this.wsChatMethodsService.getDmRoom(this.roomId).sendFile({
alias: 'document',
file: {
"type": "application/img",
"guid": guid.path,
"image_url": fileImage
},
attachments: [{
//"title": this.capturedImageTitle ,
//"text": "description",
"title_link_download": false,
//"image_url": this.capturedImage,
}]
})
}
});
}
addImage() {
const roomId = this.roomId;
this.fileService.addPictureToChat(roomId);
//this.fileService.loadPicture();
//this.fileService.addPictureToChat(roomId);
async addImage() {
this.addFileToChat(['image/apng', 'image/jpeg', 'image/png'])
}
addFile() {
this.fileService.addDocumentToChat(this.roomId);
async addFile() {
this.addFileToChat(['.doc', '.docx', '.pdf'])
}
addFileWebtrix() {
this.fileService.addDocGestaoDocumentalToChat(this.roomId);
async addFileWebtrix() {
const modal = await this.modalController.create({
component: SearchPage,
cssClass: 'group-messages modal-desktop search-modal search-modal-to-desktop',
componentProps: {
type: 'AccoesPresidenciais & ArquivoDespachoElect',
select: true,
showSearchInput: true,
}
});
await modal.present();
modal.onDidDismiss().then(async res=>{
const data = res.data;
if(data.selected){
const loader = this.toastService.loading();
let url = await this.processesService.GetDocumentUrl(res.data.selected.Id, res.data.selected.ApplicationType).toPromise();
let url_no_options: string = url.replace("webTRIX.Viewer","webTRIX.Viewer.Branch1");
console.log(url_no_options);
this.wsChatMethodsService.getDmRoom(this.roomId).sendFile({
alias: "documento",
file:{
"name": res.data.selected.Assunto,
"type": "application/webtrix",
"ApplicationId": res.data.selected.ApplicationType,
"DocId": res.data.selected.Id,
"Assunto": res.data.selected.Assunto,
},
attachments: [{
"title": res.data.selected.Assunto,
"description": res.data.selected.DocTypeDesc,
"title_link": url_no_options,
"title_link_download": true,
//"thumb_url": "assets/images/webtrix-logo.png",
"message_link": url_no_options,
"type": "webtrix"
}]
})
loader.remove();
}
});
}
async addFileToChat(types: typeof FileType[] ) {
const file = await this.fileService.getFileFromDevice(types);
const formData = new FormData();
formData.append("blobFile", file);
let guid: any = await this.AttachmentsService.uploadFile(formData).toPromise()
this.AttachmentsService.downloadFile(guid.path).subscribe(async (event) => {
if (event.type === HttpEventType.DownloadProgress) {
//this.downloadProgess = Math.round((100 * event.loaded) / event.total);
//console.log('FILE TYPE 33', msg.file.type)
} else if (event.type === HttpEventType.Response) {
var fileImage = 'data:image/jpeg;base64,' + btoa(new Uint8Array(event.body).reduce((data, byte) => data + String.fromCharCode(byte), ''));
console.log('add picture to chat',fileImage);
await this.storage.set(guid.path, fileImage).then(() => {
console.log('add picture to chat IMAGE SAVED')
this.wsChatMethodsService.getDmRoom(this.roomId).sendFile({
file: {
"type": "application/img",
"guid": guid.path,
"image_url": fileImage
},
attachments: [{
//"title": this.capturedImageTitle ,
//"text": "description",
"title_link_download": false,
//"image_url": this.capturedImage,
}]
})
});
}
});
}
bookMeeting() {
let data = {
roomId: this.roomId,
@@ -463,7 +585,13 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
}
chatSendFile() {
}
async _openChatOptions() {
const roomId = this.roomId;
const enterAnimation = (baseEl: any) => {
const backdropAnimation = this.animationController.create()
@@ -499,8 +627,10 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
}
});
await modal.present();
modal.onDidDismiss().then((res) => {
modal.onDidDismiss().then( async (res) => {
console.log(res['data']);
if (res['data'] == 'meeting') {
//this.closeAllDesktopComponents.emit();
let data = {
@@ -510,63 +640,30 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
this.openNewEventPage.emit(data);
}
else if (res['data'] == 'take-picture') {
this.fileService.addCameraPictureToChat(this.roomId);
//this.loadPicture();
this.takePicture()
}
else if (res['data'] == 'add-picture') {
this.fileService.addPictureToChat(this.roomId);
//this.loadPicture();
this.addImage()
}
else if (res['data'] == 'add-document') {
this.fileService.addDocumentToChat(this.roomId);
//this.loadDocument();
this.addFile()
}
else if (res['data'] == 'documentoGestaoDocumental') {
this.fileService.addDocGestaoDocumentalToChat(this.roomId);
this.addFileWebtrix()
this.showLoader = false;
//this.addDocGestaoDocumental();
}
});
}
async serverLongPull() {
const roomId = this.roomId;
this.chatService.getRoomMessages(this.roomId).subscribe(async res => {
console.log('serverLongPull', res['success']);
if (res['success'] == true) {
// Show Error
//showMessage(response.statusText);
/* this.messages = res['messages'].reverse();
this.chatMessageStore.add(roomId, this.messages) */
console.log('MSG FROM ROCKET ', res['messages'].reverse())
/* this.transformData(res['messages'].reverse());
this.getMessageDB(); */
//console.log(this.messages);
// Reconnect in one second
if (this.route.url != "/home/chat") {
console.log("Timer message stop")
}
else {
if (document.querySelector('app-messages')) {
await new Promise(resolve => setTimeout(resolve, 5000));
// await this.serverLongPull();
this.getDirectMessages.emit();
console.log('Timer message running')
}
}
}
}, (error) => {
console.log(error);
});
}
sliderOpts = {
zoom: false,
@@ -614,7 +711,7 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy
console.log('FILE TYPE', msg.file.type)
this.downloadFile = "";
if (msg.file.type == "application/img") {
this.fileService.downloadFile(msg.file.guid).subscribe(async (event) => {
this.AttachmentsService.downloadFile(msg.file.guid).subscribe(async (event) => {
console.log('FILE TYPE 22', msg.file.guid)
var name = msg.file.guid;