diff --git a/src/app/pages/publications/view-publications/view-publications.page.ts b/src/app/pages/publications/view-publications/view-publications.page.ts index f81eb7b19..0c1b04246 100644 --- a/src/app/pages/publications/view-publications/view-publications.page.ts +++ b/src/app/pages/publications/view-publications/view-publications.page.ts @@ -68,7 +68,7 @@ export class ViewPublicationsPage implements OnInit { if (typeof (this.folderId) == 'object') { this.folderId = this.folderId['ProcessId'] } - this.testForkJoin() + //this.testForkJoin() this.getPublicationDetail(); setTimeout(() => { this.getPublicationsIds(); @@ -76,7 +76,7 @@ export class ViewPublicationsPage implements OnInit { this.backgroundservice.registerBackService('Online', () => { this.getPublicationDetail(); - this.testForkJoin() + //this.testForkJoin() }) @@ -91,16 +91,16 @@ export class ViewPublicationsPage implements OnInit { // if (typeof (this.id == 'object') { // this.id = this.id['ProcessId'] // } - this.testForkJoin() + //this.testForkJoin() this.getPublicationDetail(); // this.getPublicationsIds(); } doRefresh = (event) => { setTimeout(() => { - this.testForkJoin() + //this.testForkJoin() this.getPublicationDetail(); - // this.getPublicationsIds(); + this.getPublicationsIds(); event.target.complete(); }, 3000); @@ -116,13 +116,13 @@ export class ViewPublicationsPage implements OnInit { } getPublicationDetail() { - this.publications.GetPresidentialAction(this.folderId).subscribe(res=>{ + this.publications.GetPresidentialAction(this.folderId).subscribe(res => { console.log(res); this.item = res; }); } -// goes to fork + // goes to fork // getPublicationsIds() { // this.showLoader = true; @@ -138,20 +138,20 @@ export class ViewPublicationsPage implements OnInit { this.showLoader = true; const folderId = this.folderId - + this.getFromDB() this.publications.GetPublicationsImages(this.folderId).subscribe(res => { console.log('publications ids', res) this.publicationList = new Array(); - /* for(let i of res) { - this.publications.GetPublicationById(i).subscribe(ress => { - console.log('publications by ids', ress) - let item: Publication = this.publicationPipe.itemList(ress) - console.log('publications by ids 2', item) - this.publicationList.push(item); - }) - } */ + /* for(let i of res) { + this.publications.GetPublicationById(i).subscribe(ress => { + console.log('publications by ids', ress) + let item: Publication = this.publicationPipe.itemList(ress) + console.log('publications by ids 2', item) + this.publicationList.push(item); + }) + } */ res.forEach(element => { console.log('publications elements', element) @@ -168,7 +168,6 @@ export class ViewPublicationsPage implements OnInit { this.publicationListStorage.add(folderId, this.publicationList) this.getpublication = this.publicationList; - this.showLoader = false; /* this.publicationList = new Array(); @@ -189,7 +188,7 @@ export class ViewPublicationsPage implements OnInit { this.showLoader = true; const folderId = this.folderId - + this.getFromDB(); this.publications.GetPublications(this.folderId).subscribe(res => { console.log(this.folderId) @@ -223,13 +222,13 @@ export class ViewPublicationsPage implements OnInit { }); } - testForkJoin(){ + testForkJoin() { forkJoin([ this.getPublicationsIds(), this.getPublications(), - ]).subscribe(allResults =>{ + ]).subscribe(allResults => { this.publicationList = allResults[2] }) } diff --git a/src/app/services/chat/ws-chat-methods.service.ts b/src/app/services/chat/ws-chat-methods.service.ts index 0cfbf8608..6cc607027 100644 --- a/src/app/services/chat/ws-chat-methods.service.ts +++ b/src/app/services/chat/ws-chat-methods.service.ts @@ -40,11 +40,21 @@ export class WsChatMethodsService { } + getRoomFromDb() { + this.storage.get('Rooms').then((rooms) => { + rooms.result.update.forEach((roomData: room) => { + this.prepareRoom(roomData); + }); + }) + }; + async getAllRooms () { this.loadingWholeList = true - + this.getRoomFromDb(); const rooms = await this.WsChatService.getRooms(); + this.storage.set('Rooms', rooms); + // console.log("ROOMS" + JSON.stringify(rooms)) rooms.result.update.forEach((roomData: room) => { diff --git a/src/app/shared/shared.module.ts b/src/app/shared/shared.module.ts index 42f4c4c87..ce95737f1 100644 --- a/src/app/shared/shared.module.ts +++ b/src/app/shared/shared.module.ts @@ -2,6 +2,7 @@ import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { IonicModule } from '@ionic/angular'; +import { IonicImageLoaderModule } from 'ionic-image-loader-v5'; // import { HeaderPage } from './header/header.page'; // import { HeaderPrPage } from './header-pr/header-pr.page'; // import { BtnSeguintePage } from './btn-seguinte/btn-seguinte.page'; @@ -17,7 +18,8 @@ import { IonicModule } from '@ionic/angular'; imports: [ CommonModule, FormsModule, - IonicModule + IonicModule, + IonicImageLoaderModule ], exports: [ // HeaderPage, From 58e969826474a0794eec209e560bb0f4eb4d87b4 Mon Sep 17 00:00:00 2001 From: Peter Maquiran Date: Mon, 31 Jan 2022 15:01:41 +0100 Subject: [PATCH 02/27] resubcribe on reconnect --- src/app/services/chat/ws-chat.service.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/app/services/chat/ws-chat.service.ts b/src/app/services/chat/ws-chat.service.ts index 3abc1ae4e..845a02ba1 100644 --- a/src/app/services/chat/ws-chat.service.ts +++ b/src/app/services/chat/ws-chat.service.ts @@ -380,7 +380,7 @@ export class WsChatService { ] } - this.ws.send({message, requestId}) + this.ws.send({message, requestId: 'loadHistory'}) return new Promise((resolve, reject) => { this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ From 629b8a71c7d585affb48f36b562cec8035da0c8d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eudes=20In=C3=A1cio?= Date: Mon, 31 Jan 2022 15:02:26 +0100 Subject: [PATCH 03/27] Offline web almost done --- src/app/pages/agenda/agenda.page.ts | 69 +++++++++--- .../agenda/view-event/view-event.page.ts | 66 ++++++----- src/app/pages/events/events.page.ts | 27 ++++- .../gabinete-digital/gabinete-digital.page.ts | 105 ++++++++++++------ 4 files changed, 192 insertions(+), 75 deletions(-) diff --git a/src/app/pages/agenda/agenda.page.ts b/src/app/pages/agenda/agenda.page.ts index e67e9bf0c..a851161b5 100644 --- a/src/app/pages/agenda/agenda.page.ts +++ b/src/app/pages/agenda/agenda.page.ts @@ -9,6 +9,7 @@ import { momentG } from 'src/plugin/momentG'; import { DomSanitizer } from "@angular/platform-browser"; import { EventPerson } from 'src/app/models/eventperson.model'; import { removeDuplicate } from 'src/plugin/removeDuplicate.js'; +import { Storage } from '@ionic/storage'; // showTimeline import { setHours, setMinutes } from 'date-fns'; @@ -179,7 +180,8 @@ export class AgendaPage implements OnInit { private sqliteservice: SqliteService, private platform: Platform, private backgroundservice: BackgroundService, - public ThemeService: ThemeService + public ThemeService: ThemeService, + private storage:Storage ) { this.dateAdapter.setLocale('es'); @@ -770,6 +772,27 @@ export class AgendaPage implements OnInit { addEventToDB(response, profile) { if (this.platform.is('desktop') || this.platform.is('mobileweb')) { + let responseArray = []; + response.forEach(element => { + let event = { + CalendarId: element.CalendarId, + CalendarName: element.CalendarName, + EndDate: element.EndDate, + EventId: element.EventId, + HasAttachments: element.HasAttachments, + HumanDate: element.HumanDate, + IsAllDayEvent: element.IsAllDayEvent, + Location: element.Location, + StartDate: element.StartDate, + Subject: element.Subject, + Profile: profile + } + responseArray.push(event) + + }); + this.storage.set('agendaResponse',responseArray).then(() => { + console.log('Agenda data saved') + }) } else { if (response.length > 0) { @@ -796,21 +819,35 @@ export class AgendaPage implements OnInit { getFromDB() { console.log('ALL EVENTS FROM DB AGENDA OFFLINE') - this.sqliteservice.getAllEvents().then((events: any[]) => { - console.log('ALL EVENTS FROM DB', events) - let eventArray = []; - - this.trasnformDataDB(events) - this.updateEventListBox() - - this.myCal.update(); - this.myCal.loadEvents(); - - this.showLoader = false; - this.showTimeline = true; - - - }) + if (this.platform.is('desktop') || this.platform.is('mobileweb')) { + this.storage.get('agendaResponse').then((events) => { + this.trasnformDataDB(events) + this.updateEventListBox() + + this.myCal.update(); + this.myCal.loadEvents(); + + this.showLoader = false; + this.showTimeline = true; + }) + } else { + this.sqliteservice.getAllEvents().then((events: any[]) => { + console.log('ALL EVENTS FROM DB', events) + let eventArray = []; + + this.trasnformDataDB(events) + this.updateEventListBox() + + this.myCal.update(); + this.myCal.loadEvents(); + + this.showLoader = false; + this.showTimeline = true; + + + }) + } + } updateEventListBox() { diff --git a/src/app/pages/agenda/view-event/view-event.page.ts b/src/app/pages/agenda/view-event/view-event.page.ts index 4175b8b86..4c9c36f76 100644 --- a/src/app/pages/agenda/view-event/view-event.page.ts +++ b/src/app/pages/agenda/view-event/view-event.page.ts @@ -21,6 +21,7 @@ import { BackgroundService } from 'src/app/services/background.service'; import { StorageService } from 'src/app/services/storage.service'; import { ThemeService } from 'src/app/services/theme.service' import { RouteService } from 'src/app/services/route.service'; +import { Storage } from '@ionic/storage'; @Component({ @@ -74,6 +75,7 @@ export class ViewEventPage implements OnInit { private storage: StorageService, public ThemeService: ThemeService, private RouteService: RouteService, + private ionicStorage: Storage ) { this.isEventEdited = false; this.loadedEvent = new Event(); @@ -394,6 +396,9 @@ export class ViewEventPage implements OnInit { addEventToDb(data) { if (this.platform.is('desktop') || this.platform.is('mobileweb')) { + this.ionicStorage.set('eventDetails', data).then(() => { + console.log('Details event saved') + }) } else { let event = { Attendees: JSON.stringify(data.Attendees) || JSON.stringify(''), @@ -423,33 +428,40 @@ export class ViewEventPage implements OnInit { getFromDb() { const loader = this.toastService.loading(); - this.sqliteservice.getEventById(this.eventId).then((event) => { - let arrayevent = []; - console.log('EVENT ATTENDEES',event[0].Attendees) - let elemet = { - Attendees: (typeof JSON.parse(event[0].Attendees) === 'undefined') ? "" : JSON.parse(event[0].Attendees), - Body: JSON.parse(event[0].Body) || "", - CalendarId: event[0].CalendarId, - CalendarName: event[0].CalendarName, - Category: event[0].Category, - EndDate: event[0].EndDate, - EventId: event[0].EventId, - EventRecurrence: JSON.parse(event[0].EventRecurrence) || "", - EventType: event[0].EventType, - HasAttachments: event[0].HasAttachments, - IsAllDayEvent: event[0].IsAllDayEvent, - IsMeeting: event[0].IsMeeting, - IsRecurring: event[0].IsRecurring, - Location: event[0].Location, - Organizer: JSON.parse(event[0].Organizer) || "", - StartDate: event[0].StartDate, - Subject: event[0].Subject, - TimeZone: event[0].TimeZone - } - arrayevent.push(elemet); - this.loadedEvent = arrayevent[0]; - console.log("Event ditails local,", elemet) - }) + if (this.platform.is('desktop') || this.platform.is('mobileweb')) { + this.ionicStorage.get('eventDetails').then((events) =>{ + this.loadedEvent = events; + }) + } else { + this.sqliteservice.getEventById(this.eventId).then((event) => { + let arrayevent = []; + console.log('EVENT ATTENDEES',event[0].Attendees) + let elemet = { + Attendees: (typeof JSON.parse(event[0].Attendees) === 'undefined') ? "" : JSON.parse(event[0].Attendees), + Body: JSON.parse(event[0].Body) || "", + CalendarId: event[0].CalendarId, + CalendarName: event[0].CalendarName, + Category: event[0].Category, + EndDate: event[0].EndDate, + EventId: event[0].EventId, + EventRecurrence: JSON.parse(event[0].EventRecurrence) || "", + EventType: event[0].EventType, + HasAttachments: event[0].HasAttachments, + IsAllDayEvent: event[0].IsAllDayEvent, + IsMeeting: event[0].IsMeeting, + IsRecurring: event[0].IsRecurring, + Location: event[0].Location, + Organizer: JSON.parse(event[0].Organizer) || "", + StartDate: event[0].StartDate, + Subject: event[0].Subject, + TimeZone: event[0].TimeZone + } + arrayevent.push(elemet); + this.loadedEvent = arrayevent[0]; + console.log("Event ditails local,", elemet) + }) + } + loader.remove() } } diff --git a/src/app/pages/events/events.page.ts b/src/app/pages/events/events.page.ts index 056d5c9d8..e4055a9a8 100644 --- a/src/app/pages/events/events.page.ts +++ b/src/app/pages/events/events.page.ts @@ -21,6 +21,7 @@ import { NetworkConnectionService } from 'src/app/services/network-connection.se import { BackgroundService } from 'src/app/services/background.service'; import { momentG } from 'src/plugin/momentG'; import { ThemeService } from 'src/app/services/theme.service' +import { Storage } from '@ionic/storage'; @Component({ selector: 'app-events', templateUrl: './events.page.html', @@ -95,7 +96,8 @@ export class EventsPage implements OnInit { private sqliteservice: SqliteService, private networkconnection: NetworkConnectionService, private backgroundservice: BackgroundService, - public ThemeService: ThemeService + public ThemeService: ThemeService, + private storage: Storage ) { /* this.existingScreenOrientation = this.screenOrientation.type; console.log(this.existingScreenOrientation); */ @@ -317,6 +319,9 @@ export class EventsPage implements OnInit { addEventToDb(list) { if (this.platform.is('desktop') || this.platform.is('mobileweb')) { + this.storage.set('events', list).then(() => { + console.log('Init events saved') + }) } else { if (list.length > 0) { list.forEach(element => { @@ -359,6 +364,9 @@ export class EventsPage implements OnInit { addProcessToDb(list) { if (this.platform.is('desktop') || this.platform.is('mobileweb')) { + this.storage.set('process', list).then(() => { + console.log('Init process saved') + }) } else { if (list.length > 0) { list.forEach(element => { @@ -376,6 +384,23 @@ export class EventsPage implements OnInit { let dateToday = date.getFullYear() + "-" + month + "-" + date.getDate(); console.log('dateeeeee', dateToday) if (this.platform.is('desktop') || this.platform.is('mobileweb')) { + this.storage.get('events').then((events: any[]) => { + console.log('Today events',events) + let todayEvents = new Array() + this.listToPresent = events + this.totalEvent = this.listToPresent.length + this.currentEvent = this.listToPresent[0].Subject + this.currentHoursMinutes = this.listToPresent[0].StartDate + console.log("All events from local,", events) + }) + + this.storage.get('process').then((process: any[]) => { + console.log('OFOFOFOOF22222', process) + const ExpedienteTask = process.map(e => this.expedienteTaskPipe.transform(e)) + this.listToPresentexpediente = ExpedienteTask; + }) + + this.showLoader = false; } else { this.sqliteservice.getAllEvents().then((event: any[]) => { diff --git a/src/app/pages/gabinete-digital/gabinete-digital.page.ts b/src/app/pages/gabinete-digital/gabinete-digital.page.ts index c3c98059d..285af08d2 100644 --- a/src/app/pages/gabinete-digital/gabinete-digital.page.ts +++ b/src/app/pages/gabinete-digital/gabinete-digital.page.ts @@ -31,6 +31,7 @@ import { Platform } from '@ionic/angular'; import { BackgroundService } from 'src/app/services/background.service'; import { SortService } from 'src/app/services/functions/sort.service'; import { DataService } from 'src/app/services/data.service'; +import { Storage } from '@ionic/storage'; @Component({ selector: 'app-gabinete-digital', @@ -135,6 +136,7 @@ export class GabineteDigitalPage implements OnInit, DoCheck { public ThemeService: ThemeService, private sortService: SortService, private dataService: DataService, + private storage: Storage ) { this.loggeduser = authService.ValidatedUser; @@ -215,7 +217,9 @@ export class GabineteDigitalPage implements OnInit, DoCheck { addProcessToDB(data) { this.platform.ready().then(() => { if (this.platform.is('desktop') || this.platform.is('mobileweb')) { - + this.storage.set('GabineteProcess', data).then(() => { + console.log('Gabinete process saved') + }) } else { data.forEach(element => { @@ -245,39 +249,77 @@ export class GabineteDigitalPage implements OnInit, DoCheck { getAllProcessFromDB() { this.hideRefreshButton(); + if (this.platform.is('desktop') || this.platform.is('mobileweb')) { + this.storage.get('GabineteProcess').then((allprocess: any[]) => { + console.log('ALL PROCESS WEB',allprocess ) + allprocess.forEach(element => { + let date = new Date(element.taskStartDate); + date.setMonth(date.getMonth() + 1); + let taskDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds(); + + let task = { + "SerialNumber": element.serialNumber, + "Folio": element.workflowInstanceDataFields.Subject, + "Senders": element.workflowInstanceDataFields.Sender, + //"CreateDate": taskDate, + "CreateDate": new Date(element.taskStartDate), + "DocumentURL": element.workflowInstanceDataFields.ViewerRequest, + "Remetente": element.workflowInstanceDataFields.Remetente, + "DocumentsQty": element.totalDocuments, + "DocId": element.workflowInstanceDataFields.DispatchDocId, + "FolderID": element.workflowInstanceDataFields.FolderID, + "WorkflowName": element.workflowDisplayName, + "activityInstanceName": element.activityInstanceName, + "Status": element.workflowInstanceDataFields.Status, + "Agenda": element.workflowInstanceDataFields.Agenda, + "customDate": this.setFormatDate(new Date(element.workflowInstanceDataFields.StartDate), new Date(element.workflowInstanceDataFields.EndDate), element.workflowInstanceDataFields.IsAllDayEvent), + } + + this.allProcessesList.push(task); + this.allProcessesList = removeDuplicate(this.allProcessesList); + this.allProcessesList = this.sortService.sortDate(this.allProcessesList, 'CreateDate') + + }); + }) + } else { + this.sqliteservice.getAllProcess().then((allprocess: any[]) => { + allprocess.forEach(element => { + let date = new Date(element.taskStartDate); + date.setMonth(date.getMonth() + 1); + let taskDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds(); + + var workflowInstanceDataFields = JSON.parse(element.workflowInstanceDataFields); + + let task = { + "SerialNumber": element.serialNumber, + "Folio": workflowInstanceDataFields.Subject, + "Senders": workflowInstanceDataFields.Sender, + "CreateDate": taskDate, + "DocumentURL": workflowInstanceDataFields.ViewerRequest, + "Remetente": workflowInstanceDataFields.Remetente, + "DocumentsQty": element.totalDocuments, + "DocId": workflowInstanceDataFields.DispatchDocId, + "FolderID": workflowInstanceDataFields.FolderID, + "WorkflowName": element.workflowDisplayName, + "activityInstanceName": element.activityInstanceName, + "Status": workflowInstanceDataFields.Status, + "Agenda": workflowInstanceDataFields.Agenda, + "customDate": this.setFormatDate(new Date(workflowInstanceDataFields.StartDate), new Date(workflowInstanceDataFields.EndDate), workflowInstanceDataFields.IsAllDayEvent), + } + + this.allProcessesList.push(task); + this.allProcessesList = removeDuplicate(this.allProcessesList) + this.allProcessesList = this.sortService.sortDate(this.allProcessesList, 'CreateDate') + + }); + console.log("All process from db ", allprocess) + }) + } - this.sqliteservice.getAllProcess().then((allprocess: any[]) => { - allprocess.forEach(element => { - let date = new Date(element.taskStartDate); - date.setMonth(date.getMonth() + 1); - let taskDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds(); + } - var workflowInstanceDataFields = JSON.parse(element.workflowInstanceDataFields); + dataTranform(data) { - let task = { - "SerialNumber": element.serialNumber, - "Folio": workflowInstanceDataFields.Subject, - "Senders": workflowInstanceDataFields.Sender, - "CreateDate": taskDate, - "DocumentURL": workflowInstanceDataFields.ViewerRequest, - "Remetente": workflowInstanceDataFields.Remetente, - "DocumentsQty": element.totalDocuments, - "DocId": workflowInstanceDataFields.DispatchDocId, - "FolderID": workflowInstanceDataFields.FolderID, - "WorkflowName": element.workflowDisplayName, - "activityInstanceName": element.activityInstanceName, - "Status": workflowInstanceDataFields.Status, - "Agenda": workflowInstanceDataFields.Agenda, - "customDate": this.setFormatDate(new Date(workflowInstanceDataFields.StartDate), new Date(workflowInstanceDataFields.EndDate), workflowInstanceDataFields.IsAllDayEvent), - } - - this.allProcessesList.push(task); - this.allProcessesList = removeDuplicate(this.allProcessesList) - this.allProcessesList = this.sortService.sortDate(this.allProcessesList, 'CreateDate') - - }); - console.log("All process from db ", allprocess) - }) } sortArrayISODate(myArray: any) { @@ -495,6 +537,7 @@ export class GabineteDigitalPage implements OnInit, DoCheck { let allProcessesList = allPreocesses_; allProcessesList = allProcessesList.filter(element => element.activityInstanceName != 'Conhecimento') + allProcessesList = allProcessesList.filter(element => element.activityInstanceName != 'Revisar Diploma') if (!this.p.userRole(['PR'])) { allProcessesList = allProcessesList.filter(element => element.activityInstanceName != 'Assinar Diplomas') From 0b0a500c3734a3caba1c852c37a107a4f17e2de8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eudes=20In=C3=A1cio?= Date: Mon, 31 Jan 2022 15:03:24 +0100 Subject: [PATCH 04/27] offline web gabinete --- src/app/pages/gabinete-digital/event-list/event-list.page.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/app/pages/gabinete-digital/event-list/event-list.page.ts b/src/app/pages/gabinete-digital/event-list/event-list.page.ts index d4c6f126d..17e91500f 100644 --- a/src/app/pages/gabinete-digital/event-list/event-list.page.ts +++ b/src/app/pages/gabinete-digital/event-list/event-list.page.ts @@ -14,6 +14,7 @@ import { Platform } from '@ionic/angular'; import { SortService } from 'src/app/services/functions/sort.service'; import { ThemeService } from 'src/app/services/theme.service' import { RouteService } from 'src/app/services/route.service'; +import { Storage } from '@ionic/storage'; @Component({ selector: 'app-event-list', @@ -46,7 +47,8 @@ export class EventListPage implements OnInit { private sortService: SortService, private backgroundservice: BackgroundService, public ThemeService: ThemeService, - private RouteService: RouteService + private RouteService: RouteService, + private storage: Storage ) { } ngOnInit() { From d2662b4ac71ffe3bc8fc135e214e8e586349c920 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eudes=20In=C3=A1cio?= Date: Tue, 1 Feb 2022 10:25:41 +0100 Subject: [PATCH 05/27] Web offline --- .../approve-event/approve-event.page.ts | 147 ++++++++++-------- .../event-list/event-list.page.ts | 51 ++++-- .../expediente-detail.page.ts | 137 ++++++++++------ .../expediente/expediente.page.ts | 87 +++++------ .../pendentes/pendentes.page.ts | 66 ++++---- .../events-to-approve.page.html | 16 +- .../events-to-approve.page.ts | 27 +++- .../expedients/expedients.page.html | 8 +- .../expedients/expedients.page.ts | 58 ++++--- .../pendentes/pendentes.page.html | 2 +- .../pendentes/pendentes.page.ts | 22 ++- 11 files changed, 384 insertions(+), 237 deletions(-) diff --git a/src/app/pages/gabinete-digital/event-list/approve-event/approve-event.page.ts b/src/app/pages/gabinete-digital/event-list/approve-event/approve-event.page.ts index 96efa78ed..231577b0f 100644 --- a/src/app/pages/gabinete-digital/event-list/approve-event/approve-event.page.ts +++ b/src/app/pages/gabinete-digital/event-list/approve-event/approve-event.page.ts @@ -19,6 +19,7 @@ import { Platform } from '@ionic/angular'; import { ThemeService } from 'src/app/services/theme.service' import { OfflineManagerService } from 'src/app/services/offline-manager.service'; import { RouteService } from 'src/app/services/route.service'; +import { Storage } from '@ionic/storage'; @Component({ selector: 'app-approve-event', @@ -63,7 +64,8 @@ export class ApproveEventPage implements OnInit { private platform: Platform, private backgroundservice: BackgroundService, public ThemeService: ThemeService, - private offlineManager: OfflineManagerService + private offlineManager: OfflineManagerService, + private storage: Storage ) { this.activatedRoute.paramMap.subscribe(params => { // console.log(params["params"]); @@ -110,6 +112,9 @@ export class ApproveEventPage implements OnInit { addProcessToDB(data) { if (this.platform.is('desktop') || this.platform.is('mobileweb')) { + this.storage.set('approve_event_detils', data).then(() => { + console.log('APPROVE EVENT DETAILS SAVED') + }) } else { this.sqliteservice.updateProcess(data); } @@ -117,69 +122,85 @@ export class ApproveEventPage implements OnInit { getProcessFromDB() { - this.platform.ready().then(() => { - - this.sqliteservice.getProcessById(this.serialNumber).then((process) => { - console.log('event aprove serial', process) - - var doc; - var action = []; - var origi = []; - var wordafi = {}; - if (process[0].Documents === "null" || process[0].Documents === "undefined") { - doc = [] - } else { - doc = JSON.parse(process[0].Documents) - } - - if (process[0].actions === "null" || process[0].actions === "undefined") { - action = [] - } else { - action = JSON.parse(process[0].Documents) - } - - if (process[0].originator === "null" || process[0].originator === "undefined") { - origi = [] - } else { - origi = JSON.parse(process[0].Documents) - } - if (process[0].workflowInstanceDataFields === "null" || process[0].workflowInstanceDataFields === "undefined") { - wordafi = [] - } else { - wordafi = JSON.parse(process[0].workflowInstanceDataFields) - } - - let task = { - "Documents": doc, - "actions": action, - "activityInstanceName": process[0].activityInstanceName, - "formURL": process[0].formURL, - "originator": origi, - "serialNumber": process[0].serialNumber, - "taskStartDate": process[0].taskStartDate, - "totalDocuments": process[0].totalDocuments, - "workflowDisplayName": process[0].workflowDisplayName, - "workflowID": process[0].workflowID, - "workflowInstanceDataFields": wordafi, - "workflowInstanceFolio": process[0].workflowInstanceFolio, - "workflowInstanceID": process[0].workflowInstanceID, - "workflowName": process[0].workflowInstanceID - - } - - this.loadedEvent = task - console.log('offline event', this.loadedEvent); - - this.today = new Date(this.loadedEvent.workflowInstanceDataFields.StartDate); - - this.customDate = this.days[this.today.getDay()] + ", " + this.today.getDate() + " de " + (this.months[this.today.getMonth()]); - - let instanceId = this.loadedEvent.workflowInstanceDataFields.InstanceId; - this.loadedAttachments = this.loadedEvent.Documents; - console.log('Attatara', this.loadedAttachments) - + if (this.platform.is('desktop') || this.platform.is('mobileweb')) { + this.storage.get('approve_event_detils').then((event) => { + this.loadedEvent = event + console.log('offline event', this.loadedEvent); + + this.today = new Date(this.loadedEvent.workflowInstanceDataFields.StartDate); + + this.customDate = this.days[this.today.getDay()] + ", " + this.today.getDate() + " de " + (this.months[this.today.getMonth()]); + + let instanceId = this.loadedEvent.workflowInstanceDataFields.InstanceId; + this.loadedAttachments = this.loadedEvent.Documents; + console.log('Attatara', this.loadedAttachments) }) - }) + } else { + this.platform.ready().then(() => { + + this.sqliteservice.getProcessById(this.serialNumber).then((process) => { + console.log('event aprove serial', process) + + var doc; + var action = []; + var origi = []; + var wordafi = {}; + if (process[0].Documents === "null" || process[0].Documents === "undefined") { + doc = [] + } else { + doc = JSON.parse(process[0].Documents) + } + + if (process[0].actions === "null" || process[0].actions === "undefined") { + action = [] + } else { + action = JSON.parse(process[0].Documents) + } + + if (process[0].originator === "null" || process[0].originator === "undefined") { + origi = [] + } else { + origi = JSON.parse(process[0].Documents) + } + if (process[0].workflowInstanceDataFields === "null" || process[0].workflowInstanceDataFields === "undefined") { + wordafi = [] + } else { + wordafi = JSON.parse(process[0].workflowInstanceDataFields) + } + + let task = { + "Documents": doc, + "actions": action, + "activityInstanceName": process[0].activityInstanceName, + "formURL": process[0].formURL, + "originator": origi, + "serialNumber": process[0].serialNumber, + "taskStartDate": process[0].taskStartDate, + "totalDocuments": process[0].totalDocuments, + "workflowDisplayName": process[0].workflowDisplayName, + "workflowID": process[0].workflowID, + "workflowInstanceDataFields": wordafi, + "workflowInstanceFolio": process[0].workflowInstanceFolio, + "workflowInstanceID": process[0].workflowInstanceID, + "workflowName": process[0].workflowInstanceID + + } + + this.loadedEvent = task + console.log('offline event', this.loadedEvent); + + this.today = new Date(this.loadedEvent.workflowInstanceDataFields.StartDate); + + this.customDate = this.days[this.today.getDay()] + ", " + this.today.getDate() + " de " + (this.months[this.today.getMonth()]); + + let instanceId = this.loadedEvent.workflowInstanceDataFields.InstanceId; + this.loadedAttachments = this.loadedEvent.Documents; + console.log('Attatara', this.loadedAttachments) + + }) + }) + } + console.log('Offlineee') } diff --git a/src/app/pages/gabinete-digital/event-list/event-list.page.ts b/src/app/pages/gabinete-digital/event-list/event-list.page.ts index 17e91500f..52ffc12d5 100644 --- a/src/app/pages/gabinete-digital/event-list/event-list.page.ts +++ b/src/app/pages/gabinete-digital/event-list/event-list.page.ts @@ -85,22 +85,37 @@ export class EventListPage implements OnInit { getEventToAproveFromDB() { - this.platform.ready().then(() => { + - this.sqliteservice.getListOfEventAprove('Agenda Oficial MDGPR', 'Agenda Pessoal MDGPR').then((event: any[]) => { - - this.eventsMDGPRList = this.sortService.sortDate(this.transformaDataDB(event), 'taskStartDate') - //this.eventsMDGPRList = this.eventsMDGPRList.filter(element => element.interveners != null) - console.log('MD event to aprove', this.eventsMDGPRList) + if (this.platform.is('desktop') || this.platform.is('mobileweb')) { + this.storage.get('event-to-aproveMD').then((events) => { + this.eventsMDGPRList = events + }) + + this.storage.get('event-to-aprovePR').then((events) => { + this.eventsPRList = events + }) + } else { + this.platform.ready().then(() => { + this.sqliteservice.getListOfEventAprove('Agenda Oficial MDGPR', 'Agenda Pessoal MDGPR').then((event: any[]) => { + + this.eventsMDGPRList = this.sortService.sortDate(this.transformaDataDB(event), 'taskStartDate') + //this.eventsMDGPRList = this.eventsMDGPRList.filter(element => element.interveners != null) + console.log('MD event to aprove', this.eventsMDGPRList) + + }) + + this.sqliteservice.getListOfEventAprove('Agenda Oficial PR', 'Agenda Pessoal PR').then((event: any[]) => { + this.eventsPRList = this.sortService.sortDate(this.transformaDataDB(event), 'taskStartDate') + console.log('PR event to aprove', this.eventsPRList) + + }) }) - this.sqliteservice.getListOfEventAprove('Agenda Oficial PR', 'Agenda Pessoal PR').then((event: any[]) => { - this.eventsPRList = this.sortService.sortDate(this.transformaDataDB(event), 'taskStartDate') - console.log('PR event to aprove', this.eventsPRList) + } + - }) - }) console.log('Offlineee') } @@ -145,16 +160,24 @@ export class EventListPage implements OnInit { let mdEventsPessoal = await this.processes.GetTasksList('Agenda Pessoal MDGPR', false).toPromise(); this.eventsMDGPRList = mdEventsOficial.concat(mdEventsPessoal); this.eventsMDGPRList = this.sortService.sortDate(this.eventsMDGPRList, 'taskStartDate') + this.eventsMDGPRList = this.sortService.sortArrayByDate(this.eventsMDGPRList) console.log('MD EVENT TO APROVE ONLINE',this.eventsMDGPRList) - this.eventaprovacaostore.resetmd(this.sortService.sortArrayByDate(this.eventsMDGPRList).reverse()); + this.storage.set('event-to-aproveMD',this.eventsMDGPRList).then(() => { + console.log(' EVENTMD TO APROVE SAVED') + }) + //this.eventaprovacaostore.resetmd(this.sortService.sortArrayByDate(this.eventsMDGPRList).reverse()); } else if (this.segment == 'PR') { let prEventsOficial = await this.processes.GetTasksList('Agenda Oficial PR', false).toPromise(); let prEventsPessoal = await this.processes.GetTasksList('Agenda Pessoal PR', false).toPromise(); this.eventsPRList = prEventsOficial.concat(prEventsPessoal); this.eventsPRList = this.sortService.sortDate(this.eventsPRList, 'taskStartDate') + this.eventsPRList = this.sortService.sortArrayByDate(this.eventsPRList) console.log('PR EVENT TO APROVE ONLINE',this.eventsPRList) - this.eventaprovacaostore.resetpr(this.sortService.sortArrayByDate(this.eventsPRList).reverse()); + this.storage.set('event-to-aprovePR',this.eventsPRList).then(() => { + console.log(' EVENTPR TO APROVE SAVED') + }) + //this.eventaprovacaostore.resetpr(this.sortService.sortArrayByDate(this.eventsPRList).reverse()); } this.showLoader = false; this.skeletonLoader = false @@ -164,6 +187,8 @@ export class EventListPage implements OnInit { }) } + + async openApproveModal(eventSerialNumber, event) { const modal = await this.modalController.create({ component: ApproveEventModalPage, diff --git a/src/app/pages/gabinete-digital/expediente/expediente-detail/expediente-detail.page.ts b/src/app/pages/gabinete-digital/expediente/expediente-detail/expediente-detail.page.ts index c1a167d21..2ac4ac6ad 100644 --- a/src/app/pages/gabinete-digital/expediente/expediente-detail/expediente-detail.page.ts +++ b/src/app/pages/gabinete-digital/expediente/expediente-detail/expediente-detail.page.ts @@ -33,6 +33,7 @@ import { BackgroundService } from 'src/app/services/background.service'; import { NewGroupPage } from 'src/app/pages/chat/new-group/new-group.page'; import { DataService } from 'src/app/services/data.service'; import { RouteService } from 'src/app/services/route.service'; +import { Storage } from '@ionic/storage'; @Component({ selector: 'app-expediente-detail', @@ -82,6 +83,7 @@ export class ExpedienteDetailPage implements OnInit { private backgroundservice: BackgroundService, public ThemeService: ThemeService, private dataService: DataService, + private storage: Storage ) { this.activatedRoute.paramMap.subscribe(params => { if (params["params"].SerialNumber) { @@ -112,63 +114,106 @@ export class ExpedienteDetailPage implements OnInit { updateProcessDB(res) { if (this.platform.is('desktop') || this.platform.is('mobileweb')) { + this.storage.set('expediente_details',res).then(() =>{ + console.log('EXPEDIENTE DETAILS SAVED') + }) } else { this.sqliteservice.updateProcess(res) } } getFromDB() { - - this.platform.ready().then(() => { - this.onlinecheck = false; - this.sqliteservice.getProcessById(this.serialNumber).then((process) => { - console.log("expedient ditail", process) - - var workflow = JSON.parse(process[0].workflowInstanceDataFields); - var origina - if (process[0].originator === "undefined") { - origina = "" - } else { - origina = JSON.parse(process[0].originator) - } - + if (this.platform.is('desktop') || this.platform.is('mobileweb')) { + this.storage.get('expediente_details').then((process) => { this.task = { - "SerialNumber": process[0].serialNumber, - "Folio": workflow.Subject, - "Senders": origina.email || process[0].originator, - "CreateDate": momentG(new Date(process[0].taskStartDate), 'yyyy-MM-dd HH:mm:ss'), - "DocumentURL": workflow.ViewerRequest, - "Remetente": workflow.Sender, - "Note": workflow.TaskMessage || workflow.Note, - "FolderId": workflow.FolderID, - "FsId": workflow.FsId, - "DocId": workflow.DocID, - "WorkflowName": process[0].workflowDisplayName, - "Status": workflow.Status, - "DispatchNumber": workflow.DispatchNumber, - "AttachmentsProcessLastInstanceID": workflow.AttachmentsProcessLastInstanceID, - "InstanceID": workflow.InstanceID + "SerialNumber": process.serialNumber, + "Folio": process.workflowInstanceDataFields.Subject, + "Senders": process.originator || process.originator, + "CreateDate": momentG(new Date(process.taskStartDate), 'yyyy-MM-dd HH:mm:ss'), + "DocumentURL": process.workflowInstanceDataFields.ViewerRequest, + "Remetente": process.workflowInstanceDataFields.Sender, + "Note": process.workflowInstanceDataFields.TaskMessage || process.workflowInstanceDataFields.Note, + "FolderId": process.workflowInstanceDataFields.FolderID, + "FsId": process.workflowInstanceDataFields.FsId, + "DocId": process.workflowInstanceDataFields.DocID, + "WorkflowName": process.workflowDisplayName, + "Status": process.workflowInstanceDataFields.Status, + "DispatchNumber": process.workflowInstanceDataFields.DispatchNumber, + "AttachmentsProcessLastInstanceID": process.workflowInstanceDataFields.AttachmentsProcessLastInstanceID, + "InstanceID": process.workflowInstanceDataFields.InstanceID } this.fulltask = { - Documents: JSON.parse(process[0].Documents), - actions: JSON.parse(process[0].actions), - activityInstanceName: process[0].activityInstanceName, - formURL: process[0].formURL, - interveners: process[0].interveners, - originator: JSON.parse(process[0].originator), - serialNumber: process[0].serialNumber, - taskStartDate: process[0].taskStartDate, - totalDocuments: process[0].totalDocuments, - workflowDisplayName: process[0].workflowDisplayName, - workflowID: process[0].workflowID, - workflowInstanceDataFields: JSON.parse(process[0].workflowInstanceDataFields), - workflowInstanceFolio: process[0].workflowInstanceFolio, - workflowInstanceID: process[0].workflowInstanceID, - workflowName: process[0].workflowName, + Documents: process.Documents, + actions: process.actions, + activityInstanceName: process.activityInstanceName, + formURL: process.formURL, + interveners: process.interveners, + originator: process.originator, + serialNumber: process.serialNumber, + taskStartDate: process.taskStartDate, + totalDocuments: process.totalDocuments, + workflowDisplayName: process.workflowDisplayName, + workflowID: process.workflowID, + workflowInstanceDataFields: process.workflowInstanceDataFields, + workflowInstanceFolio: process.workflowInstanceFolio, + workflowInstanceID: process.workflowInstanceID, + workflowName: process.workflowName, } - }) - }) + } else { + this.platform.ready().then(() => { + this.onlinecheck = false; + this.sqliteservice.getProcessById(this.serialNumber).then((process) => { + console.log("expedient ditail", process) + + var workflow = JSON.parse(process[0].workflowInstanceDataFields); + var origina + if (process[0].originator === "undefined") { + origina = "" + } else { + origina = JSON.parse(process[0].originator) + } + + this.task = { + "SerialNumber": process[0].serialNumber, + "Folio": workflow.Subject, + "Senders": origina.email || process[0].originator, + "CreateDate": momentG(new Date(process[0].taskStartDate), 'yyyy-MM-dd HH:mm:ss'), + "DocumentURL": workflow.ViewerRequest, + "Remetente": workflow.Sender, + "Note": workflow.TaskMessage || workflow.Note, + "FolderId": workflow.FolderID, + "FsId": workflow.FsId, + "DocId": workflow.DocID, + "WorkflowName": process[0].workflowDisplayName, + "Status": workflow.Status, + "DispatchNumber": workflow.DispatchNumber, + "AttachmentsProcessLastInstanceID": workflow.AttachmentsProcessLastInstanceID, + "InstanceID": workflow.InstanceID + } + + this.fulltask = { + Documents: JSON.parse(process[0].Documents), + actions: JSON.parse(process[0].actions), + activityInstanceName: process[0].activityInstanceName, + formURL: process[0].formURL, + interveners: process[0].interveners, + originator: JSON.parse(process[0].originator), + serialNumber: process[0].serialNumber, + taskStartDate: process[0].taskStartDate, + totalDocuments: process[0].totalDocuments, + workflowDisplayName: process[0].workflowDisplayName, + workflowID: process[0].workflowID, + workflowInstanceDataFields: JSON.parse(process[0].workflowInstanceDataFields), + workflowInstanceFolio: process[0].workflowInstanceFolio, + workflowInstanceID: process[0].workflowInstanceID, + workflowName: process[0].workflowName, + } + + }) + }) + } + } diff --git a/src/app/pages/gabinete-digital/expediente/expediente.page.ts b/src/app/pages/gabinete-digital/expediente/expediente.page.ts index fbb867aa7..1a01b95dc 100644 --- a/src/app/pages/gabinete-digital/expediente/expediente.page.ts +++ b/src/app/pages/gabinete-digital/expediente/expediente.page.ts @@ -9,6 +9,7 @@ import { Platform } from '@ionic/angular'; import { BackgroundService } from '../../../services/background.service'; import { ThemeService } from 'src/app/services/theme.service' import { SortService } from 'src/app/services/functions/sort.service'; +import {Storage } from '@ionic/storage'; @Component({ selector: 'app-expediente', @@ -40,6 +41,7 @@ export class ExpedientePage implements OnInit { private backgroundservice: BackgroundService, public ThemeService: ThemeService, private sortService: SortService, + private storage: Storage ) { } ngOnInit() { @@ -112,63 +114,48 @@ export class ExpedientePage implements OnInit { addProcessTODb(task) { if (this.platform.is('desktop') || this.platform.is('mobileweb')) { + this.storage.set('gabinete-expediente',task).then(() => { + console.log('GABINETE EXPEDIENTE SAVED') + }) } else { this.sqliteservice.addProcess(task); } } - SqliteAddExpediente(list) { - list.forEach((expediente) => { - let data = { - serialNumber: expediente.serialNumber, - workflowInstanceFolio: expediente.workflowInstanceFolio, - Documents: expediente.Documents, - actions: expediente.actions, - activityInstanceName: expediente.activityInstanceName, - formURL: expediente.formURL, - originator: expediente.originator, - taskStartDate: expediente.taskStartDate, - totalDocuments: expediente.totalDocuments, - workflowDisplayName: expediente.workflowDisplayName, - workflowID: expediente.workflowID, - workflowInstanceDataFields: expediente.workflowInstanceDataFields, - workflowInstanceID: expediente.workflowInstanceID, - workflowName: expediente.workflowName - } - - this.sqliteservice.addExpediente(data); - }) - - } - getEventsFromLocalDb() { - this.taskslist = new Array(); - this.sqliteservice.getprocessByworkflow("Expediente").then((expediente: any[]) => { - console.log("All expedientes from local,", expediente) - - expediente.forEach((element) => { - - var workflow = JSON.parse(element.workflowInstanceDataFields); - - let exped = { - "CreateDate": element.taskStartDate, - "DocumentsQty": element.totalDocuments, - "Senders": workflow.Senders, - "SerialNumber": element.serialNumber, - "Status": workflow.Status, - "Subject": workflow.Subject, - "WorkflowName": element.workflowDisplayName, - "activityInstanceName": element.activityInstanceName - } - - this.taskslist.push(exped) - - }); - - this.listToPresent = this.taskslist - - }) + if (this.platform.is('desktop') || this.platform.is('mobileweb')) { + this.storage.get('gabinete-expediente').then((expediente) => { + this.listToPresent = expediente + }) + } else { + this.taskslist = new Array(); + this.sqliteservice.getprocessByworkflow("Expediente").then((expediente: any[]) => { + console.log("All expedientes from local,", expediente) + + expediente.forEach((element) => { + + var workflow = JSON.parse(element.workflowInstanceDataFields); + + let exped = { + "CreateDate": element.taskStartDate, + "DocumentsQty": element.totalDocuments, + "Senders": workflow.Senders, + "SerialNumber": element.serialNumber, + "Status": workflow.Status, + "Subject": workflow.Subject, + "WorkflowName": element.workflowDisplayName, + "activityInstanceName": element.activityInstanceName + } + + this.taskslist.push(exped) + + }); + + this.listToPresent = this.taskslist + + }) + } } } diff --git a/src/app/pages/gabinete-digital/pendentes/pendentes.page.ts b/src/app/pages/gabinete-digital/pendentes/pendentes.page.ts index 06fb79049..7948de036 100644 --- a/src/app/pages/gabinete-digital/pendentes/pendentes.page.ts +++ b/src/app/pages/gabinete-digital/pendentes/pendentes.page.ts @@ -14,6 +14,7 @@ import { SqliteService } from 'src/app/services/sqlite.service'; import { BackgroundService } from 'src/app/services/background.service'; import { Platform } from '@ionic/angular'; import { SortService } from 'src/app/services/functions/sort.service'; +import { Storage } from '@ionic/storage'; @Component({ @@ -47,6 +48,7 @@ export class PendentesPage implements OnInit { private platform: Platform, private backgroundservices: BackgroundService, private sortService: SortService, + private storage: Storage ) { this.loggeduser = authService.ValidatedUser; this.profile = 'mdgpr'; @@ -104,6 +106,9 @@ export class PendentesPage implements OnInit { pendentesList = removeDuplicate(pendentesList) pendentesList = this.sortService.sortDate(pendentesList, 'CreateDate'); this.listToPresent = pendentesList; + this.storage.set('pendente-list',pendentesList).then(() => { + console.log('Pendente list SAVED') + }) this.skeletonLoader = false; }, (error) => { @@ -116,34 +121,41 @@ export class PendentesPage implements OnInit { getFromDb() { - this.platform.ready().then(() => { - this.sqliteservice.getAllProcess().then((process: any[]) => { - var pendingList = [] - console.log('Pendentes off off',process ) - process.forEach(element => { - var workflow = JSON.parse(element.workflowInstanceDataFields); - if (workflow.Status === "Pending") { - let task = { - "CreateDate": new Date(element.taskStartDate), - "DocumentsQty": element.totalDocuments, - "FolderID": workflow.FolderID, - "Folio": workflow.Subject, - "Senders": workflow.Sender, - "SerialNumber": element.serialNumber, - "Status": workflow.Status, - "WorkflowName": element.workflowDisplayName - - } - pendingList.push(task) - } - }); - - pendingList = this.sortService.sortDate(pendingList, 'CreateDate'); - this.listToPresent = pendingList; - console.log('pendentes', pendingList) - + if (this.platform.is('desktop') || this.platform.is('mobileweb')) { + this.storage.get('pendente-list').then((pendentes) => { + this.listToPresent =pendentes }) - }) + } else { + + this.platform.ready().then(() => { + this.sqliteservice.getAllProcess().then((process: any[]) => { + var pendingList = [] + console.log('Pendentes off off',process ) + process.forEach(element => { + var workflow = JSON.parse(element.workflowInstanceDataFields); + if (workflow.Status === "Pending") { + let task = { + "CreateDate": new Date(element.taskStartDate), + "DocumentsQty": element.totalDocuments, + "FolderID": workflow.FolderID, + "Folio": workflow.Subject, + "Senders": workflow.Sender, + "SerialNumber": element.serialNumber, + "Status": workflow.Status, + "WorkflowName": element.workflowDisplayName + + } + pendingList.push(task) + } + }); + + pendingList = this.sortService.sortDate(pendingList, 'CreateDate'); + this.listToPresent = pendingList; + console.log('pendentes', pendingList) + + }) + }) + } } async refreshing() { diff --git a/src/app/shared/gabinete-digital/events-to-approve/events-to-approve.page.html b/src/app/shared/gabinete-digital/events-to-approve/events-to-approve.page.html index eff4cab69..7a244f1de 100644 --- a/src/app/shared/gabinete-digital/events-to-approve/events-to-approve.page.html +++ b/src/app/shared/gabinete-digital/events-to-approve/events-to-approve.page.html @@ -28,12 +28,12 @@
-
+
@@ -52,7 +52,7 @@
-
+
@@ -62,12 +62,12 @@
-
+
-
+
@@ -87,10 +87,10 @@
-
+
+ *ngIf="eventsPRList.length < 1"> Lista vazia
diff --git a/src/app/shared/gabinete-digital/events-to-approve/events-to-approve.page.ts b/src/app/shared/gabinete-digital/events-to-approve/events-to-approve.page.ts index 93a20876d..34a6c3042 100644 --- a/src/app/shared/gabinete-digital/events-to-approve/events-to-approve.page.ts +++ b/src/app/shared/gabinete-digital/events-to-approve/events-to-approve.page.ts @@ -8,6 +8,7 @@ import { LoginUserRespose } from 'src/app/models/user.model'; import { AuthService } from 'src/app/services/auth.service'; import { EventoAprovacaoStore } from 'src/app/store/eventoaprovacao-store.service'; import { SortService } from 'src/app/services/functions/sort.service'; +import { Storage } from '@ionic/storage'; @Component({ selector: 'app-events-to-approve', @@ -33,6 +34,7 @@ export class EventsToApprovePage implements OnInit { private router: Router, private userAuth: AuthService, private sortService: SortService, + private storage: Storage ) { this.loggeduser = userAuth.ValidatedUser; @@ -63,25 +65,46 @@ export class EventsToApprovePage implements OnInit { async LoadToApproveEvents() { this.showLoader = true; console.log(this.segment); + this.getFromDB(); if(this.segment == 'MDGPR'){ let mdEventsOficial = await this.processes.GetTasksList('Agenda Oficial MDGPR', false).toPromise(); let mdEventsPessoal = await this.processes.GetTasksList('Agenda Pessoal MDGPR', false).toPromise(); this.eventsMDGPRList = mdEventsOficial.concat(mdEventsPessoal); + this.eventsMDGPRList = this.sortService.sortArrayByDate(this.eventsMDGPRList) console.log(this.sortService.sortArrayByDate(this.eventsMDGPRList)); - this.eventaprovacaostore.resetmd(this.sortService.sortDate(this.eventsMDGPRList, 'CreateDate')); + this.storage.set('event-to-aproveMD',this.eventsMDGPRList).then(() => { + console.log(' EVENTMD TO APROVE SAVED') + }) + + //this.eventaprovacaostore.resetmd(this.sortService.sortDate(this.eventsMDGPRList, 'CreateDate')); } else if(this.segment == 'PR'){ let prEventsOficial = await this.processes.GetTasksList('Agenda Oficial PR', false).toPromise(); let prEventsPessoal = await this.processes.GetTasksList('Agenda Pessoal PR', false).toPromise(); this.eventsPRList = prEventsOficial.concat(prEventsPessoal); + this.eventsPRList = this.sortService.sortArrayByDate(this.eventsPRList) - this.eventaprovacaostore.resetpr(this.sortService.sortDate(this.eventsPRList, 'CreateDate')); + this.storage.set('event-to-aprovePR',this.eventsPRList).then(() => { + console.log(' EVENTPR TO APROVE SAVED') + }) + //this.eventaprovacaostore.resetpr(this.sortService.sortDate(this.eventsPRList, 'CreateDate')); } this.showLoader = false; } + getFromDB() { + this.storage.get('event-to-aproveMD').then((events) => { + this.eventsMDGPRList = events + }) + + this.storage.get('event-to-aprovePR').then((events) => { + this.eventsPRList = events + }) + } + + toDateString(e) { return new Date(e).toDateString() } diff --git a/src/app/shared/gabinete-digital/expedients/expedients.page.html b/src/app/shared/gabinete-digital/expedients/expedients.page.html index 505783c38..b2cb23a60 100644 --- a/src/app/shared/gabinete-digital/expedients/expedients.page.html +++ b/src/app/shared/gabinete-digital/expedients/expedients.page.html @@ -22,10 +22,10 @@
- +
@@ -58,13 +58,13 @@
Lista vazia
-
+
diff --git a/src/app/shared/gabinete-digital/expedients/expedients.page.ts b/src/app/shared/gabinete-digital/expedients/expedients.page.ts index 84d2baad5..8c5696320 100644 --- a/src/app/shared/gabinete-digital/expedients/expedients.page.ts +++ b/src/app/shared/gabinete-digital/expedients/expedients.page.ts @@ -6,6 +6,7 @@ import { ExpedienteGdStore } from 'src/app/store/expedientegd-store.service'; import { ExpedienteTaskPipe } from 'src/app/pipes/expediente-task.pipe'; import { ThemeService } from 'src/app/services/theme.service' import { SortService } from 'src/app/services/functions/sort.service'; +import { Storage } from '@ionic/storage'; @Component({ selector: 'app-expedients', @@ -13,27 +14,28 @@ import { SortService } from 'src/app/services/functions/sort.service'; styleUrls: ['./expedients.page.scss'], }) export class ExpedientsPage implements OnInit { - segment:string; + segment: string; taskslist = []; - serialNumber:string; + serialNumber: string; - @Input() profile:string; + @Input() profile: string; skeletonLoader = true expedientegbstore = ExpedienteGdStore expedienteTaskPipe = new ExpedienteTaskPipe() constructor( - private processes:ProcessesService, + private processes: ProcessesService, private alertService: AlertService, private router: Router, public ThemeService: ThemeService, private sortService: SortService, - ) { - this.profile = 'mdgpr'; + private storage: Storage + ) { + this.profile = 'mdgpr'; - } + } ngOnInit() { //Inicializar segment @@ -43,11 +45,11 @@ export class ExpedientsPage implements OnInit { this.router.events.forEach((event) => { if (event instanceof NavigationStart && event.url.startsWith('/home/gabinete-digital?expedientes=true')) { - if(window.location.pathname.split('/').length >= 4 && window.location.pathname.startsWith('/home/gabinete-digital')) { - this.doRefresh() - } else { - this.LoadList() - } + if (window.location.pathname.split('/').length >= 4 && window.location.pathname.startsWith('/home/gabinete-digital')) { + this.doRefresh() + } else { + this.LoadList() + } } }); @@ -75,21 +77,35 @@ export class ExpedientsPage implements OnInit { this.taskslist.push(task); }); - this.taskslist = this.sortService.sortDate(this.taskslist, 'CreateDate') + this.addProcessTODb(this.taskslist); this.expedientegbstore.reset(this.taskslist); + }, (error) => { + this.getEventsFromLocalDb(); }); } - doRefresh() { - setTimeout(()=>{ - this.LoadList(); - }, 1000) - + addProcessTODb(task) { + this.storage.set('gabinete-expediente', task).then(() => { + console.log('GABINETE EXPEDIENTE SAVED') + }) } - goToExpediente(serialNumber:any){ - this.router.navigate(['/home/gabinete-digital/expediente',serialNumber,'gabinete-digital']); + getEventsFromLocalDb() { + this.storage.get('gabinete-expediente').then((expediente) => { + this.taskslist = expediente + }) } -} + doRefresh() { + setTimeout(() => { + this.LoadList(); + }, 1000) + + } + + goToExpediente(serialNumber: any) { + this.router.navigate(['/home/gabinete-digital/expediente', serialNumber, 'gabinete-digital']); + } + + } diff --git a/src/app/shared/gabinete-digital/pendentes/pendentes.page.html b/src/app/shared/gabinete-digital/pendentes/pendentes.page.html index f91d503c5..d3a69b760 100644 --- a/src/app/shared/gabinete-digital/pendentes/pendentes.page.html +++ b/src/app/shared/gabinete-digital/pendentes/pendentes.page.html @@ -20,7 +20,7 @@ diff --git a/src/app/shared/gabinete-digital/pendentes/pendentes.page.ts b/src/app/shared/gabinete-digital/pendentes/pendentes.page.ts index 6ee44b91a..4ee229244 100644 --- a/src/app/shared/gabinete-digital/pendentes/pendentes.page.ts +++ b/src/app/shared/gabinete-digital/pendentes/pendentes.page.ts @@ -8,6 +8,7 @@ import { PendentesStore } from 'src/app/store/pendestes-store.service'; import { LoginUserRespose } from 'src/app/models/user.model'; import { CustomTaskPipe } from 'src/app/pipes/custom-task.pipe'; import { SortService } from 'src/app/services/functions/sort.service'; +import { Storage } from '@ionic/storage'; @Component({ selector: 'app-pendentes', @@ -20,6 +21,7 @@ export class PendentesPage implements OnInit { pendentesstore = PendentesStore; customTaskPipe = new CustomTaskPipe() loggeduser: LoginUserRespose; + listToPresent = []; @Input() profile:string; segment:string; @@ -30,6 +32,7 @@ export class PendentesPage implements OnInit { private authService: AuthService, private router: Router, private sortService: SortService, + private storage: Storage ) { this.loggeduser = authService.ValidatedUser; } @@ -52,7 +55,7 @@ export class PendentesPage implements OnInit { async LoadList(){ this.skeletonLoader = true; - + this.processes.GetPendingTasks(false).subscribe(async res => { let pendentes = await this.processes.GetPendingTasks(false).toPromise(); let pendentesList = []; @@ -64,9 +67,24 @@ export class PendentesPage implements OnInit { pendentesList = removeDuplicate( pendentesList) pendentesList = this.sortService.sortDate(pendentesList, 'CreateDate') + this.listToPresent = pendentesList this.pendentesstore.reset(pendentesList); + this.storage.set('pendente-list',pendentesList).then(() => { + console.log('Pendente list SAVED') + }) this.skeletonLoader = false; - } + }, (error) => { + if(error.status == 0){ + this.getFromDb(); + } + }) +} + +getFromDb() { + this.storage.get('pendente-list').then((pendentes) => { + this.listToPresent =pendentes + }) +} doRefresh() { setTimeout(()=>{ From bd316d9e1770a1600c96096a22793bd4e0fb35fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eudes=20In=C3=A1cio?= Date: Wed, 2 Feb 2022 10:37:57 +0100 Subject: [PATCH 06/27] duplicate roms bug fix --- src/app/pages/chat/chat.page.ts | 4 ++-- src/app/pages/chat/group-messages/group-messages.page.html | 2 +- src/app/services/chat/ws-chat-methods.service.ts | 6 +++--- src/app/shared/chat/group-messages/group-messages.page.html | 2 +- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/app/pages/chat/chat.page.ts b/src/app/pages/chat/chat.page.ts index b5963e605..8c6c10a53 100644 --- a/src/app/pages/chat/chat.page.ts +++ b/src/app/pages/chat/chat.page.ts @@ -143,8 +143,8 @@ export class ChatPage implements OnInit { ngOnInit() { - console.log(this.wsChatMethodsService.dm); - console.log(this.wsChatMethodsService.group); + console.log('Rooms INDIVIDUAIS',this.wsChatMethodsService._dm); + console.log(' ROOMS GROUP',this.wsChatMethodsService._group); this.segment = "Contactos"; diff --git a/src/app/pages/chat/group-messages/group-messages.page.html b/src/app/pages/chat/group-messages/group-messages.page.html index cdfd4646b..a6b7ff0fb 100644 --- a/src/app/pages/chat/group-messages/group-messages.page.html +++ b/src/app/pages/chat/group-messages/group-messages.page.html @@ -102,7 +102,7 @@
- image + image
diff --git a/src/app/services/chat/ws-chat-methods.service.ts b/src/app/services/chat/ws-chat-methods.service.ts index 2158e8be8..b82f531c9 100644 --- a/src/app/services/chat/ws-chat-methods.service.ts +++ b/src/app/services/chat/ws-chat-methods.service.ts @@ -99,10 +99,10 @@ export class WsChatMethodsService { async getAllRooms () { this.loadingWholeList = true - this.getRoomFromDb(); + //this.getRoomFromDb(); const rooms = await this.WsChatService.getRooms(); - - this.storage.set('Rooms', rooms); + await this.storage.remove('Rooms'); + await this.storage.set('Rooms', rooms); // console.log("ROOMS" + JSON.stringify(rooms)) this.WsChatService.registerCallback({ diff --git a/src/app/shared/chat/group-messages/group-messages.page.html b/src/app/shared/chat/group-messages/group-messages.page.html index 2bbb6b651..40fe8d047 100644 --- a/src/app/shared/chat/group-messages/group-messages.page.html +++ b/src/app/shared/chat/group-messages/group-messages.page.html @@ -78,7 +78,7 @@
- image + image
From 50845aca9917ccbc1b222d469024c384621081e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eudes=20In=C3=A1cio?= Date: Wed, 2 Feb 2022 11:58:01 +0100 Subject: [PATCH 07/27] Add image to chat web hiden false --- src/app/pages/chat/messages/messages.page.ts | 2 +- src/app/shared/chat/group-messages/group-messages.page.html | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/app/pages/chat/messages/messages.page.ts b/src/app/pages/chat/messages/messages.page.ts index 605f83532..6558fc4f5 100644 --- a/src/app/pages/chat/messages/messages.page.ts +++ b/src/app/pages/chat/messages/messages.page.ts @@ -517,7 +517,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { async openChatOptions(ev?: any) { const roomId = this.roomId - console.log(this.members); + console.log('MOBILE CHAT OPTION',this.members); const popover = await this.popoverController.create({ component: ChatOptionsPopoverPage, diff --git a/src/app/shared/chat/group-messages/group-messages.page.html b/src/app/shared/chat/group-messages/group-messages.page.html index 40fe8d047..d1989fed9 100644 --- a/src/app/shared/chat/group-messages/group-messages.page.html +++ b/src/app/shared/chat/group-messages/group-messages.page.html @@ -222,7 +222,7 @@ - + From 33cce0fd449e4a66ff13fdcd6f14662876a68c0a Mon Sep 17 00:00:00 2001 From: Peter Maquiran Date: Wed, 2 Feb 2022 20:16:12 +0100 Subject: [PATCH 08/27] add chat offline --- src/app/models/chatMethod.ts | 8 +- src/app/services/chat/message.service.ts | 16 +- src/app/services/chat/room.service.ts | 146 +++++++++++++----- .../services/chat/ws-chat-methods.service.ts | 3 +- src/app/services/chat/ws-chat.service.ts | 8 +- src/environments/environment.prod.ts | 1 + src/environments/environment.ts | 1 + 7 files changed, 134 insertions(+), 49 deletions(-) diff --git a/src/app/models/chatMethod.ts b/src/app/models/chatMethod.ts index 99d41f39d..1b5c6bd9c 100644 --- a/src/app/models/chatMethod.ts +++ b/src/app/models/chatMethod.ts @@ -59,7 +59,7 @@ interface FirstUnread { msg: string; ts: Ts2; u: U2; - _updatedAt: UpdatedAt2; + _updatedAt: string; mentions: any[]; channels: any[]; } @@ -72,7 +72,7 @@ export interface Message { ts: Ts; u: U; t: string; - _updatedAt: UpdatedAt; + _updatedAt: ''; mentions: any[]; channels: any[]; attachments: Attachment[]; @@ -232,7 +232,7 @@ interface FirstUnread { msg: string; ts: Ts2; u: U2; - _updatedAt: UpdatedAt2; + _updatedAt: string; mentions: any[]; channels: any[]; } @@ -245,7 +245,7 @@ export interface Message { ts: Ts; u: U; t: string; - _updatedAt: UpdatedAt; + _updatedAt: ''; mentions: any[]; channels: any[]; attachments: Attachment[]; diff --git a/src/app/services/chat/message.service.ts b/src/app/services/chat/message.service.ts index bde3ef601..43c8f74be 100644 --- a/src/app/services/chat/message.service.ts +++ b/src/app/services/chat/message.service.ts @@ -17,9 +17,10 @@ export class MessageService { u = {} t = '' _id ='' - _updatedAt = {} + _updatedAt = '' file attachments + offline = false constructor(private storage: Storage) { } @@ -47,10 +48,23 @@ export class MessageService { }); } } + + + if(this.rid == 'offline') { + this.offline = true + } else { + this.offline = false + } + } delete() {} showDateDuration() {} + + resend() { + + } + } diff --git a/src/app/services/chat/room.service.ts b/src/app/services/chat/room.service.ts index fb89ea961..623d6043b 100644 --- a/src/app/services/chat/room.service.ts +++ b/src/app/services/chat/room.service.ts @@ -13,6 +13,7 @@ import { SessionStore } from 'src/app/store/session.service'; 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'; @Injectable({ providedIn: 'root' @@ -51,6 +52,8 @@ export class RoomService { return [] } + sortRoomList = () => {} + constructor( public WsChatService: WsChatService, private MessageService: MessageService, @@ -80,40 +83,34 @@ export class RoomService { this.id, "stream-room-messages", (ChatMessage) => { - ChatMessage = ChatMessage.fields.args[0] - ChatMessage = this.fix_updatedAt(ChatMessage) - console.log('recivemessage', ChatMessage) + if(environment.chatOffline == false) { + ChatMessage = ChatMessage.fields.args[0] + ChatMessage = this.fix_updatedAt(ChatMessage) + console.log('recivemessage', ChatMessage) + + const message = this.prepareMessage(ChatMessage) - const message = this.prepareMessage(ChatMessage) + this.lastMessage = message + if (message.t == 'r') { this.name = message.msg } + this.calDateDuration(ChatMessage._updatedAt) + + setTimeout(() => { + this.scrollDown() + }, 100) + + //this.sortService.sortDate(this.messages, '') + + if(SessionStore.user.RochetChatUser != ChatMessage.u.username) { + this.NativeNotificationService.sendNotificationChat({ + message: message.msg, + title: this.name + }); + } - this.lastMessage = message - if (message.t == 'r') { this.name = message.msg } - this.calDateDuration(ChatMessage._updatedAt) - this.messages.push(message) - - setTimeout(() => { - this.scrollDown() - }, 100) - - //this.sortService.sortDate(this.messages, '') - - if(SessionStore.user.RochetChatUser != ChatMessage.u.username) { - this.NativeNotificationService.sendNotificationChat({ - message: message.msg, - title: this.name - }); + this.addMessageDB(ChatMessage) } - // save to ionic storage - this.storage.get('chatmsg' + this.id).then((messages: any) => { - const newListMessages = messages.push(ChatMessage) - - this.storage.set('chatmsg' + this.id, newListMessages).then((value) => { - console.log('MSG SAVED ON STORAGE', value) - }); - }) - } ) @@ -133,6 +130,15 @@ export class RoomService { this.WsChatService.registerCallback } + + addMessageDB(ChatMessage) { + this.storage.get('chatmsg' + this.id).then((messages: any = []) => { + messages.push(ChatMessage) + + this.storage.set('chatmsg' + this.id, messages) + }) + } + async receiveMessageDelete() { this.WsChatService.updateRoomEventss( @@ -195,8 +201,60 @@ export class RoomService { * @description sen text message */ send() { - this.WsChatService.send(this.id, this.message) - this.message= '' + + if(environment.chatOffline == false) { + this.WsChatService.send(this.id, this.message) + this.message= '' + } else { + + const offlineChatMessage = { + channels: [], + mentions: [], + rid: 'offline', + msg: this.message, + ts: { $date: new Date().getTime() }, + u: { + name: this.usernameToDisplayName(SessionStore.user.RochetChatUser), + username: SessionStore.user.RochetChatUser, + _id: "" + }, + _updatedAt: new Date().getTime() + } + + this.addMessageDB(offlineChatMessage) + const message: MessageService = this.prepareMessage(offlineChatMessage) + + setTimeout(() => { + this.scrollDown() + }, 150) + + this.lastMessage = message + + this.redefinedMessage(message) + + 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 + + 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() + }) } @@ -266,22 +324,31 @@ export class RoomService { } - // runs onces only - loadHistory(limit = 100) { - - if (this.hasLoadHistory) { return false } - + restoreMessageFromDB() { this.storage.get('chatmsg' + this.id).then((messages = []) => { let localMessages = [] - messages.forEach(message => { + messages.forEach((message = []) => { const wewMessage = this.prepareMessage(message) + + if(wewMessage.rid == 'offline') { + this.redefinedMessage(wewMessage) + } + localMessages.push(wewMessage) }); this.messages = localMessages }) + } + + // runs onces only + loadHistory(limit = 100) { + + if (this.hasLoadHistory) { return false } + + this.restoreMessageFromDB() this.WsChatService.loadHistory(this.id, limit).then((chatHistory:chatHistory) => { console.log('loadHistory', chatHistory) @@ -317,7 +384,8 @@ export class RoomService { message = this.fix_updatedAt(message) const wewMessage = new MessageService(this.storage) wewMessage.setData(message) - + this.messages.push(wewMessage) + return wewMessage } @@ -343,7 +411,7 @@ export class RoomService { if (message.result) { console.log('FIX UPDATE ', message.result) message.result._updatedAt = message.result._updatedAt['$date'] - } else { + } else if(message._updatedAt.hasOwnProperty('$date')) { // console.log('FIX UPDATE 11', message) message._updatedAt = message._updatedAt['$date'] } diff --git a/src/app/services/chat/ws-chat-methods.service.ts b/src/app/services/chat/ws-chat-methods.service.ts index 4208e6ca7..4d86b8ef6 100644 --- a/src/app/services/chat/ws-chat-methods.service.ts +++ b/src/app/services/chat/ws-chat-methods.service.ts @@ -131,7 +131,7 @@ export class WsChatMethodsService { /** * @description sort room list by last message date */ - sortRoomList() { + sortRoomList =() => { this._dm = this.sortService.sortDate(this._dm,'_updatedAt').reverse() this._group = this.sortService.sortDate(this._group,'_updatedAt').reverse() } @@ -207,6 +207,7 @@ export class WsChatMethodsService { room.receiveMessage() room.getAllUsers = this.getUsers room.receiveMessageDelete(); + room.sortRoomList = this.sortRoomList let roomId = this.getRoomId(roomData) diff --git a/src/app/services/chat/ws-chat.service.ts b/src/app/services/chat/ws-chat.service.ts index 845a02ba1..af2d28267 100644 --- a/src/app/services/chat/ws-chat.service.ts +++ b/src/app/services/chat/ws-chat.service.ts @@ -30,8 +30,8 @@ export class WsChatService { support: ["1"] } - this.ws.send({message, loginRequired: false}) - this.ws.send({message:{msg:"pong"}, loginRequired: false}) + this.ws.send({message, loginRequired: false, requestId: 'connectMessage'}) + this.ws.send({message:{msg:"pong"}, loginRequired: false, requestId: 'connectPong'}) this.ws.registerCallback({ type:'Onmessage', @@ -65,7 +65,7 @@ export class WsChatService { } ] } - this.ws.send({message, requestId, loginRequired: false}) + this.ws.send({message, requestId: 'login', loginRequired: false}) return new Promise((resolve, reject) => { @@ -633,7 +633,7 @@ updateRoomEventss(roomId, collection:string, funx: Function, ) { if (this.ws.connected == false || loginRequired == true && this.isLogin == false) { // save data to send when back online // console.log('save msgQueue this.ws.connected == false || loginRequired == true && this.isLogin == false',this.ws.connected, loginRequired, this.isLogin) - console.log('save msgQueue', requestId) + console.log('save msgQueue', requestId, message) this.wsMsgQueue[requestId] = {message, requestId, loginRequired} } else { diff --git a/src/environments/environment.prod.ts b/src/environments/environment.prod.ts index d839c7ee7..e5f72e4c6 100644 --- a/src/environments/environment.prod.ts +++ b/src/environments/environment.prod.ts @@ -6,4 +6,5 @@ export const environment = { domain: 'gabinetedigital.local', defaultuser: '',//paulo.pinto paulo.pinto@gabinetedigital.local defaultuserpwd: '', //tabteste@006, + chatOffline: true }; diff --git a/src/environments/environment.ts b/src/environments/environment.ts index 37e513724..cd809f519 100644 --- a/src/environments/environment.ts +++ b/src/environments/environment.ts @@ -13,6 +13,7 @@ export const environment = { domain: 'gabinetedigital.local', //gabinetedigital.local defaultuser: 'paulo.pinto@gabinetedigital.local',//paulo.pinto paulo.pinto@gabinetedigital.local defaultuserpwd: 'tabteste@006', //tabteste@006, + chatOffline: true }; /* From 47fd5e3895d9a48b8d28078de92de53e7bcda7ce Mon Sep 17 00:00:00 2001 From: Peter Maquiran Date: Thu, 3 Feb 2022 15:52:21 +0100 Subject: [PATCH 09/27] receive message --- nice.html | 49 +++++++++++++++++++++++++++ src/app/services/auth.service.ts | 2 +- src/app/services/chat/room.service.ts | 19 ++++++----- 3 files changed, 60 insertions(+), 10 deletions(-) create mode 100644 nice.html diff --git a/nice.html b/nice.html new file mode 100644 index 000000000..9e964f49f --- /dev/null +++ b/nice.html @@ -0,0 +1,49 @@ + + + + + + + Document + + + + + + + \ No newline at end of file diff --git a/src/app/services/auth.service.ts b/src/app/services/auth.service.ts index f26ca9f5e..9167fa75d 100644 --- a/src/app/services/auth.service.ts +++ b/src/app/services/auth.service.ts @@ -131,7 +131,7 @@ export class AuthService { localStorage.setItem('userChat', JSON.stringify(responseChat)); this.storageService.store(AuthConnstants.AUTH, responseChat); - this.autologout(10000); + // this.autologout(10000); return true; diff --git a/src/app/services/chat/room.service.ts b/src/app/services/chat/room.service.ts index 2f2e4645d..a3c58eaed 100644 --- a/src/app/services/chat/room.service.ts +++ b/src/app/services/chat/room.service.ts @@ -77,6 +77,11 @@ export class RoomService { this.calDateDuration() } + + isSenderIsNotMe(ChatMessage) { + return SessionStore.user.RochetChatUser != ChatMessage.u.username + } + receiveMessage() { this.WsChatService.updateRoomEventss( @@ -84,7 +89,7 @@ export class RoomService { "stream-room-messages", (ChatMessage) => { - if(environment.chatOffline == false) { + if(environment.chatOffline == false || this.isSenderIsNotMe(ChatMessage)) { ChatMessage = ChatMessage.fields.args[0] ChatMessage = this.fix_updatedAt(ChatMessage) console.log('recivemessage', ChatMessage) @@ -99,14 +104,10 @@ export class RoomService { this.scrollDown() }, 100) - //this.sortService.sortDate(this.messages, '') - - if(SessionStore.user.RochetChatUser != ChatMessage.u.username) { - this.NativeNotificationService.sendNotificationChat({ - message: message.msg, - title: this.name - }); - } + this.NativeNotificationService.sendNotificationChat({ + message: message.msg, + title: this.name + }); this.addMessageDB(ChatMessage) From 33a2982805548f5a9345b65aec51d6dbb4bd8453 Mon Sep 17 00:00:00 2001 From: Peter Maquiran Date: Thu, 3 Feb 2022 16:14:21 +0100 Subject: [PATCH 10/27] send message offline --- src/app/services/chat/ws-chat.service.ts | 10 +++++++++- src/app/shared/chat/messages/messages.page.html | 6 +++--- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/src/app/services/chat/ws-chat.service.ts b/src/app/services/chat/ws-chat.service.ts index 0c97a91a8..4b94ad019 100644 --- a/src/app/services/chat/ws-chat.service.ts +++ b/src/app/services/chat/ws-chat.service.ts @@ -14,7 +14,15 @@ export class WsChatService { isLogin = false; loginResponse = {} - constructor() {} + constructor() { + + + window.addEventListener('online', ()=>{ + this.connect() + this.login() + }); + + } connect() { // dont connect if is already connected diff --git a/src/app/shared/chat/messages/messages.page.html b/src/app/shared/chat/messages/messages.page.html index 37c723586..b132f662f 100644 --- a/src/app/shared/chat/messages/messages.page.html +++ b/src/app/shared/chat/messages/messages.page.html @@ -48,11 +48,11 @@
- {{msg.u.name}} + {{msg.u.name}} {{msg.offline}} {{showDateDuration(msg._updatedAt)}}
- {{msg.msg}} + {{msg.msg}} {{msg.offline}} {{last ? scrollToBottom() : ''}}
@@ -67,7 +67,7 @@
- {{msg.u.name}} + {{msg.u.name}} {{showDateDuration(msg.duration)}}
From 99b33375b85245c7d788c4d547078b3cc29d4f91 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eudes=20In=C3=A1cio?= Date: Thu, 3 Feb 2022 16:36:05 +0100 Subject: [PATCH 11/27] Mobile add picture publiation and chat --- .../group-messages/group-messages.page.ts | 3 + src/app/pages/chat/messages/messages.page.ts | 9 ++- .../new-publication/new-publication.page.ts | 25 ++++--- src/app/services/auth.service.ts | 2 +- src/app/services/functions/file.service.ts | 72 ++++++++++++++----- src/app/shared/chat/messages/messages.page.ts | 1 + .../chat-options-popover.page.html | 2 +- 7 files changed, 81 insertions(+), 33 deletions(-) diff --git a/src/app/pages/chat/group-messages/group-messages.page.ts b/src/app/pages/chat/group-messages/group-messages.page.ts index 385b64a06..56ffae756 100644 --- a/src/app/pages/chat/group-messages/group-messages.page.ts +++ b/src/app/pages/chat/group-messages/group-messages.page.ts @@ -118,6 +118,9 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy { this.getChatMembers(); this.getRoomMessageDB(this.roomId); + this.wsChatMethodsService.getUserOfRoom(this.roomId).then((value) => { + console.log('MEMBER', value) + }) } setStatus(status:string){ diff --git a/src/app/pages/chat/messages/messages.page.ts b/src/app/pages/chat/messages/messages.page.ts index 6558fc4f5..63e80320f 100644 --- a/src/app/pages/chat/messages/messages.page.ts +++ b/src/app/pages/chat/messages/messages.page.ts @@ -123,9 +123,12 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { ngOnInit() { //this.load(); this.setStatus('online'); - + this.wsChatMethodsService.getUserOfRoom(this.roomId).then((value) => { + console.log('MEMBER', value) + }) //this.loadFiles(); VoiceRecorder.requestAudioRecordingPermission(); + this.getChatMembers(); Filesystem.mkdir({ path: IMAGE_DIR, directory: Directory.Data, @@ -541,8 +544,8 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { //this.loadPicture(); } else if (res['data'] == 'add-picture') { - this.fileService.addPictureToChatMobile(roomId); - //this.loadPicture(); + //this.fileService.addPictureToChat(roomId); + this.fileService.loadPicture(this.roomId); } else if (res['data'] == 'add-document') { this.fileService.addDocumentToChat(this.roomId); diff --git a/src/app/pages/publications/new-publication/new-publication.page.ts b/src/app/pages/publications/new-publication/new-publication.page.ts index 479be1a7c..1c66f87bf 100644 --- a/src/app/pages/publications/new-publication/new-publication.page.ts +++ b/src/app/pages/publications/new-publication/new-publication.page.ts @@ -172,20 +172,23 @@ export class NewPublicationPage implements OnInit { this.capturedImageTitle = new Date().getTime() + '.jpeg'; } */ - laodPicture() { - const input = this.fileLoaderService.createInput({ - accept: ['image/apng', 'image/jpeg', 'image/png'] - }) + async laodPicture() { + + const capturedImage = await Camera.getPhoto({ + quality: 90, + // allowEditing: true, + resultType: CameraResultType.Uri, + source: CameraSource.Photos + }); - input.onchange = async () => { - const file = this.fileLoaderService.getFirstFile(input) + const response = await fetch(capturedImage.webPath!); + const blob = await response.blob(); - const imageData = await this.fileToBase64Service.convert(file) - this.capturedImage = imageData; - this.capturedImageTitle = file.name + this.convertBlobToBase64Worker.postMessage(blob); + this.convertBlobToBase64Worker.onmessage = async (oEvent)=> { + this.capturedImage = oEvent.data - console.log(this.capturedImage) - }; + } } diff --git a/src/app/services/auth.service.ts b/src/app/services/auth.service.ts index f26ca9f5e..6c844238f 100644 --- a/src/app/services/auth.service.ts +++ b/src/app/services/auth.service.ts @@ -131,7 +131,7 @@ export class AuthService { localStorage.setItem('userChat', JSON.stringify(responseChat)); this.storageService.store(AuthConnstants.AUTH, responseChat); - this.autologout(10000); + /* this.autologout(10000); */ return true; diff --git a/src/app/services/functions/file.service.ts b/src/app/services/functions/file.service.ts index f864b398f..f7c684859 100644 --- a/src/app/services/functions/file.service.ts +++ b/src/app/services/functions/file.service.ts @@ -41,6 +41,7 @@ export class FileService { headers: HttpHeaders; downloadProgess = 0; downloadFilename: any; + convertBlobToBase64Worker; constructor( private fileLoaderService: FileLoaderService, @@ -146,27 +147,64 @@ export class FileService { reader.readAsDataURL(blob); }); - async loadPicture() { - const input = this.fileLoaderService.createInput({ - accept: ['image/apng', 'image/jpeg', 'image/png', '.pdf'] - }) + async loadPicture(roomid) { + const capturedImage = await Camera.getPhoto({ + quality: 90, + // allowEditing: true, + resultType: CameraResultType.Uri, + source: CameraSource.Photos + }); - input.onchange = async () => { - const file = this.fileLoaderService.getFirstFile(input) + const response = await fetch(capturedImage.webPath!); + const blob = await response.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); - console.log(file); - const imageData = await this.fileToBase64Service.convert(file) - this.capturedImage = imageData; - this.capturedImageTitle = file.name; + this.downloadFile(guid.path).subscribe(async (event) => { - let data = { - image:this.capturedImage, - name: this.capturedImageTitle - } + 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!"); + }); - return data; - }; + }); + } + + }); } //new method1 @@ -336,7 +374,7 @@ export class FileService { quality: 50, // allowEditing: true, resultType: CameraResultType.Uri, - source: CameraSource.Camera + source: CameraSource.Photos }); diff --git a/src/app/shared/chat/messages/messages.page.ts b/src/app/shared/chat/messages/messages.page.ts index f799c6d64..f61e12a17 100644 --- a/src/app/shared/chat/messages/messages.page.ts +++ b/src/app/shared/chat/messages/messages.page.ts @@ -114,6 +114,7 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy ngOnInit() { this.scrollToBottom(); this.setStatus('online'); + this.getChatMembers(); } diff --git a/src/app/shared/popover/chat-options-popover/chat-options-popover.page.html b/src/app/shared/popover/chat-options-popover/chat-options-popover.page.html index fb5cc2d04..96b7c7ae8 100644 --- a/src/app/shared/popover/chat-options-popover/chat-options-popover.page.html +++ b/src/app/shared/popover/chat-options-popover/chat-options-popover.page.html @@ -8,7 +8,7 @@
- +
From 61de7b937b7f99aebd6a25377c22f44a748a1aac Mon Sep 17 00:00:00 2001 From: Peter Maquiran Date: Thu, 3 Feb 2022 21:01:53 +0100 Subject: [PATCH 12/27] improve chat --- .../group-messages/group-messages.page.ts | 218 ++++++++- src/app/pages/chat/messages/messages.page.ts | 311 ++++++++----- src/app/services/attachments.service.ts | 41 ++ src/app/services/camera.service.spec.ts | 16 + src/app/services/camera.service.ts | 36 ++ src/app/services/chat/message.service.ts | 44 +- src/app/services/chat/room.service.ts | 88 +++- .../services/chat/ws-chat-methods.service.ts | 2 +- src/app/services/file-system.service.spec.ts | 16 + src/app/services/file-system.service.ts | 145 ++++++ src/app/services/functions/file.service.ts | 429 +----------------- .../group-messages/group-messages.page.ts | 226 ++++++++- src/app/shared/chat/messages/messages.page.ts | 243 +++++++--- 13 files changed, 1147 insertions(+), 668 deletions(-) create mode 100644 src/app/services/camera.service.spec.ts create mode 100644 src/app/services/camera.service.ts create mode 100644 src/app/services/file-system.service.spec.ts create mode 100644 src/app/services/file-system.service.ts diff --git a/src/app/pages/chat/group-messages/group-messages.page.ts b/src/app/pages/chat/group-messages/group-messages.page.ts index 385b64a06..d0de49f31 100644 --- a/src/app/pages/chat/group-messages/group-messages.page.ts +++ b/src/app/pages/chat/group-messages/group-messages.page.ts @@ -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; diff --git a/src/app/pages/chat/messages/messages.page.ts b/src/app/pages/chat/messages/messages.page.ts index 605f83532..9568bcd3b 100644 --- a/src/app/pages/chat/messages/messages.page.ts +++ b/src/app/pages/chat/messages/messages.page.ts @@ -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; diff --git a/src/app/services/attachments.service.ts b/src/app/services/attachments.service.ts index fa0be2ba1..1c20db0dd 100644 --- a/src/app/services/attachments.service.ts +++ b/src/app/services/attachments.service.ts @@ -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(`${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{ let geturl = environment.apiURL + 'attachments/GetAttachments'; let params = new HttpParams(); diff --git a/src/app/services/camera.service.spec.ts b/src/app/services/camera.service.spec.ts new file mode 100644 index 000000000..73b57d3a5 --- /dev/null +++ b/src/app/services/camera.service.spec.ts @@ -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(); + }); +}); diff --git a/src/app/services/camera.service.ts b/src/app/services/camera.service.ts new file mode 100644 index 000000000..b99fd6956 --- /dev/null +++ b/src/app/services/camera.service.ts @@ -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(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; + }) + + } +} diff --git a/src/app/services/chat/message.service.ts b/src/app/services/chat/message.service.ts index 43c8f74be..758e296a5 100644 --- a/src/app/services/chat/message.service.ts +++ b/src/app/services/chat/message.service.ts @@ -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 + } + } diff --git a/src/app/services/chat/room.service.ts b/src/app/services/chat/room.service.ts index a3c58eaed..1112c4a23 100644 --- a/src/app/services/chat/room.service.ts +++ b/src/app/services/chat/room.service.ts @@ -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 } diff --git a/src/app/services/chat/ws-chat-methods.service.ts b/src/app/services/chat/ws-chat-methods.service.ts index 985041e86..1129e85a9 100644 --- a/src/app/services/chat/ws-chat-methods.service.ts +++ b/src/app/services/chat/ws-chat-methods.service.ts @@ -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, diff --git a/src/app/services/file-system.service.spec.ts b/src/app/services/file-system.service.spec.ts new file mode 100644 index 000000000..f6d5285f4 --- /dev/null +++ b/src/app/services/file-system.service.spec.ts @@ -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(); + }); +}); diff --git a/src/app/services/file-system.service.ts b/src/app/services/file-system.service.ts new file mode 100644 index 000000000..668cede8a --- /dev/null +++ b/src/app/services/file-system.service.ts @@ -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} + + } + + +} diff --git a/src/app/services/functions/file.service.ts b/src/app/services/functions/file.service.ts index f864b398f..b279a0f7d 100644 --- a/src/app/services/functions/file.service.ts +++ b/src/app/services/functions/file.service.ts @@ -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; 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(`${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((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(); diff --git a/src/app/shared/chat/group-messages/group-messages.page.ts b/src/app/shared/chat/group-messages/group-messages.page.ts index 5747db9e1..f61c9c520 100644 --- a/src/app/shared/chat/group-messages/group-messages.page.ts +++ b/src/app/shared/chat/group-messages/group-messages.page.ts @@ -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; diff --git a/src/app/shared/chat/messages/messages.page.ts b/src/app/shared/chat/messages/messages.page.ts index f799c6d64..5f093b9e0 100644 --- a/src/app/shared/chat/messages/messages.page.ts +++ b/src/app/shared/chat/messages/messages.page.ts @@ -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; From 0f04ad98c235b3f83a07adbde7fa15f3638c4ca8 Mon Sep 17 00:00:00 2001 From: Peter Maquiran Date: Fri, 4 Feb 2022 00:22:35 +0100 Subject: [PATCH 13/27] offline messagens --- .../group-messages/group-messages.page.html | 2 +- .../group-messages/group-messages.page.ts | 118 +++++++++++------ .../pages/chat/messages/messages.page.html | 2 +- src/app/pages/chat/messages/messages.page.ts | 120 +++++++++++------ src/app/services/chat/message.service.ts | 27 +++- src/app/services/chat/room.service.ts | 82 +++++------- src/app/services/chat/ws-chat.service.ts | 23 ++-- .../group-messages/group-messages.page.html | 2 +- .../group-messages/group-messages.page.ts | 118 +++++++++++------ .../shared/chat/messages/messages.page.html | 2 +- src/app/shared/chat/messages/messages.page.ts | 124 ++++++++++++------ 11 files changed, 381 insertions(+), 239 deletions(-) diff --git a/src/app/pages/chat/group-messages/group-messages.page.html b/src/app/pages/chat/group-messages/group-messages.page.html index cdfd4646b..c4a428958 100644 --- a/src/app/pages/chat/group-messages/group-messages.page.html +++ b/src/app/pages/chat/group-messages/group-messages.page.html @@ -121,7 +121,7 @@ {{file.description}} • - {{msg.file.type.replace('application/','').toUpperCase()}} + {{msg.displayType}}
diff --git a/src/app/pages/chat/group-messages/group-messages.page.ts b/src/app/pages/chat/group-messages/group-messages.page.ts index d0de49f31..b6c4dca14 100644 --- a/src/app/pages/chat/group-messages/group-messages.page.ts +++ b/src/app/pages/chat/group-messages/group-messages.page.ts @@ -339,7 +339,7 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy { sendMessage() { - this.wsChatMethodsService.getGroupRoom(this.roomId).send() + this.wsChatMethodsService.getGroupRoom(this.roomId).send({}) } async openOptions() { @@ -503,13 +503,36 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy { const lastphoto: any = await this.FileSystemService.loadFiles(roomId); const { capturedImage, capturedImageTitle} = await this.FileSystemService.loadFileData(lastphoto, roomId); + const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(this.roomId).send({ + file: { + "type": "application/img", + "guid": '', + "image_url": capturedImage + }, + attachments: [{ + //"title": this.capturedImageTitle , + //"text": "description", + "title_link_download": false, + //"image_url": this.capturedImage, + }] + }) + + 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); + updateMessage({ + file: { + type: "application/img", + guid: guid.path, + image_url: capturedImage + } + }) this.AttachmentsService.downloadFile(guid.path).subscribe(async (event) => { @@ -518,25 +541,12 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy { //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', capturedImage); + await this.storage.set(guid.path, capturedImage).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, - }] - }) - + message.getFileFromDb() }); + } }); @@ -565,15 +575,10 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy { modal.onDidDismiss().then(async res=>{ const data = res.data; - if(data.selected){ + 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", + const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(this.roomId).send({ file:{ "name": res.data.selected.Assunto, "type": "application/webtrix", @@ -581,6 +586,22 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy { "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" + }] + }) + + 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); + + updateMessage({ attachments: [{ "title": res.data.selected.Assunto, "description": res.data.selected.DocTypeDesc, @@ -591,6 +612,7 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy { "type": "webtrix" }] }) + loader.remove(); } @@ -598,11 +620,37 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy { } + async addFileToChat(types: typeof FileType[] ) { const file = await this.fileService.getFileFromDevice(types); + const imageData = await this.fileToBase64Service.convert(file) + const formData = new FormData(); formData.append("blobFile", file); + + const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(this.roomId).send({ + file: { + "type": "application/img", + "guid": '', + "image_url": imageData + }, + attachments: [{ + //"title": this.capturedImageTitle , + //"text": "description", + "title_link_download": false, + //"image_url": this.capturedImage, + }] + }) + let guid: any = await this.AttachmentsService.uploadFile(formData).toPromise() + updateMessage({ + file: { + type: "application/img", + guid: guid.path, + image_url: imageData + } + }) + this.AttachmentsService.downloadFile(guid.path).subscribe(async (event) => { if (event.type === HttpEventType.DownloadProgress) { @@ -613,21 +661,7 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy { 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, - }] - }) - + message.getFileFromDb() }); } @@ -680,7 +714,7 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy { await this.storage.set(guid.path, fileImage).then(() => { console.log('add picture to chat IMAGE SAVED') - this.wsChatMethodsService.getDmRoom(this.roomId).sendFile({ + this.wsChatMethodsService.getDmRoom(this.roomId).send({ file: { "type": "application/img", "guid": guid.path, diff --git a/src/app/pages/chat/messages/messages.page.html b/src/app/pages/chat/messages/messages.page.html index ee9612b12..dabd8c88d 100644 --- a/src/app/pages/chat/messages/messages.page.html +++ b/src/app/pages/chat/messages/messages.page.html @@ -102,7 +102,7 @@ {{file.description}} • - {{msg.file.type.replace('application/','').toUpperCase()}} + {{msg.displayType}}
diff --git a/src/app/pages/chat/messages/messages.page.ts b/src/app/pages/chat/messages/messages.page.ts index 9568bcd3b..3c4da98de 100644 --- a/src/app/pages/chat/messages/messages.page.ts +++ b/src/app/pages/chat/messages/messages.page.ts @@ -38,6 +38,7 @@ 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'; +import { FileToBase64Service } from 'src/app/services/file/file-to-base64.service'; const IMAGE_DIR = 'stored-images'; @@ -111,6 +112,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { private CameraService: CameraService, private processesService: ProcessesService, private storage: Storage, + private fileToBase64Service: FileToBase64Service, ) { this.loggedUser = authService.ValidatedUserChat['data']; this.roomId = this.navParams.get('roomId'); @@ -347,7 +349,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { } sendMessage() { - this.wsChatMethodsService.getDmRoom(this.roomId).send() + this.wsChatMethodsService.getDmRoom(this.roomId).send({}) } @@ -524,13 +526,36 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { const lastphoto: any = await this.FileSystemService.loadFiles(roomId); const { capturedImage, capturedImageTitle} = await this.FileSystemService.loadFileData(lastphoto, roomId); + const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(this.roomId).send({ + file: { + "type": "application/img", + "guid": '', + "image_url": capturedImage + }, + attachments: [{ + //"title": this.capturedImageTitle , + //"text": "description", + "title_link_download": false, + //"image_url": this.capturedImage, + }] + }) + + 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); + updateMessage({ + file: { + type: "application/img", + guid: guid.path, + image_url: capturedImage + } + }) this.AttachmentsService.downloadFile(guid.path).subscribe(async (event) => { @@ -539,25 +564,12 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { //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', capturedImage); + await this.storage.set(guid.path, capturedImage).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, - }] - }) - + message.getFileFromDb() }); + } }); @@ -586,15 +598,10 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { modal.onDidDismiss().then(async res=>{ const data = res.data; - if(data.selected){ + 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", + const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(this.roomId).send({ file:{ "name": res.data.selected.Assunto, "type": "application/webtrix", @@ -602,6 +609,22 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { "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" + }] + }) + + 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); + + updateMessage({ attachments: [{ "title": res.data.selected.Assunto, "description": res.data.selected.DocTypeDesc, @@ -612,6 +635,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { "type": "webtrix" }] }) + loader.remove(); } @@ -619,11 +643,37 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { } + async addFileToChat(types: typeof FileType[] ) { const file = await this.fileService.getFileFromDevice(types); + const imageData = await this.fileToBase64Service.convert(file) + const formData = new FormData(); formData.append("blobFile", file); + + const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(this.roomId).send({ + file: { + "type": "application/img", + "guid": '', + "image_url": imageData + }, + attachments: [{ + //"title": this.capturedImageTitle , + //"text": "description", + "title_link_download": false, + //"image_url": this.capturedImage, + }] + }) + let guid: any = await this.AttachmentsService.uploadFile(formData).toPromise() + updateMessage({ + file: { + type: "application/img", + guid: guid.path, + image_url: imageData + } + }) + this.AttachmentsService.downloadFile(guid.path).subscribe(async (event) => { if (event.type === HttpEventType.DownloadProgress) { @@ -634,21 +684,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { 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, - }] - }) - + message.getFileFromDb() }); } @@ -701,7 +737,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { await this.storage.set(guid.path, fileImage).then(() => { console.log('add picture to chat IMAGE SAVED') - this.wsChatMethodsService.getDmRoom(this.roomId).sendFile({ + this.wsChatMethodsService.getDmRoom(this.roomId).send({ file: { "type": "application/img", "guid": guid.path, diff --git a/src/app/services/chat/message.service.ts b/src/app/services/chat/message.service.ts index 758e296a5..6eb0f3015 100644 --- a/src/app/services/chat/message.service.ts +++ b/src/app/services/chat/message.service.ts @@ -23,6 +23,7 @@ export class MessageService { file attachments offline = true + displayType = '' constructor(private storage: Storage) { } @@ -49,14 +50,16 @@ export class MessageService { if (this.file) { - if (this.file.guid) { - this.storage.get(this.file.guid).then((image) => { - // console.log('IMAGE FROM STORAGE', image) - this.file.image_url = image - }); + this.getFileFromDb() + if(this.file.type) { + if(this.file.type != 'application/webtrix' && typeof(this.file.type) == 'string') { + this.displayType = this.file.type.replace('application/','').toUpperCase() + } } + } + } delete() {} @@ -75,4 +78,18 @@ export class MessageService { return firstName + ' ' + lastName } + + getFileFromDb() { + if (this.file) { + if (this.file.guid) { + this.storage.get(this.file.guid).then((image) => { + if(image != null) { + this.file.image_url = image + } + + }); + } + } + } + } diff --git a/src/app/services/chat/room.service.ts b/src/app/services/chat/room.service.ts index 1112c4a23..7a32579ed 100644 --- a/src/app/services/chat/room.service.ts +++ b/src/app/services/chat/room.service.ts @@ -54,6 +54,7 @@ export class RoomService { } sortRoomList = () => {} + uploadAttachment = (formData) => {} constructor( public WsChatService: WsChatService, @@ -204,51 +205,9 @@ export class RoomService { /** * @description sen text message */ - send() { - - if(environment.chatOffline == false) { - this.WsChatService.send(this.id, this.message) - this.message= '' - } else { - - const offlineChatMessage = { - channels: [], - mentions: [], - rid: this.id, - msg: this.message, - u: { - name: this.usernameToDisplayName(SessionStore.user.RochetChatUser), - username: SessionStore.user.RochetChatUser, - _id: "" - }, - _updatedAt: new Date().getTime(), - offline: true - } - - this.addMessageDB(offlineChatMessage) - const message: MessageService = this.prepareMessage(offlineChatMessage) - - setTimeout(() => { - this.scrollDown() - }, 150) - - this.lastMessage = message + send({file = null, attachments = null}) { - 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= '' - } - - } - - sendFile({file, attachments, alias = 'document'}) { let offlineChatMessage = { rid: this.id, msg: this.message, @@ -265,16 +224,35 @@ export class RoomService { this.lastMessage = message + + if(file == null && attachments == null) { + console.log('simple send') + this.WsChatService.send({roomId:this.id, msg:message.msg}).then((data: any) => { + let ChatMessage = data.result + this.redefinedMessage(message, ChatMessage) + }) + } else { + console.log('complex send') + return { + message: message, + updateMessage: (update)=> { + offlineChatMessage = Object.assign(offlineChatMessage, update) + + this.WsChatService.send({roomId:this.id, msg:message.msg,attachments:offlineChatMessage.attachments, file:offlineChatMessage.file}).then((data: any) => { + console.log('send sucees', data.result) + let ChatMessage = data.result + this.redefinedMessage(message, ChatMessage) + }) + + } + } + } + + 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) => { - }); + this.message= '' } redefinedMessage (message: MessageService, ChatMessage) { @@ -362,11 +340,13 @@ export class RoomService { let localMessages = [] + if(messages==null) messages = [] + messages.forEach((ChatMessage, index) => { const wewMessage = this.prepareMessage(ChatMessage) if(wewMessage.offline == true) { - this.WsChatService.send(this.id, wewMessage.msg).then((data: any) => { + this.WsChatService.send({roomId:this.id, msg:wewMessage.msg, attachments:wewMessage.attachments, file: wewMessage.file}).then((data: any) => { let _ChatMessage = data.result this.redefinedMessage(wewMessage, _ChatMessage) this.storage.set('chatmsg' + this.id, messages) diff --git a/src/app/services/chat/ws-chat.service.ts b/src/app/services/chat/ws-chat.service.ts index 4b94ad019..593b79276 100644 --- a/src/app/services/chat/ws-chat.service.ts +++ b/src/app/services/chat/ws-chat.service.ts @@ -162,7 +162,7 @@ export class WsChatService { } // send message to room - send(roomId, msg) { + send({roomId, msg, attachments = null, file = null}) { const requestId = uuidv4() @@ -171,9 +171,10 @@ export class WsChatService { method: "sendMessage", id: requestId, params: [{ - _id: uuidv4(), rid: roomId, - msg: msg + msg: msg, + attachments, + file }] } @@ -181,7 +182,7 @@ export class WsChatService { return new Promise((resolve, reject) => { this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ - if(message.id == requestId || deepFind(message,'result.id') == requestId) { // same request send + if(message.id == requestId ) { // same request send resolve(message) return true } @@ -206,7 +207,7 @@ export class WsChatService { return new Promise((resolve, reject) => { this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ - if(message.id == requestId || deepFind(message,'result.id') == requestId) { // same request send + if(message.id == requestId ) { // same request send resolve(message) return true } @@ -232,7 +233,7 @@ export class WsChatService { return new Promise((resolve, reject) => { this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ - if(message.id == requestId || deepFind(message,'result.id') == requestId) { // same request send + if(message.id == requestId ) { // same request send resolve(message) return true } @@ -255,7 +256,7 @@ export class WsChatService { return new Promise((resolve, reject) => { this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ - if(message.id == requestId || deepFind(message,'result.id') == requestId) { // same request send + if(message.id == requestId ) { // same request send resolve(message) return true } @@ -310,7 +311,7 @@ export class WsChatService { return new Promise((resolve, reject) => { this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ - if(message.id == requestId || deepFind(message,'result.id') == requestId) { // same request send + if(message.id == requestId ) { // same request send resolve(message) return true } @@ -337,7 +338,7 @@ export class WsChatService { return new Promise((resolve, reject) => { this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ - if(message.id == requestId || deepFind(message,'result.id') == requestId) { // same request send + if(message.id == requestId ) { // same request send resolve(message) return true } @@ -565,7 +566,7 @@ updateRoomEventss(roomId, collection:string, funx: Function, ) { return new Promise((resolve, reject) => { this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ - if(message.id == requestId || deepFind(message,'result.id') == requestId) { // same request send + if(message.id == requestId ) { // same request send resolve(message) return true } @@ -592,7 +593,7 @@ updateRoomEventss(roomId, collection:string, funx: Function, ) { return new Promise((resolve, reject) => { this.ws.registerCallback({type:'Onmessage', funx:(message)=>{ - if(message.id == requestId || deepFind(message,'result.id') == requestId) { // same request send + if(message.id == requestId ) { // same request send resolve(message) return true } diff --git a/src/app/shared/chat/group-messages/group-messages.page.html b/src/app/shared/chat/group-messages/group-messages.page.html index 2bbb6b651..7538b7768 100644 --- a/src/app/shared/chat/group-messages/group-messages.page.html +++ b/src/app/shared/chat/group-messages/group-messages.page.html @@ -97,7 +97,7 @@ {{file.description}} • - {{msg.file.type.replace('application/','').toUpperCase()}} + {{msg.displayType}}
diff --git a/src/app/shared/chat/group-messages/group-messages.page.ts b/src/app/shared/chat/group-messages/group-messages.page.ts index f61c9c520..870e8b7f6 100644 --- a/src/app/shared/chat/group-messages/group-messages.page.ts +++ b/src/app/shared/chat/group-messages/group-messages.page.ts @@ -317,7 +317,7 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe } sendMessage() { - this.wsChatMethodsService.getGroupRoom(this.roomId).send() + this.wsChatMethodsService.getGroupRoom(this.roomId).send({}) } deleteMessage(msgId: string, room:any) { @@ -674,13 +674,36 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe const lastphoto: any = await this.FileSystemService.loadFiles(roomId); const { capturedImage, capturedImageTitle} = await this.FileSystemService.loadFileData(lastphoto, roomId); + const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(this.roomId).send({ + file: { + "type": "application/img", + "guid": '', + "image_url": capturedImage + }, + attachments: [{ + //"title": this.capturedImageTitle , + //"text": "description", + "title_link_download": false, + //"image_url": this.capturedImage, + }] + }) + + 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); + updateMessage({ + file: { + type: "application/img", + guid: guid.path, + image_url: capturedImage + } + }) this.AttachmentsService.downloadFile(guid.path).subscribe(async (event) => { @@ -689,25 +712,12 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe //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', capturedImage); + await this.storage.set(guid.path, capturedImage).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, - }] - }) - + message.getFileFromDb() }); + } }); @@ -736,15 +746,10 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe modal.onDidDismiss().then(async res=>{ const data = res.data; - if(data.selected){ + 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", + const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(this.roomId).send({ file:{ "name": res.data.selected.Assunto, "type": "application/webtrix", @@ -752,6 +757,22 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe "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" + }] + }) + + 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); + + updateMessage({ attachments: [{ "title": res.data.selected.Assunto, "description": res.data.selected.DocTypeDesc, @@ -762,6 +783,7 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe "type": "webtrix" }] }) + loader.remove(); } @@ -769,11 +791,37 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe } + async addFileToChat(types: typeof FileType[] ) { const file = await this.fileService.getFileFromDevice(types); + const imageData = await this.fileToBase64Service.convert(file) + const formData = new FormData(); formData.append("blobFile", file); + + const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(this.roomId).send({ + file: { + "type": "application/img", + "guid": '', + "image_url": imageData + }, + attachments: [{ + //"title": this.capturedImageTitle , + //"text": "description", + "title_link_download": false, + //"image_url": this.capturedImage, + }] + }) + let guid: any = await this.AttachmentsService.uploadFile(formData).toPromise() + updateMessage({ + file: { + type: "application/img", + guid: guid.path, + image_url: imageData + } + }) + this.AttachmentsService.downloadFile(guid.path).subscribe(async (event) => { if (event.type === HttpEventType.DownloadProgress) { @@ -784,21 +832,7 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe 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, - }] - }) - + message.getFileFromDb() }); } @@ -887,7 +921,7 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe await this.storage.set(guid.path, fileImage).then(() => { console.log('add picture to chat IMAGE SAVED') - this.wsChatMethodsService.getDmRoom(this.roomId).sendFile({ + this.wsChatMethodsService.getDmRoom(this.roomId).send({ file: { "type": "application/img", "guid": guid.path, diff --git a/src/app/shared/chat/messages/messages.page.html b/src/app/shared/chat/messages/messages.page.html index b132f662f..16c0804e9 100644 --- a/src/app/shared/chat/messages/messages.page.html +++ b/src/app/shared/chat/messages/messages.page.html @@ -97,7 +97,7 @@ {{file.description}} • {{msg.file.type.replace('application/','').toUpperCase()}} + *ngIf="msg.file.type != 'application/webtrix'">{{msg.displayType}}
diff --git a/src/app/shared/chat/messages/messages.page.ts b/src/app/shared/chat/messages/messages.page.ts index 5f093b9e0..a9ad0190f 100644 --- a/src/app/shared/chat/messages/messages.page.ts +++ b/src/app/shared/chat/messages/messages.page.ts @@ -32,6 +32,7 @@ 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'; +import { FileToBase64Service } from 'src/app/services/file/file-to-base64.service'; const IMAGE_DIR = 'stored-images'; @Component({ @@ -102,6 +103,7 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy private FileSystemService: FileSystemService, private CameraService: CameraService, private processesService: ProcessesService, + private fileToBase64Service: FileToBase64Service, ) { this.loggedUser = authService.ValidatedUserChat['data']; @@ -113,6 +115,11 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy this.wsChatMethodsService.getDmRoom(this.roomId).scrollDown = this.scrollToBottomClicked this.wsChatMethodsService.openRoom(this.roomId) + + this.wsChatMethodsService.getDmRoom(this.roomId).uploadAttachment = async (formData) => { + let guid: any = await this.AttachmentsService.uploadFile(formData).toPromise() + } + setTimeout(() => { this.scrollToBottomClicked() }, 150) @@ -238,7 +245,7 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy } sendMessage() { - this.wsChatMethodsService.getDmRoom(this.roomId).send() + this.wsChatMethodsService.getDmRoom(this.roomId).send({}) } deleteMessage(msgId: string, room:any) { @@ -443,13 +450,36 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy const lastphoto: any = await this.FileSystemService.loadFiles(roomId); const { capturedImage, capturedImageTitle} = await this.FileSystemService.loadFileData(lastphoto, roomId); + const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(this.roomId).send({ + file: { + "type": "application/img", + "guid": '', + "image_url": capturedImage + }, + attachments: [{ + //"title": this.capturedImageTitle , + //"text": "description", + "title_link_download": false, + //"image_url": this.capturedImage, + }] + }) + + 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); + updateMessage({ + file: { + type: "application/img", + guid: guid.path, + image_url: capturedImage + } + }) this.AttachmentsService.downloadFile(guid.path).subscribe(async (event) => { @@ -458,26 +488,12 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy //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', capturedImage); + await this.storage.set(guid.path, capturedImage).then(() => { console.log('add picture to chat IMAGE SAVED') + message.getFileFromDb() }); - 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, - }] - }) - } }); @@ -506,15 +522,10 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy modal.onDidDismiss().then(async res=>{ const data = res.data; - if(data.selected){ + 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", + const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(this.roomId).send({ file:{ "name": res.data.selected.Assunto, "type": "application/webtrix", @@ -522,6 +533,22 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy "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" + }] + }) + + 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); + + updateMessage({ attachments: [{ "title": res.data.selected.Assunto, "description": res.data.selected.DocTypeDesc, @@ -532,6 +559,7 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy "type": "webtrix" }] }) + loader.remove(); } @@ -539,11 +567,37 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy } + async addFileToChat(types: typeof FileType[] ) { const file = await this.fileService.getFileFromDevice(types); + const imageData = await this.fileToBase64Service.convert(file) + const formData = new FormData(); formData.append("blobFile", file); + + const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(this.roomId).send({ + file: { + "type": "application/img", + "guid": '', + "image_url": imageData + }, + attachments: [{ + //"title": this.capturedImageTitle , + //"text": "description", + "title_link_download": false, + //"image_url": this.capturedImage, + }] + }) + let guid: any = await this.AttachmentsService.uploadFile(formData).toPromise() + updateMessage({ + file: { + type: "application/img", + guid: guid.path, + image_url: imageData + } + }) + this.AttachmentsService.downloadFile(guid.path).subscribe(async (event) => { if (event.type === HttpEventType.DownloadProgress) { @@ -554,21 +608,7 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy 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, - }] - }) - + message.getFileFromDb() }); } @@ -585,7 +625,7 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy } - chatSendFile() { + chatsend() { } From 3b6e519adb23542276b26847734d6eb53f1465a1 Mon Sep 17 00:00:00 2001 From: Peter Maquiran Date: Fri, 4 Feb 2022 00:54:41 +0100 Subject: [PATCH 14/27] fix --- .../group-messages/group-messages.page.ts | 30 ++++++++++++++----- src/app/pages/chat/messages/messages.page.ts | 11 ++++--- src/app/shared/chat/messages/messages.page.ts | 10 +++---- 3 files changed, 31 insertions(+), 20 deletions(-) diff --git a/src/app/pages/chat/group-messages/group-messages.page.ts b/src/app/pages/chat/group-messages/group-messages.page.ts index b6c4dca14..3a98cd9a3 100644 --- a/src/app/pages/chat/group-messages/group-messages.page.ts +++ b/src/app/pages/chat/group-messages/group-messages.page.ts @@ -638,18 +638,15 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy { //"title": this.capturedImageTitle , //"text": "description", "title_link_download": false, - //"image_url": this.capturedImage, + "type": "application/img", + "guid": '', + "image_url": imageData }] }) let guid: any = await this.AttachmentsService.uploadFile(formData).toPromise() - updateMessage({ - file: { - type: "application/img", - guid: guid.path, - image_url: imageData - } - }) + message.file.guid = guid.path + this.AttachmentsService.downloadFile(guid.path).subscribe(async (event) => { @@ -659,6 +656,23 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy { } 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); + + updateMessage({ + file: { + type: "application/img", + guid: guid.path, + image_url: fileImage + }, + attachments: [{ + //"title": this.capturedImageTitle , + //"text": "description", + "title_link_download": false, + "type": "application/img", + guid: guid.path, + "image_url": fileImage + }] + }) + await this.storage.set(guid.path, fileImage).then(() => { console.log('add picture to chat IMAGE SAVED') message.getFileFromDb() diff --git a/src/app/pages/chat/messages/messages.page.ts b/src/app/pages/chat/messages/messages.page.ts index 3c4da98de..d4cf829be 100644 --- a/src/app/pages/chat/messages/messages.page.ts +++ b/src/app/pages/chat/messages/messages.page.ts @@ -658,10 +658,9 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { "image_url": imageData }, attachments: [{ - //"title": this.capturedImageTitle , - //"text": "description", + "title": file.name, "title_link_download": false, - //"image_url": this.capturedImage, + "image_url": imageData, }] }) @@ -744,10 +743,10 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { "image_url": fileImage }, attachments: [{ - //"title": this.capturedImageTitle , - //"text": "description", + "title": capturedImageTitle , + "text": "description", "title_link_download": false, - //"image_url": this.capturedImage, + "image_url": capturedImage, }] }) diff --git a/src/app/shared/chat/messages/messages.page.ts b/src/app/shared/chat/messages/messages.page.ts index a9ad0190f..cb4ec06fb 100644 --- a/src/app/shared/chat/messages/messages.page.ts +++ b/src/app/shared/chat/messages/messages.page.ts @@ -457,10 +457,9 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy "image_url": capturedImage }, attachments: [{ - //"title": this.capturedImageTitle , - //"text": "description", + "title": capturedImageTitle , + "text": "description", "title_link_download": false, - //"image_url": this.capturedImage, }] }) @@ -582,10 +581,9 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy "image_url": imageData }, attachments: [{ - //"title": this.capturedImageTitle , - //"text": "description", + "title": file.name , + "text": "description", "title_link_download": false, - //"image_url": this.capturedImage, }] }) From 7ee2289ca01a469e7185b051a329838f3ce15696 Mon Sep 17 00:00:00 2001 From: Peter Maquiran Date: Fri, 4 Feb 2022 00:57:46 +0100 Subject: [PATCH 15/27] fix --- .../group-messages/group-messages.page.ts | 38 ++++++------------- src/app/pages/chat/messages/messages.page.ts | 9 ++--- .../group-messages/group-messages.page.ts | 10 ++--- 3 files changed, 19 insertions(+), 38 deletions(-) diff --git a/src/app/pages/chat/group-messages/group-messages.page.ts b/src/app/pages/chat/group-messages/group-messages.page.ts index 3a98cd9a3..3e8d02d58 100644 --- a/src/app/pages/chat/group-messages/group-messages.page.ts +++ b/src/app/pages/chat/group-messages/group-messages.page.ts @@ -510,10 +510,9 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy { "image_url": capturedImage }, attachments: [{ - //"title": this.capturedImageTitle , - //"text": "description", + "title": capturedImageTitle , + "text": "description", "title_link_download": false, - //"image_url": this.capturedImage, }] }) @@ -635,18 +634,20 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy { "image_url": imageData }, attachments: [{ - //"title": this.capturedImageTitle , - //"text": "description", + "title": file.name , + "text": "description", "title_link_download": false, - "type": "application/img", - "guid": '', - "image_url": imageData }] }) let guid: any = await this.AttachmentsService.uploadFile(formData).toPromise() - message.file.guid = guid.path - + updateMessage({ + file: { + type: "application/img", + guid: guid.path, + image_url: imageData + } + }) this.AttachmentsService.downloadFile(guid.path).subscribe(async (event) => { @@ -656,23 +657,6 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy { } 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); - - updateMessage({ - file: { - type: "application/img", - guid: guid.path, - image_url: fileImage - }, - attachments: [{ - //"title": this.capturedImageTitle , - //"text": "description", - "title_link_download": false, - "type": "application/img", - guid: guid.path, - "image_url": fileImage - }] - }) - await this.storage.set(guid.path, fileImage).then(() => { console.log('add picture to chat IMAGE SAVED') message.getFileFromDb() diff --git a/src/app/pages/chat/messages/messages.page.ts b/src/app/pages/chat/messages/messages.page.ts index d4cf829be..b47923aa5 100644 --- a/src/app/pages/chat/messages/messages.page.ts +++ b/src/app/pages/chat/messages/messages.page.ts @@ -533,10 +533,9 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { "image_url": capturedImage }, attachments: [{ - //"title": this.capturedImageTitle , - //"text": "description", + "title": capturedImageTitle , + "text": "description", "title_link_download": false, - //"image_url": this.capturedImage, }] }) @@ -658,9 +657,9 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { "image_url": imageData }, attachments: [{ - "title": file.name, + "title": file.name , + "text": "description", "title_link_download": false, - "image_url": imageData, }] }) diff --git a/src/app/shared/chat/group-messages/group-messages.page.ts b/src/app/shared/chat/group-messages/group-messages.page.ts index 870e8b7f6..76b20d77c 100644 --- a/src/app/shared/chat/group-messages/group-messages.page.ts +++ b/src/app/shared/chat/group-messages/group-messages.page.ts @@ -681,10 +681,9 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe "image_url": capturedImage }, attachments: [{ - //"title": this.capturedImageTitle , - //"text": "description", + "title": capturedImageTitle , + "text": "description", "title_link_download": false, - //"image_url": this.capturedImage, }] }) @@ -806,10 +805,9 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe "image_url": imageData }, attachments: [{ - //"title": this.capturedImageTitle , - //"text": "description", + "title": file.name , + "text": "description", "title_link_download": false, - //"image_url": this.capturedImage, }] }) From 1ffeb3df5c945d44c5490e67d6acbf41e23fbf28 Mon Sep 17 00:00:00 2001 From: Peter Maquiran Date: Fri, 4 Feb 2022 07:42:43 +0100 Subject: [PATCH 16/27] update --- .../group-messages/group-messages.page.ts | 16 +- src/app/pages/chat/messages/messages.page.ts | 16 +- src/app/services/file-system.service.spec.ts | 16 -- src/app/services/file-system.service.ts | 145 -------------- src/app/services/functions/file.service.ts | 188 ++++++++++-------- .../group-messages/group-messages.page.ts | 16 +- src/app/shared/chat/messages/messages.page.ts | 10 +- 7 files changed, 135 insertions(+), 272 deletions(-) delete mode 100644 src/app/services/file-system.service.spec.ts delete mode 100644 src/app/services/file-system.service.ts diff --git a/src/app/pages/chat/group-messages/group-messages.page.ts b/src/app/pages/chat/group-messages/group-messages.page.ts index 3e8d02d58..ffb265c32 100644 --- a/src/app/pages/chat/group-messages/group-messages.page.ts +++ b/src/app/pages/chat/group-messages/group-messages.page.ts @@ -29,7 +29,7 @@ import { WsChatMethodsService } from 'src/app/services/chat/ws-chat-methods.serv 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'; @@ -98,7 +98,7 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy { private AttachmentsService: AttachmentsService, private storage: Storage, private processesService: ProcessesService, - private FileSystemService: FileSystemService, + private CameraService: CameraService, ) { this.loggedUserChat = authService.ValidatedUserChat['data']; @@ -499,9 +499,9 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy { 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); + await this.fileService.saveImage(image) + const lastphoto: any = await this.fileService.loadFiles(); + const { capturedImage, capturedImageTitle} = await this.fileService.loadFileData(lastphoto); const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(this.roomId).send({ file: { @@ -689,9 +689,9 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy { } 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); + await this.fileService.saveImage(image) + const lastphoto: any = await this.fileService.loadFiles(); + const { capturedImage, capturedImageTitle} = await this.fileService.loadFileData(lastphoto); const base64 = await fetch(capturedImage); const blob = await base64.blob(); diff --git a/src/app/pages/chat/messages/messages.page.ts b/src/app/pages/chat/messages/messages.page.ts index b47923aa5..8b03a1439 100644 --- a/src/app/pages/chat/messages/messages.page.ts +++ b/src/app/pages/chat/messages/messages.page.ts @@ -32,7 +32,7 @@ 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'; @@ -108,7 +108,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { private sqlservice: SqliteService, public wsChatMethodsService: WsChatMethodsService, private AttachmentsService: AttachmentsService, - private FileSystemService: FileSystemService, + private CameraService: CameraService, private processesService: ProcessesService, private storage: Storage, @@ -522,9 +522,9 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { 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); + await this.fileService.saveImage(image) + const lastphoto: any = await this.fileService.loadFiles(); + const { capturedImage, capturedImageTitle} = await this.fileService.loadFileData(lastphoto); const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(this.roomId).send({ file: { @@ -712,9 +712,9 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { } 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); + await this.fileService.saveImage(image) + const lastphoto: any = await this.fileService.loadFiles(); + const { capturedImage, capturedImageTitle} = await this.fileService.loadFileData(lastphoto); const base64 = await fetch(capturedImage); const blob = await base64.blob(); diff --git a/src/app/services/file-system.service.spec.ts b/src/app/services/file-system.service.spec.ts deleted file mode 100644 index f6d5285f4..000000000 --- a/src/app/services/file-system.service.spec.ts +++ /dev/null @@ -1,16 +0,0 @@ -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(); - }); -}); diff --git a/src/app/services/file-system.service.ts b/src/app/services/file-system.service.ts deleted file mode 100644 index 668cede8a..000000000 --- a/src/app/services/file-system.service.ts +++ /dev/null @@ -1,145 +0,0 @@ -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} - - } - - -} diff --git a/src/app/services/functions/file.service.ts b/src/app/services/functions/file.service.ts index b279a0f7d..56c42904d 100644 --- a/src/app/services/functions/file.service.ts +++ b/src/app/services/functions/file.service.ts @@ -3,13 +3,14 @@ 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 } from '@ionic/angular'; +import { LoadingController, ModalController, Platform } from '@ionic/angular'; import { SearchPage } from 'src/app/pages/search/search.page'; import { ProcessesService } from '../processes.service'; import { ToastService } from '../toast.service'; -import { Camera, CameraResultType, CameraSource} from '@capacitor/camera'; +import { Camera, CameraResultType, CameraSource, Photo} from '@capacitor/camera'; import { FileType } from 'src/app/models/fileType'; -import { FileSystemService } from 'src/app/services/file-system.service'; + +import { Filesystem, Directory } from '@capacitor/filesystem'; const IMAGE_DIR = 'stored-images'; @@ -44,22 +45,12 @@ export class FileService { private modalController: ModalController, private processesService: ProcessesService, private toastService: ToastService, - private FileSystemService: FileSystemService + + private loadingCtrl: LoadingController, + private platform: Platform, ) {} - _arrayBufferToBase64( buffer ) { - var binary = ''; - var bytes = new Uint8Array( buffer ); - var len = bytes.byteLength; - for (var i = 0; i < len; i++) { - binary += String.fromCharCode( bytes[ i ] ); - } - return window.btoa( binary ); -} - - - convertBlobToBase64 = (blob: Blob) => new Promise((resolve, reject) => { const reader = new FileReader; reader.onerror = reject; @@ -69,73 +60,7 @@ export class FileService { reader.readAsDataURL(blob); }); - async loadPicture() { - const input = this.fileLoaderService.createInput({ - accept: ['image/apng', 'image/jpeg', 'image/png', '.pdf'] - }) - input.onchange = async () => { - const file = this.fileLoaderService.getFirstFile(input) - - console.log(file); - - const imageData = await this.fileToBase64Service.convert(file) - this.capturedImage = imageData; - this.capturedImageTitle = file.name; - - let data = { - image:this.capturedImage, - name: this.capturedImageTitle - } - - return data; - }; - } - - - async addPictureToChatMobile(roomId) { - - const capturedImage = await Camera.getPhoto({ - quality: 50, - // allowEditing: true, - resultType: CameraResultType.Uri, - source: CameraSource.Camera - - }); - - if (capturedImage) { - await this.FileSystemService.saveImage(capturedImage,roomId) - } - - } - - - addDocumentToChat(roomId:string) { - const input = this.fileLoaderService.createInput({ - accept: ['.doc', '.docx', '.pdf'] - }) - - input.onchange = async () => { - const loader = this.toastService.loading(); - const file = this.fileLoaderService.getFirstFile(input) - - console.log(file); - - const formData = new FormData(); - formData.append('file', file, file.name); - - this.chatService.uploadFile(formData, roomId).subscribe(res=> { - console.log(res); - loader.remove(); - },(error) => { - loader.remove(); - }); - //console.log(this.capturedImage) - }; - } - - - getFileFromDevice(types: typeof FileType[]) { return new Promise((resolve, reject)=>{ const input = this.fileLoaderService.createInput({ @@ -155,4 +80,103 @@ export class FileService { const browser = this.iab.create(url,"_parent"); browser.show(); } + + + async saveImage(photo: Photo) { + 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() { + + 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; + } + } + + + async readFile(filePath) { + return await Filesystem.readFile({ + path: filePath, + directory: Directory.Data, + }); + } + + //new method 4 + async loadFileData(fileName: string) { + console.log('ALL PHOTOT FILE', fileName) + // for (let f of fileNames) { + const filePath = `${IMAGE_DIR}/${fileName}`; + + const readFile = await this.readFile(filePath) + + const image ={ + name: fileName, + path: filePath, + data: `data:image/jpeg;base64,${readFile.data}`, + }; + + console.log('ALL IMAGE', image) + + const capturedImage = image.data + + const capturedImageTitle = new Date().getTime() + '.jpeg'; + + + return { capturedImage, capturedImageTitle} + + } + } diff --git a/src/app/shared/chat/group-messages/group-messages.page.ts b/src/app/shared/chat/group-messages/group-messages.page.ts index 76b20d77c..d25537edb 100644 --- a/src/app/shared/chat/group-messages/group-messages.page.ts +++ b/src/app/shared/chat/group-messages/group-messages.page.ts @@ -27,7 +27,7 @@ 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'; @@ -103,7 +103,7 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe private changeDetectorRef: ChangeDetectorRef, private storage: Storage, private AttachmentsService: AttachmentsService, - private FileSystemService: FileSystemService, + private CameraService: CameraService, private toastService: ToastService, @@ -670,9 +670,9 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe 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); + await this.fileService.saveImage(image) + const lastphoto: any = await this.fileService.loadFiles(); + const { capturedImage, capturedImageTitle} = await this.fileService.loadFileData(lastphoto); const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(this.roomId).send({ file: { @@ -896,9 +896,9 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe 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); + await this.fileService.saveImage(image) + const lastphoto: any = await this.fileService.loadFiles(); + const { capturedImage, capturedImageTitle} = await this.fileService.loadFileData(lastphoto); const base64 = await fetch(capturedImage); const blob = await base64.blob(); diff --git a/src/app/shared/chat/messages/messages.page.ts b/src/app/shared/chat/messages/messages.page.ts index cb4ec06fb..21675134e 100644 --- a/src/app/shared/chat/messages/messages.page.ts +++ b/src/app/shared/chat/messages/messages.page.ts @@ -27,7 +27,7 @@ import { WsChatMethodsService } from 'src/app/services/chat/ws-chat-methods.serv import { WsChatService } from 'src/app/services/chat/ws-chat.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 { FileType } from 'src/app/models/fileType'; import { SearchPage } from 'src/app/pages/search/search.page'; @@ -100,7 +100,7 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy public wsChatMethodsService: WsChatMethodsService, public WsChatService: WsChatService, private AttachmentsService: AttachmentsService, - private FileSystemService: FileSystemService, + private CameraService: CameraService, private processesService: ProcessesService, private fileToBase64Service: FileToBase64Service, @@ -446,9 +446,9 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy 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); + await this.fileService.saveImage(image) + const lastphoto: any = await this.fileService.loadFiles(); + const { capturedImage, capturedImageTitle} = await this.fileService.loadFileData(lastphoto); const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(this.roomId).send({ file: { From 80aaf352b61d724e12074bf3ab8e50fc658a35da Mon Sep 17 00:00:00 2001 From: Peter Maquiran Date: Fri, 4 Feb 2022 08:00:10 +0100 Subject: [PATCH 17/27] improve --- .../group-messages/group-messages.page.ts | 119 ++----------- src/app/pages/chat/messages/messages.page.ts | 49 +----- .../group-messages/group-messages.page.ts | 162 +----------------- src/app/shared/chat/messages/messages.page.ts | 4 +- 4 files changed, 24 insertions(+), 310 deletions(-) diff --git a/src/app/pages/chat/group-messages/group-messages.page.ts b/src/app/pages/chat/group-messages/group-messages.page.ts index ffb265c32..b6023c121 100644 --- a/src/app/pages/chat/group-messages/group-messages.page.ts +++ b/src/app/pages/chat/group-messages/group-messages.page.ts @@ -249,7 +249,6 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy { this.roomCountDownDate = this.timeService.countDownDateTimer(this.room.customFields.countDownDate, this.room._id); } this.getGroupContacts(this.room); - this.loadGroupMessages(this.room); this.showLoader = false; }); } @@ -298,27 +297,6 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy { } } - loadGroupMessages(room:any){ - this.showLoader = true; - //If group is private call getGroupMembers - if(this.room.t === 'p'){ - this.chatService.getPrivateGroupMessages(this.roomId).subscribe(res=>{ - console.log(res); - let msgOnly = res['messages'].filter(data => data.t != 'au'); - //this.messages = msgOnly.reverse(); - this.transformDataMSG(msgOnly.reverse()); - this.getRoomMessageDB(this.roomId); - this.showLoader = false; - }); - } - //Otherwise call getChannelMembers for públic groups - /* else{ - this.chatService.getPublicGroupMessages(this.roomId).subscribe(res=>{ - console.log(res); - this.messages = res['messages'].reverse(); - }); - } */ - } showDateDuration(start:any){ return this.timeService.showDateDuration(start); @@ -366,42 +344,6 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy { }); } - loadPicture() { - const input = this.fileLoaderService.createInput({ - accept: ['image/apng', 'image/jpeg', 'image/png'] - }) - - input.onchange = async () => { - const file = this.fileLoaderService.getFirstFile(input) - - console.log(file); - - const imageData = await this.fileToBase64Service.convert(file) - this.capturedImage = imageData; - this.capturedImageTitle = file.name; - - let body = { - "message": - { - "rid": this.roomId, - "msg": "", - "attachments": [{ - //"title": this.capturedImageTitle , - //"text": "description", - "title_link_download": false, - "image_url": this.capturedImage, - }] - } - } - - this.chatService.sendMessage(body).subscribe(res=> { - console.log(res); - },(error) => { - - }); - //console.log(this.capturedImage) - }; - } viewDocument(file:any, url?:string){ @@ -608,7 +550,9 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy { "title_link_download": true, //"thumb_url": "assets/images/webtrix-logo.png", "message_link": url_no_options, - "type": "webtrix" + "type": "webtrix", + "text": res.data.selected.DocTypeDesc, + "thumb_url": "https://static.ichimura.ed.jp/uploads/2017/10/pdf-icon.png", }] }) @@ -619,7 +563,6 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy { } - async addFileToChat(types: typeof FileType[] ) { const file = await this.fileService.getFileFromDevice(types); const imageData = await this.fileToBase64Service.convert(file) @@ -684,65 +627,23 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy { await popover.present(); await popover.onDidDismiss().then( async(res)=>{ console.log(res['data']); - if(res['data'] == 'meeting'){ + if (res['data'] == 'meeting') { this.bookMeeting(); } - else if(res['data'] == 'take-picture') { - const image = await this.CameraService.takePicture(); - await this.fileService.saveImage(image) - const lastphoto: any = await this.fileService.loadFiles(); - const { capturedImage, capturedImageTitle} = await this.fileService.loadFileData(lastphoto); - - 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).send({ - 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'] == 'take-picture') { + this.takePicture() } - else if(res['data'] == 'add-picture'){ - + else if (res['data'] == 'add-picture') { this.addImage() } - else if(res['data'] == 'add-document'){ + else if (res['data'] == 'add-document') { this.addFile() } - else if(res['data'] == 'documentoGestaoDocumental'){ + else if (res['data'] == 'documentoGestaoDocumental') { + this.addFileWebtrix() } - this.loadGroupMessages(this.roomId); }); } diff --git a/src/app/pages/chat/messages/messages.page.ts b/src/app/pages/chat/messages/messages.page.ts index 8b03a1439..1bbcebd38 100644 --- a/src/app/pages/chat/messages/messages.page.ts +++ b/src/app/pages/chat/messages/messages.page.ts @@ -526,7 +526,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { const lastphoto: any = await this.fileService.loadFiles(); const { capturedImage, capturedImageTitle} = await this.fileService.loadFileData(lastphoto); - const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(this.roomId).send({ + const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(roomId).send({ file: { "type": "application/img", "guid": '', @@ -631,7 +631,9 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { "title_link_download": true, //"thumb_url": "assets/images/webtrix-logo.png", "message_link": url_no_options, - "type": "webtrix" + "type": "webtrix", + "text": res.data.selected.DocTypeDesc, + "thumb_url": "https://static.ichimura.ed.jp/uploads/2017/10/pdf-icon.png", }] }) @@ -711,48 +713,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { this.bookMeeting(); } else if (res['data'] == 'take-picture') { - const image = await this.CameraService.takePicture(); - await this.fileService.saveImage(image) - const lastphoto: any = await this.fileService.loadFiles(); - const { capturedImage, capturedImageTitle} = await this.fileService.loadFileData(lastphoto); - - 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).send({ - file: { - "type": "application/img", - "guid": guid.path, - "image_url": fileImage - }, - attachments: [{ - "title": capturedImageTitle , - "text": "description", - "title_link_download": false, - "image_url": capturedImage, - }] - }) - - }); - } - - }); + this.takePicture() } else if (res['data'] == 'add-picture') { this.addImage() diff --git a/src/app/shared/chat/group-messages/group-messages.page.ts b/src/app/shared/chat/group-messages/group-messages.page.ts index d25537edb..fbff28265 100644 --- a/src/app/shared/chat/group-messages/group-messages.page.ts +++ b/src/app/shared/chat/group-messages/group-messages.page.ts @@ -398,10 +398,6 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe else { this.roomName = res.data.name.split('-').join(' '); console.log(this.roomName); - - //this.getRoomInfo(); - this.loadGroupMessages(this.roomId); - //this.modalController.dismiss(); }; }); @@ -478,85 +474,6 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe }); } - loadPicture() { - const input = this.fileLoaderService.createInput({ - accept: ['image/apng', 'image/jpeg', 'image/png'] - }) - - input.onchange = async () => { - const file = this.fileLoaderService.getFirstFile(input) - - console.log(file); - - const imageData = await this.fileToBase64Service.convert(file) - this.capturedImage = imageData; - this.capturedImageTitle = file.name; - - let body = { - "message": - { - "rid": this.roomId, - "msg": "", - "attachments": [{ - //"title": this.capturedImageTitle , - //"text": "description", - "title_link_download": false, - "image_url": this.capturedImage, - }] - } - } - - this.chatService.sendMessage(body).subscribe(res => { - console.log(res); - }, (error) => { - - }); - //console.log(this.capturedImage) - }; - } - - loadDocument() { - const input = this.fileLoaderService.createInput({ - accept: ['.doc', '.docx', '.pdf'] - }) - - input.onchange = async () => { - const file = this.fileLoaderService.getFirstFile(input) - - console.log(file); - - const imageData = await this.fileToBase64Service.convert(file) - this.capturedImage = imageData; - this.capturedImageTitle = file.name; - - let body = { - "message": - { - "rid": this.roomId, - "msg": "", - "attachments": [{ - "title": this.capturedImageTitle, - "text": "", - "title_link": this.capturedImage, - "title_link_download": true, - "thumb_url": "https://static.ichimura.ed.jp/uploads/2017/10/pdf-icon.png", - "message_link": this.capturedImage, - }], - "file": { - "name": this.capturedImageTitle, - "type": "application/pdf", - } - } - } - - this.chatService.sendMessage(body).subscribe(res => { - //console.log(res); - }, (error) => { - - }); - //console.log(this.capturedImage) - }; - } async addDocGestaoDocumental() { const modal = await this.modalController.create({ @@ -573,36 +490,8 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe if (res) { const data = res.data; 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); - //console.log('Oie'); - - let body = { - "message": - { - "rid": this.roomId, - "msg": "", - "attachments": [{ - "title": res.data.selected.Assunto, - "text": res.data.selected.DocTypeDesc, - "title_link": url_no_options, - "title_link_download": true, - "thumb_url": "https://static.ichimura.ed.jp/uploads/2017/10/pdf-icon.png", - "message_link": url_no_options, - }] - } - } - this.chatService.sendMessage(body).subscribe(res => { - console.log(res); - }, (error) => { - - }); - + + this.addFileWebtrix() } }); } @@ -779,7 +668,9 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe "title_link_download": true, //"thumb_url": "assets/images/webtrix-logo.png", "message_link": url_no_options, - "type": "webtrix" + "type": "webtrix", + "text": res.data.selected.DocTypeDesc, + "thumb_url": "https://static.ichimura.ed.jp/uploads/2017/10/pdf-icon.png", }] }) @@ -895,48 +786,7 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe } else if (res['data'] == 'take-picture') { - const image = await this.CameraService.takePicture(); - await this.fileService.saveImage(image) - const lastphoto: any = await this.fileService.loadFiles(); - const { capturedImage, capturedImageTitle} = await this.fileService.loadFileData(lastphoto); - - 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).send({ - file: { - "type": "application/img", - "guid": guid.path, - "image_url": fileImage - }, - attachments: [{ - //"title": this.capturedImageTitle , - //"text": "description", - "title_link_download": false, - //"image_url": this.capturedImage, - }] - }) - - }); - } - - }); + this.takePicture() } else if (res['data'] == 'add-picture') { diff --git a/src/app/shared/chat/messages/messages.page.ts b/src/app/shared/chat/messages/messages.page.ts index 21675134e..8faa411ec 100644 --- a/src/app/shared/chat/messages/messages.page.ts +++ b/src/app/shared/chat/messages/messages.page.ts @@ -555,7 +555,9 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy "title_link_download": true, //"thumb_url": "assets/images/webtrix-logo.png", "message_link": url_no_options, - "type": "webtrix" + "type": "webtrix", + "text": res.data.selected.DocTypeDesc, + "thumb_url": "https://static.ichimura.ed.jp/uploads/2017/10/pdf-icon.png", }] }) From 91ed23cb3a64cb5051a353affa4ac8ef48b5bc26 Mon Sep 17 00:00:00 2001 From: Peter Maquiran Date: Fri, 4 Feb 2022 08:11:49 +0100 Subject: [PATCH 18/27] improve --- src/app/pages/chat/chat.page.ts | 5 -- src/app/pages/chat/messages/messages.page.ts | 49 ++------------ .../group-messages/group-messages.page.ts | 65 ++----------------- src/app/shared/chat/messages/messages.page.ts | 49 ++------------ 4 files changed, 18 insertions(+), 150 deletions(-) diff --git a/src/app/pages/chat/chat.page.ts b/src/app/pages/chat/chat.page.ts index b5963e605..916f0f0cb 100644 --- a/src/app/pages/chat/chat.page.ts +++ b/src/app/pages/chat/chat.page.ts @@ -159,11 +159,6 @@ export class ChatPage implements OnInit { let t = this.showDateDuration(new Date()); - this.setStatus('away'); - /* if(this.dataService.get("newGroup")){ - this.openNewGroupPage(); - } */ - this.router.events.forEach((event) => { if (event instanceof NavigationStart && event.url.startsWith('/home/chat')) { if (this.dataService.get("newGroup")) { diff --git a/src/app/pages/chat/messages/messages.page.ts b/src/app/pages/chat/messages/messages.page.ts index 1bbcebd38..b57bfadb8 100644 --- a/src/app/pages/chat/messages/messages.page.ts +++ b/src/app/pages/chat/messages/messages.page.ts @@ -596,11 +596,12 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { await modal.present(); modal.onDidDismiss().then(async res=>{ const data = res.data; + const roomId = this.roomId if(data.selected) { const loader = this.toastService.loading(); - const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(this.roomId).send({ + const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(roomId).send({ file:{ "name": res.data.selected.Assunto, "type": "application/webtrix", @@ -646,13 +647,15 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { async addFileToChat(types: typeof FileType[] ) { + const roomId = this.roomId + const file = await this.fileService.getFileFromDevice(types); const imageData = await this.fileToBase64Service.convert(file) const formData = new FormData(); formData.append("blobFile", file); - const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(this.roomId).send({ + const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(roomId).send({ file: { "type": "application/img", "guid": '', @@ -807,48 +810,6 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { } - sliderOpts = { - zoom: false, - slidesPerView: 1.5, - spaceBetween: 20, - centeredSlides: true - }; - zoomActive = false; - zoomScale = 1; - - sliderZoomOpts = { - allowSlidePrev: false, - allowSlideNext: false, - zoom: { - maxRatio: 5 - }, - on: { - zoomChange: (scale, imageEl, slideEl) => { - this.zoomActive = true; - this.zoomScale = scale / 5; - this.changeDetectorRef.detectChanges(); - } - } - } - - async touchEnd(zoomslides: IonSlides, card) { - // Zoom back to normal - const slider = await zoomslides.getSwiper(); - const zoom = slider.zoom; - zoom.out(); - - // Card back to normal - card.el.style['z-index'] = 9; - - this.zoomActive = false; - this.changeDetectorRef.detectChanges(); - } - - touchStart(card) { - // Make card appear above backdrop - card.el.style['z-index'] = 11; - } - downloadFileMsg(msg: MessageService) { console.log('FILE TYPE', msg.file.type) this.downloadFile = ""; diff --git a/src/app/shared/chat/group-messages/group-messages.page.ts b/src/app/shared/chat/group-messages/group-messages.page.ts index fbff28265..0a02d3063 100644 --- a/src/app/shared/chat/group-messages/group-messages.page.ts +++ b/src/app/shared/chat/group-messages/group-messages.page.ts @@ -139,7 +139,6 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe setTimeout(() => { this.getRoomInfo(); }, 1000); - this.setStatus('online'); this.getChatMembers(); //this.getMessageDB(); @@ -226,7 +225,6 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe } ngOnDestroy() { - this.setStatus('away'); window.removeEventListener('scroll', this.scrollChangeCallback, true); } @@ -307,15 +305,6 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe } } - loadGroupMessages(roomId) { - this.showLoader = true; - this.chatService.getPrivateGroupMessages(this.roomId).subscribe(res => { - console.log(res); - let msgOnly = res['messages'].filter(data => data.t != 'au'); - this.showLoader = false; - }); - } - sendMessage() { this.wsChatMethodsService.getGroupRoom(this.roomId).send({}) } @@ -429,7 +418,6 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe popover.onDidDismiss().then(res => { console.log(res); if (res.data) { - this.loadGroupMessages(this.roomId); //this.getRoomInfo(); //this.modalController.dismiss(); }; @@ -470,7 +458,6 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe modal.onDidDismiss().then(() => { //this.getRoomInfo(); - this.loadGroupMessages(this.roomId) }); } @@ -563,7 +550,7 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe const lastphoto: any = await this.fileService.loadFiles(); const { capturedImage, capturedImageTitle} = await this.fileService.loadFileData(lastphoto); - const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(this.roomId).send({ + const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(roomId).send({ file: { "type": "application/img", "guid": '', @@ -621,6 +608,8 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe } async addFileWebtrix() { + const roomId = this.roomId + const modal = await this.modalController.create({ component: SearchPage, cssClass: 'group-messages modal-desktop search-modal search-modal-to-desktop', @@ -637,7 +626,7 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe if(data.selected) { const loader = this.toastService.loading(); - const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(this.roomId).send({ + const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(roomId).send({ file:{ "name": res.data.selected.Assunto, "type": "application/webtrix", @@ -683,13 +672,15 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe async addFileToChat(types: typeof FileType[] ) { + const roomId = this.roomId + const file = await this.fileService.getFileFromDevice(types); const imageData = await this.fileToBase64Service.convert(file) const formData = new FormData(); formData.append("blobFile", file); - const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(this.roomId).send({ + const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(roomId).send({ file: { "type": "application/img", "guid": '', @@ -810,48 +801,6 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe } - sliderOpts = { - zoom: false, - slidesPerView: 1.5, - spaceBetween: 20, - centeredSlides: true - }; - zoomActive = false; - zoomScale = 1; - - sliderZoomOpts = { - allowSlidePrev: false, - allowSlideNext: false, - zoom: { - maxRatio: 5 - }, - on: { - zoomChange: (scale, imageEl, slideEl) => { - this.zoomActive = true; - this.zoomScale = scale / 5; - this.changeDetectorRef.detectChanges(); - } - } - } - - async touchEnd(zoomslides: IonSlides, card) { - // Zoom back to normal - const slider = await zoomslides.getSwiper(); - const zoom = slider.zoom; - zoom.out(); - - // Card back to normal - card.el.style['z-index'] = 9; - - this.zoomActive = false; - this.changeDetectorRef.detectChanges(); - } - - touchStart(card) { - // Make card appear above backdrop - card.el.style['z-index'] = 11; - } - downloadFileMsg(msg: MessageService) { console.log('FILE TYPE', msg.file.type) this.downloadFile = ""; diff --git a/src/app/shared/chat/messages/messages.page.ts b/src/app/shared/chat/messages/messages.page.ts index 8faa411ec..97651efad 100644 --- a/src/app/shared/chat/messages/messages.page.ts +++ b/src/app/shared/chat/messages/messages.page.ts @@ -450,7 +450,7 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy const lastphoto: any = await this.fileService.loadFiles(); const { capturedImage, capturedImageTitle} = await this.fileService.loadFileData(lastphoto); - const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(this.roomId).send({ + const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(roomId).send({ file: { "type": "application/img", "guid": '', @@ -520,11 +520,12 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy await modal.present(); modal.onDidDismiss().then(async res=>{ const data = res.data; + const roomId = this.roomId if(data.selected) { const loader = this.toastService.loading(); - const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(this.roomId).send({ + const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(roomId).send({ file:{ "name": res.data.selected.Assunto, "type": "application/webtrix", @@ -570,13 +571,15 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy async addFileToChat(types: typeof FileType[] ) { + const roomId = this.roomId + const file = await this.fileService.getFileFromDevice(types); const imageData = await this.fileToBase64Service.convert(file) const formData = new FormData(); formData.append("blobFile", file); - const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(this.roomId).send({ + const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(roomId).send({ file: { "type": "application/img", "guid": '', @@ -705,47 +708,7 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy } - sliderOpts = { - zoom: false, - slidesPerView: 1.5, - spaceBetween: 20, - centeredSlides: true - }; - zoomActive = false; - zoomScale = 1; - sliderZoomOpts = { - allowSlidePrev: false, - allowSlideNext: false, - zoom: { - maxRatio: 5 - }, - on: { - zoomChange: (scale, imageEl, slideEl) => { - this.zoomActive = true; - this.zoomScale = scale / 5; - this.changeDetectorRef.detectChanges(); - } - } - } - - async touchEnd(zoomslides: IonSlides, card) { - // Zoom back to normal - const slider = await zoomslides.getSwiper(); - const zoom = slider.zoom; - zoom.out(); - - // Card back to normal - card.el.style['z-index'] = 9; - - this.zoomActive = false; - this.changeDetectorRef.detectChanges(); - } - - touchStart(card) { - // Make card appear above backdrop - card.el.style['z-index'] = 11; - } downloadFileMsg(msg: MessageService) { console.log('FILE TYPE', msg.file.type) From 88a810a7bba863288d5c97f5d3c11c173a73aa31 Mon Sep 17 00:00:00 2001 From: Peter Maquiran Date: Fri, 4 Feb 2022 08:17:39 +0100 Subject: [PATCH 19/27] improve --- src/app/services/functions/file.service.ts | 17 ++--------------- 1 file changed, 2 insertions(+), 15 deletions(-) diff --git a/src/app/services/functions/file.service.ts b/src/app/services/functions/file.service.ts index 56c42904d..01b42f718 100644 --- a/src/app/services/functions/file.service.ts +++ b/src/app/services/functions/file.service.ts @@ -1,19 +1,12 @@ 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 { LoadingController, ModalController, Platform } from '@ionic/angular'; -import { SearchPage } from 'src/app/pages/search/search.page'; -import { ProcessesService } from '../processes.service'; -import { ToastService } from '../toast.service'; -import { Camera, CameraResultType, CameraSource, Photo} from '@capacitor/camera'; +import { LoadingController, Platform } from '@ionic/angular'; +import {Photo} from '@capacitor/camera'; import { FileType } from 'src/app/models/fileType'; - import { Filesystem, Directory } from '@capacitor/filesystem'; const IMAGE_DIR = 'stored-images'; - interface LocalFile { name: string; path: string; @@ -39,13 +32,7 @@ export class FileService { constructor( private fileLoaderService: FileLoaderService, - private fileToBase64Service: FileToBase64Service, private iab: InAppBrowser, - private chatService: ChatService, - private modalController: ModalController, - private processesService: ProcessesService, - private toastService: ToastService, - private loadingCtrl: LoadingController, private platform: Platform, ) {} From 1d0913cd500cd020d7160f29447bf28a81153489 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eudes=20In=C3=A1cio?= Date: Mon, 7 Feb 2022 12:56:35 +0100 Subject: [PATCH 20/27] view publications headch --- .../view-publications.page.html | 2 +- .../view-publications/view-publications.page.ts | 17 +++++++++++++---- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/src/app/pages/publications/view-publications/view-publications.page.html b/src/app/pages/publications/view-publications/view-publications.page.html index 615e85d99..db5984a90 100644 --- a/src/app/pages/publications/view-publications/view-publications.page.html +++ b/src/app/pages/publications/view-publications/view-publications.page.html @@ -44,7 +44,7 @@
- +
diff --git a/src/app/pages/publications/view-publications/view-publications.page.ts b/src/app/pages/publications/view-publications/view-publications.page.ts index 2e5a38217..e07c42b7d 100644 --- a/src/app/pages/publications/view-publications/view-publications.page.ts +++ b/src/app/pages/publications/view-publications/view-publications.page.ts @@ -98,12 +98,12 @@ export class ViewPublicationsPage implements OnInit { } doRefresh = (event) => { - setTimeout(() => { + //setTimeout(() => { //this.testForkJoin() this.getPublicationDetail(); this.getPublicationsIds(); event.target.complete(); - }, 3000); + //}, 3000); } @@ -249,10 +249,10 @@ export class ViewPublicationsPage implements OnInit { ProcessId: publications[0].ProcessId } this.publicationDitails = item; */ - this.item = JSON.parse(publications[0].publicationsDetails); + this.item = this.isJson(publications[0].publicationsDetails); let publicationArray = []; - JSON.parse(publications[0].publications).forEach(element => { + this.isJson(publications[0].publications).forEach(element => { let publicationlis = { DateIndex: element.DateIndex, DatePublication: element.DatePublication, @@ -272,6 +272,15 @@ export class ViewPublicationsPage implements OnInit { }) } + isJson(str) { + try { + JSON.parse(str); + } catch (e) { + return str; + } + return JSON.parse(str); + } + async AddPublication(publicationType: any, folderId: any) { const modal = await this.modalController.create({ component: NewPublicationPage, From a3f1da77b92f31c146a246e265b01915d251c25e Mon Sep 17 00:00:00 2001 From: Peter Maquiran Date: Mon, 7 Feb 2022 13:24:24 +0100 Subject: [PATCH 21/27] rever array --- src/app/services/chat/room.service.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/app/services/chat/room.service.ts b/src/app/services/chat/room.service.ts index 7a32579ed..325172ac2 100644 --- a/src/app/services/chat/room.service.ts +++ b/src/app/services/chat/room.service.ts @@ -342,7 +342,7 @@ export class RoomService { if(messages==null) messages = [] - messages.forEach((ChatMessage, index) => { + messages.reverse().forEach((ChatMessage, index) => { const wewMessage = this.prepareMessage(ChatMessage) if(wewMessage.offline == true) { From 2caaad7f2b4a51796c55df12721bae6e02f1b1b5 Mon Sep 17 00:00:00 2001 From: Peter Maquiran Date: Mon, 7 Feb 2022 15:51:21 +0100 Subject: [PATCH 22/27] chat --- src/app/guards/auth.guard.ts | 2 ++ src/app/models/chatMethod.ts | 1 + src/app/services/chat/message.service.ts | 19 +++++++------------ ...ser.service.spec.ts => nf.service.spec.ts} | 8 ++++---- .../{chat-user.service.ts => nf.service.ts} | 2 +- src/app/services/chat/room.service.ts | 7 +++---- src/app/shared/chat/messages/messages.page.ts | 3 ++- 7 files changed, 20 insertions(+), 22 deletions(-) rename src/app/services/chat/{chat-user.service.spec.ts => nf.service.spec.ts} (53%) rename src/app/services/chat/{chat-user.service.ts => nf.service.ts} (77%) diff --git a/src/app/guards/auth.guard.ts b/src/app/guards/auth.guard.ts index 74a8e799d..cb879693d 100644 --- a/src/app/guards/auth.guard.ts +++ b/src/app/guards/auth.guard.ts @@ -17,10 +17,12 @@ export class AuthGuard implements CanActivate { route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable | Promise | boolean | UrlTree { + // if user not active if(!SessionStore.user.Inactivity) { this.router.navigate(['/']); return false } + // if session doesn't exit else if(!SessionStore.exist) { this.router.navigate(['/']); return false diff --git a/src/app/models/chatMethod.ts b/src/app/models/chatMethod.ts index 1b5c6bd9c..1adabf590 100644 --- a/src/app/models/chatMethod.ts +++ b/src/app/models/chatMethod.ts @@ -80,6 +80,7 @@ export interface Message { editedAt: EditedAt; editedBy: EditedBy; urls: any[]; + temporaryData: object } diff --git a/src/app/services/chat/message.service.ts b/src/app/services/chat/message.service.ts index 6eb0f3015..e803e3beb 100644 --- a/src/app/services/chat/message.service.ts +++ b/src/app/services/chat/message.service.ts @@ -1,6 +1,5 @@ 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' @@ -24,11 +23,12 @@ export class MessageService { attachments offline = true displayType = '' + temporaryData = {} constructor(private storage: Storage) { } - setData({customFields, channels, mentions, msg ,rid ,ts, u, t, _id, _updatedAt, file, attachments}:Message) { + setData({customFields, channels, mentions, msg ,rid ,ts, u, t, _id, _updatedAt, file, attachments, temporaryData}:Message) { this.customFields = customFields this.channels = channels || [] this.mentions = mentions || [] @@ -41,6 +41,7 @@ export class MessageService { this._updatedAt = _updatedAt || new Date().getTime() this.file = file this.attachments = attachments + this,temporaryData = {} if(!this.ts) { this.offline = true @@ -62,15 +63,6 @@ export class MessageService { } - delete() {} - - showDateDuration() {} - - resend() { - - } - - private usernameToDisplayName(username) { const firstName = capitalizeTxt(username.split('.')[0]) @@ -78,7 +70,6 @@ export class MessageService { return firstName + ' ' + lastName } - getFileFromDb() { if (this.file) { if (this.file.guid) { @@ -92,4 +83,8 @@ export class MessageService { } } + sendFile() { + + } + } diff --git a/src/app/services/chat/chat-user.service.spec.ts b/src/app/services/chat/nf.service.spec.ts similarity index 53% rename from src/app/services/chat/chat-user.service.spec.ts rename to src/app/services/chat/nf.service.spec.ts index 089b979cf..b8546cad7 100644 --- a/src/app/services/chat/chat-user.service.spec.ts +++ b/src/app/services/chat/nf.service.spec.ts @@ -1,13 +1,13 @@ import { TestBed } from '@angular/core/testing'; -import { ChatUserService } from './chat-user.service'; +import { NfService } from './nf.service'; -describe('ChatUserService', () => { - let service: ChatUserService; +describe('NfService', () => { + let service: NfService; beforeEach(() => { TestBed.configureTestingModule({}); - service = TestBed.inject(ChatUserService); + service = TestBed.inject(NfService); }); it('should be created', () => { diff --git a/src/app/services/chat/chat-user.service.ts b/src/app/services/chat/nf.service.ts similarity index 77% rename from src/app/services/chat/chat-user.service.ts rename to src/app/services/chat/nf.service.ts index 7a8fd0a8d..ea45b17e5 100644 --- a/src/app/services/chat/chat-user.service.ts +++ b/src/app/services/chat/nf.service.ts @@ -3,7 +3,7 @@ import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) -export class ChatUserService { +export class NfService { constructor() { } } diff --git a/src/app/services/chat/room.service.ts b/src/app/services/chat/room.service.ts index 325172ac2..332263585 100644 --- a/src/app/services/chat/room.service.ts +++ b/src/app/services/chat/room.service.ts @@ -1,7 +1,6 @@ import { Injectable } from '@angular/core'; import { WsChatService } from 'src/app/services/chat/ws-chat.service'; import { MessageService } from 'src/app/services/chat/message.service'; -import { ChatUserService } from 'src/app/services/chat/chat-user.service'; import { showDateDuration } from 'src/plugin/showDateDuration'; import { ToastsService } from '../toast.service'; import { chatHistory, ChatMessage } from 'src/app/models/chatMethod'; @@ -24,8 +23,7 @@ export class RoomService { messages: MessageService[] = [] storageMessage: any[] = []; lastMessage: MessageService; - - chatUser: ChatUserService[] = [] + customFields: any; id = '' t = '' @@ -205,7 +203,7 @@ export class RoomService { /** * @description sen text message */ - send({file = null, attachments = null}) { + send({file = null, attachments = null, temporary= {}}) { let offlineChatMessage = { @@ -213,6 +211,7 @@ export class RoomService { msg: this.message, attachments, file, + temporary } this.addMessageDB(offlineChatMessage) diff --git a/src/app/shared/chat/messages/messages.page.ts b/src/app/shared/chat/messages/messages.page.ts index 55316e203..7d388fdaf 100644 --- a/src/app/shared/chat/messages/messages.page.ts +++ b/src/app/shared/chat/messages/messages.page.ts @@ -542,7 +542,8 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy //"thumb_url": "assets/images/webtrix-logo.png", // "message_link": url_no_options, "type": "webtrix" - }] + }], + temporary: res }) let url = await this.processesService.GetDocumentUrl(res.data.selected.Id, res.data.selected.ApplicationType).toPromise(); From e03fb2b41317aafa4050faac5416215090ea7b1c Mon Sep 17 00:00:00 2001 From: Peter Maquiran Date: Mon, 7 Feb 2022 17:55:00 +0100 Subject: [PATCH 23/27] improve --- nice.html | 17 +- package-lock.json | 172 +++++++++++++++++- package.json | 1 + .../group-messages/group-messages.page.ts | 88 ++------- src/app/pages/chat/messages/messages.page.ts | 98 ++-------- src/app/services/attachments.service.ts | 8 +- src/app/services/auth.service.ts | 72 ++++++-- src/app/services/chat/message.service.ts | 26 ++- src/app/services/chat/nf.service.ts | 5 + src/app/services/chat/room.service.ts | 30 +-- .../services/chat/ws-chat-methods.service.ts | 7 +- src/app/services/processes.service.ts | 8 +- .../group-messages/group-messages.page.ts | 88 +-------- src/app/shared/chat/messages/messages.page.ts | 92 +--------- 14 files changed, 333 insertions(+), 379 deletions(-) diff --git a/nice.html b/nice.html index 9e964f49f..dbf55e663 100644 --- a/nice.html +++ b/nice.html @@ -17,13 +17,20 @@ var data= [ - {a:{aa:10},b:{bb:2}}, - {a:{aa:10},b:{bb:2}}, - {a:{aa:2},b:{bb:2}}, - {a:{aa:3},b:{bb:3}} + { a:{aa:10}, b:{bb:2} }, + { a:{aa:10}, b:{bb:2} }, + { a:{aa:2} , b:{bb:2} }, + { a:{aa:3} , b:{bb:3} } ] - var res = alasql('SELECT a, b FROM ? WHERE b->bb = 2',[data]); + + function db(table, sql) { + const data = indexedDB.gettable(table) + return alasql(sql, [data]); + } + + + var res = alasql('SELECT a, b FROM ? WHERE b->bb = 2',[ data ]); console.log(res) diff --git a/package-lock.json b/package-lock.json index f6d0aa1b8..a299ff62c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -5312,6 +5312,15 @@ "regex-parser": "^2.2.11" } }, + "adler-32": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/adler-32/-/adler-32-1.2.0.tgz", + "integrity": "sha1-aj5r8KY5ALoVZSgIyxXGgT0aXyU=", + "requires": { + "exit-on-epipe": "~1.0.1", + "printj": "~1.1.0" + } + }, "adm-zip": { "version": "0.4.16", "resolved": "https://registry.npmjs.org/adm-zip/-/adm-zip-0.4.16.tgz", @@ -5388,6 +5397,35 @@ "integrity": "sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ==", "dev": true }, + "alasql": { + "version": "1.7.3", + "resolved": "https://registry.npmjs.org/alasql/-/alasql-1.7.3.tgz", + "integrity": "sha512-YaMgHfoR4f7n05NXFVgD+WgmlNKlP4BGZpXSkJCYtniioK7DMJUoN6ZZmUpM0LAavPLXxHM+V+4gM+M/82sIoQ==", + "requires": { + "dom-storage": "^2.1.0", + "es6-promise": "^4.2.6", + "lodash": "4.17.21", + "request": "2.88.2", + "xlsx": "0.17.0", + "yargs": "16.2.0" + }, + "dependencies": { + "yargs": { + "version": "16.2.0", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-16.2.0.tgz", + "integrity": "sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw==", + "requires": { + "cliui": "^7.0.2", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.0", + "y18n": "^5.0.5", + "yargs-parser": "^20.2.2" + } + } + } + }, "alphanum-sort": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/alphanum-sort/-/alphanum-sort-1.0.2.tgz", @@ -6849,6 +6887,38 @@ "resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz", "integrity": "sha1-G2gcIf+EAzyCZUMJBolCDRhxUdw=" }, + "cfb": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/cfb/-/cfb-1.2.1.tgz", + "integrity": "sha512-wT2ScPAFGSVy7CY+aauMezZBnNrfnaLSrxHUHdea+Td/86vrk6ZquggV+ssBR88zNs0OnBkL2+lf9q0K+zVGzQ==", + "requires": { + "adler-32": "~1.3.0", + "crc-32": "~1.2.0", + "printj": "~1.3.0" + }, + "dependencies": { + "adler-32": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/adler-32/-/adler-32-1.3.0.tgz", + "integrity": "sha512-f5nltvjl+PRUh6YNfUstRaXwJxtfnKEWhAWWlmKvh+Y3J2+98a0KKVYDEhz6NdKGqswLhjNGznxfSsZGOvOd9g==", + "requires": { + "printj": "~1.2.2" + }, + "dependencies": { + "printj": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/printj/-/printj-1.2.3.tgz", + "integrity": "sha512-sanczS6xOJOg7IKDvi4sGOUOe7c1tsEzjwlLFH/zgwx/uyImVM9/rgBkc8AfiQa/Vg54nRd8mkm9yI7WV/O+WA==" + } + } + }, + "printj": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/printj/-/printj-1.3.1.tgz", + "integrity": "sha512-GA3TdL8szPK4AQ2YnOe/b+Y1jUFwmmGMMK/qbY7VcE3Z7FU8JstbKiKRzO6CIiAKPhTO8m01NoQ0V5f3jc4OGg==" + } + } + }, "chalk": { "version": "4.1.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", @@ -7158,6 +7228,22 @@ } } }, + "codepage": { + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/codepage/-/codepage-1.14.0.tgz", + "integrity": "sha1-jL4lSBMjVZ19MHVxsP/5HnodL5k=", + "requires": { + "commander": "~2.14.1", + "exit-on-epipe": "~1.0.1" + }, + "dependencies": { + "commander": { + "version": "2.14.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.14.1.tgz", + "integrity": "sha512-+YR16o3rK53SmWHU3rEM3tPAh2rwb1yPcQX5irVn7mb0gXbwuCCrnkbV5+PBfETdfg1vui07nM6PCG1zndcjQw==" + } + } + }, "collect-v8-coverage": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/collect-v8-coverage/-/collect-v8-coverage-1.0.1.tgz", @@ -8185,6 +8271,22 @@ "yaml": "^1.10.0" } }, + "crc-32": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/crc-32/-/crc-32-1.2.1.tgz", + "integrity": "sha512-Dn/xm/1vFFgs3nfrpEVScHoIslO9NZRITWGz/1E/St6u4xw99vfZzVkW0OSnzx2h9egej9xwMCEut6sqwokM/w==", + "requires": { + "exit-on-epipe": "~1.0.1", + "printj": "~1.3.1" + }, + "dependencies": { + "printj": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/printj/-/printj-1.3.1.tgz", + "integrity": "sha512-GA3TdL8szPK4AQ2YnOe/b+Y1jUFwmmGMMK/qbY7VcE3Z7FU8JstbKiKRzO6CIiAKPhTO8m01NoQ0V5f3jc4OGg==" + } + } + }, "critters": { "version": "0.0.10", "resolved": "https://registry.npmjs.org/critters/-/critters-0.0.10.tgz", @@ -9182,6 +9284,11 @@ "entities": "^2.0.0" } }, + "dom-storage": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/dom-storage/-/dom-storage-2.1.0.tgz", + "integrity": "sha512-g6RpyWXzl0RR6OTElHKBl7nwnK87GUyZMYC7JWsB/IA73vpqK2K6LT39x4VepLxlSsWBFrPVLnsSR5Jyty0+2Q==" + }, "dom-walk": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/dom-walk/-/dom-walk-0.1.2.tgz", @@ -9580,8 +9687,7 @@ "es6-promise": { "version": "4.2.8", "resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-4.2.8.tgz", - "integrity": "sha512-HJDGx5daxeIvxdBxvG2cb9g4tEvwIk3i8+nhX0yGrYmZUzbkdg8QbDevheDB8gd0//uPj4c1EQua8Q+MViT0/w==", - "dev": true + "integrity": "sha512-HJDGx5daxeIvxdBxvG2cb9g4tEvwIk3i8+nhX0yGrYmZUzbkdg8QbDevheDB8gd0//uPj4c1EQua8Q+MViT0/w==" }, "es6-promise-plugin": { "version": "4.2.2", @@ -9764,6 +9870,11 @@ "resolved": "https://registry.npmjs.org/exit/-/exit-0.1.2.tgz", "integrity": "sha1-BjJjj42HfMghB9MKD/8aF8uhzQw=" }, + "exit-on-epipe": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/exit-on-epipe/-/exit-on-epipe-1.0.1.tgz", + "integrity": "sha512-h2z5mrROTxce56S+pnvAV890uu7ls7f1kEvVGJbw1OlFH3/mlJ5bkXu0KRyW94v37zzHPiUd55iLn3DA7TjWpw==" + }, "expand-brackets": { "version": "2.1.4", "resolved": "https://registry.npmjs.org/expand-brackets/-/expand-brackets-2.1.4.tgz", @@ -10216,6 +10327,11 @@ "resolved": "https://registry.npmjs.org/fecha/-/fecha-4.2.1.tgz", "integrity": "sha512-MMMQ0ludy/nBs1/o0zVOiKTpG7qMbonKUzjJgQFEuvq6INZ1OraKPRAWkBq5vlKLOUMpmNYG1JoN3oDPUQ9m3Q==" }, + "fflate": { + "version": "0.3.11", + "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.3.11.tgz", + "integrity": "sha512-Rr5QlUeGN1mbOHlaqcSYMKVpPbgLy0AWT/W0EHxA6NGI12yO1jpoui2zBBvU2G824ltM6Ut8BFgfHSBGfkmS0A==" + }, "figures": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/figures/-/figures-2.0.0.tgz", @@ -10416,6 +10532,11 @@ "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==" }, + "frac": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/frac/-/frac-1.1.2.tgz", + "integrity": "sha512-w/XBfkibaTl3YDqASwfDUqkna4Z2p9cFSr1aHDt0WoMTECnRfBOv2WArlZILlqgWlmdIlALXGpM2AOhEk5W3IA==" + }, "fragment-cache": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/fragment-cache/-/fragment-cache-0.2.1.tgz", @@ -18740,6 +18861,11 @@ "react-is": "^17.0.1" } }, + "printj": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/printj/-/printj-1.1.2.tgz", + "integrity": "sha512-zA2SmoLaxZyArQTOPj5LXecR+RagfPSU5Kw1qP+jkWeNlrq+eJZyY2oS68SU1Z/7/myXM4lo9716laOFAVStCQ==" + }, "process": { "version": "0.11.10", "resolved": "https://registry.npmjs.org/process/-/process-0.11.10.tgz", @@ -21180,6 +21306,14 @@ "integrity": "sha512-VE0SOVEHCk7Qc8ulkWw3ntAzXuqf7S2lvwQaDLRnUeIEaKNQJzV6BwmLKhOqT61aGhfUMrXeaBk+oDGCzvhcug==", "dev": true }, + "ssf": { + "version": "0.11.2", + "resolved": "https://registry.npmjs.org/ssf/-/ssf-0.11.2.tgz", + "integrity": "sha512-+idbmIXoYET47hH+d7dfm2epdOMUDjqcB4648sTZ+t2JwoyBFL/insLfB/racrDmsKB3diwsDA696pZMieAC5g==", + "requires": { + "frac": "~1.1.2" + } + }, "sshpk": { "version": "1.16.1", "resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.16.1.tgz", @@ -24599,6 +24733,16 @@ "pify": "^4.0.1" } }, + "wmf": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wmf/-/wmf-1.0.2.tgz", + "integrity": "sha512-/p9K7bEh0Dj6WbXg4JG0xvLQmIadrner1bi45VMJTfnbVHsc7yIajZyoSoK60/dtVBs12Fm6WkUI5/3WAVsNMw==" + }, + "word": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/word/-/word-0.3.0.tgz", + "integrity": "sha512-OELeY0Q61OXpdUfTp+oweA/vtLVg5VDOXh+3he3PNzLGG/y0oylSOC1xRVj0+l4vQ3tj/bB1HVHv1ocXkQceFA==" + }, "word-wrap": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.3.tgz", @@ -24651,6 +24795,30 @@ "resolved": "https://registry.npmjs.org/xdg-basedir/-/xdg-basedir-4.0.0.tgz", "integrity": "sha512-PSNhEJDejZYV7h50BohL09Er9VaIefr2LMAf3OEmpCkjOi34eYyQYAXUTjEQtZJTKcF0E2UKTh+osDLsgNim9Q==" }, + "xlsx": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/xlsx/-/xlsx-0.17.0.tgz", + "integrity": "sha512-bZ36FSACiAyjoldey1+7it50PMlDp1pcAJrZKcVZHzKd8BC/z6TQ/QAN8onuqcepifqSznR6uKnjPhaGt6ig9A==", + "requires": { + "adler-32": "~1.2.0", + "cfb": "^1.1.4", + "codepage": "~1.14.0", + "commander": "~2.17.1", + "crc-32": "~1.2.0", + "exit-on-epipe": "~1.0.1", + "fflate": "^0.3.8", + "ssf": "~0.11.2", + "wmf": "~1.0.1", + "word": "~0.3.0" + }, + "dependencies": { + "commander": { + "version": "2.17.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.17.1.tgz", + "integrity": "sha512-wPMUt6FnH2yzG95SA6mzjQOEKUU3aLaDEmzs1ti+1E9h+CsrZghRlqEM/EJ4KscsQVG8uNN4uVreUeT8+drlgg==" + } + } + }, "xml-name-validator": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-3.0.0.tgz", diff --git a/package.json b/package.json index be5ff886f..043a2de96 100644 --- a/package.json +++ b/package.json @@ -91,6 +91,7 @@ "@pdftron/pdfjs-express": "^8.0.1", "@types/jest-environment-puppeteer": "^4.4.1", "@types/puppeteer": "^5.4.4", + "alasql": "^1.7.3", "angular-calendar": "^0.28.22", "angular-cropperjs": "^0.1.5", "angular-svg-icon": "^12.0.0", diff --git a/src/app/pages/chat/group-messages/group-messages.page.ts b/src/app/pages/chat/group-messages/group-messages.page.ts index 5623e58b7..f3195f633 100644 --- a/src/app/pages/chat/group-messages/group-messages.page.ts +++ b/src/app/pages/chat/group-messages/group-messages.page.ts @@ -446,13 +446,18 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy { await this.fileService.saveImage(image) const lastphoto: any = await this.fileService.loadFiles(); const { capturedImage, capturedImageTitle} = await this.fileService.loadFileData(lastphoto); + const base64 = await fetch(capturedImage); + const blob = await base64.blob(); + const formData = new FormData(); + formData.append("blobFile", blob); - const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(this.roomId).send({ + this.wsChatMethodsService.getDmRoom(roomId).send({ file: { "type": "application/img", "guid": '', "image_url": capturedImage }, + temporary: formData, attachments: [{ "title": capturedImageTitle , "text": "description", @@ -460,40 +465,6 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy { }] }) - - 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() - updateMessage({ - file: { - type: "application/img", - guid: guid.path, - image_url: capturedImage - } - }) - - 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', capturedImage); - await this.storage.set(guid.path, capturedImage).then(() => { - console.log('add picture to chat IMAGE SAVED') - message.getFileFromDb() - }); - - } - - }); - } async addImage() { @@ -521,7 +492,7 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy { if(data.selected) { const loader = this.toastService.loading(); - const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(this.roomId).send({ + this.wsChatMethodsService.getDmRoom(this.roomId).send({ file:{ "name": res.data.selected.Assunto, "type": "application/webtrix", @@ -536,28 +507,14 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy { "title_link_download": true, //"thumb_url": "assets/images/webtrix-logo.png", // "message_link": url_no_options, - "type": "webtrix" - }] - }) - - 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); - - updateMessage({ - 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", + //"thumb_url": "assets/images/webtrix-logo.png", "text": res.data.selected.DocTypeDesc, "thumb_url": "https://static.ichimura.ed.jp/uploads/2017/10/pdf-icon.png", }] }) + loader.remove(); } @@ -572,12 +529,13 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy { const formData = new FormData(); formData.append("blobFile", file); - const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(this.roomId).send({ + this.wsChatMethodsService.getDmRoom(this.roomId).send({ file: { "type": "application/img", "guid": '', "image_url": imageData }, + temporary: formData, attachments: [{ "title": file.name , "text": "description", @@ -585,30 +543,6 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy { }] }) - let guid: any = await this.AttachmentsService.uploadFile(formData).toPromise() - updateMessage({ - file: { - type: "application/img", - guid: guid.path, - image_url: imageData - } - }) - - 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') - message.getFileFromDb() - }); - } - - }); } async openChatOptions(ev?: any) { diff --git a/src/app/pages/chat/messages/messages.page.ts b/src/app/pages/chat/messages/messages.page.ts index cc7d24b79..7b17085bb 100644 --- a/src/app/pages/chat/messages/messages.page.ts +++ b/src/app/pages/chat/messages/messages.page.ts @@ -529,7 +529,14 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { const lastphoto: any = await this.fileService.loadFiles(); const { capturedImage, capturedImageTitle} = await this.fileService.loadFileData(lastphoto); - const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(roomId).send({ + + const base64 = await fetch(capturedImage); + const blob = await base64.blob(); + const formData = new FormData(); + formData.append("blobFile", blob); + console.log('ALL IMAGE', formData) + + this.wsChatMethodsService.getDmRoom(roomId).send({ file: { "type": "application/img", "guid": '', @@ -539,43 +546,10 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { "title": capturedImageTitle , "text": "description", "title_link_download": false, - }] + }], + temporary: formData }) - - 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() - updateMessage({ - file: { - type: "application/img", - guid: guid.path, - image_url: capturedImage - } - }) - - 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', capturedImage); - await this.storage.set(guid.path, capturedImage).then(() => { - console.log('add picture to chat IMAGE SAVED') - message.getFileFromDb() - }); - - } - - }); - } async addImage() { @@ -604,7 +578,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { if(data.selected) { const loader = this.toastService.loading(); - const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(roomId).send({ + this.wsChatMethodsService.getDmRoom(roomId).send({ file:{ "name": res.data.selected.Assunto, "type": "application/webtrix", @@ -617,27 +591,10 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { "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" - }] - }) - - 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); - - updateMessage({ - 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", - "text": res.data.selected.DocTypeDesc, "thumb_url": "https://static.ichimura.ed.jp/uploads/2017/10/pdf-icon.png", + // "message_link": url_no_options, + "text": res.data.selected.DocTypeDesc, + "type": "webtrix" }] }) @@ -658,12 +615,13 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { const formData = new FormData(); formData.append("blobFile", file); - const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(roomId).send({ + this.wsChatMethodsService.getDmRoom(roomId).send({ file: { "type": "application/img", "guid": '', "image_url": imageData }, + temporary: formData, attachments: [{ "title": file.name , "text": "description", @@ -671,30 +629,6 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { }] }) - let guid: any = await this.AttachmentsService.uploadFile(formData).toPromise() - updateMessage({ - file: { - type: "application/img", - guid: guid.path, - image_url: imageData - } - }) - - 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') - message.getFileFromDb() - }); - } - - }); } async openChatOptions(ev?: any) { diff --git a/src/app/services/attachments.service.ts b/src/app/services/attachments.service.ts index 1c20db0dd..2beeaef61 100644 --- a/src/app/services/attachments.service.ts +++ b/src/app/services/attachments.service.ts @@ -3,8 +3,8 @@ import { Attachment, EventAttachment } from '../models/attachment.model'; import { Observable } from 'rxjs'; import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'; import { environment } from 'src/environments/environment'; -import { AuthService } from '../services/auth.service'; import { LoginUserRespose } from '../models/user.model'; +import { SessionStore } from '../store/session.service'; @Injectable({ providedIn: 'root' @@ -14,10 +14,10 @@ export class AttachmentsService { loggeduser: LoginUserRespose; headers: HttpHeaders; - constructor(private http: HttpClient, user: AuthService) { - this.loggeduser = user.ValidatedUser; + constructor(private http: HttpClient) { + this.loggeduser = SessionStore.user this.headers = new HttpHeaders(); - this.headers = this.headers.set('Authorization', this.loggeduser.BasicAuthKey); + this.headers = this.headers.set('Authorization', SessionStore.user.BasicAuthKey); } uploadFile(formData:any) { diff --git a/src/app/services/auth.service.ts b/src/app/services/auth.service.ts index 6c844238f..700c24c46 100644 --- a/src/app/services/auth.service.ts +++ b/src/app/services/auth.service.ts @@ -12,6 +12,12 @@ import { AESEncrypt } from '../services/aesencrypt.service'; import { CookieService } from 'ngx-cookie-service'; import { WsChatService } from 'src/app/services/chat/ws-chat.service'; import { Router } from '@angular/router'; +import { NfService } from 'src/app/services/chat/nf.service' +import { MessageService } from 'src/app/services/chat/message.service'; +import { ProcessesService } from 'src/app/services/processes.service'; +import { AttachmentsService } from 'src/app/services/attachments.service'; +import { RoomService } from './chat/room.service'; +import { Storage } from '@ionic/storage'; @Injectable({ providedIn: 'root' }) @@ -33,7 +39,11 @@ export class AuthService { private aesencrypt: AESEncrypt, private cookieService: CookieService, private WsChatService: WsChatService, - private router: Router,) { + private router: Router, + private NfService:NfService, + private processesService: ProcessesService, + private AttachmentsService: AttachmentsService, + private storage: Storage ) { this.headers = new HttpHeaders(); @@ -41,13 +51,7 @@ export class AuthService { this.ValidatedUser = SessionStore.user console.log('login', SessionStore.user.RochetChatUser, SessionStore.user.Password) - this.WsChatService.connect(); - this.WsChatService.login().then((message) => { - console.log('rocket chat login successfully', message) - this.WsChatService.setStatus('busy') - }).catch((message)=>{ - console.log('rocket chat login failed', message) - }) + this.loginToChatWs() } @@ -115,16 +119,7 @@ export class AuthService { if(responseChat) { - setTimeout(()=>{ - - this.WsChatService.connect(); - this.WsChatService.login().then((message) => { - console.log('rocket chat login successfully', message) - this.WsChatService.setStatus('online') - }).catch((message)=>{ - console.log('rocket chat login failed', message) - }) - }, 1) + this.loginToChatWs() console.log('Login to Rocket chat OK'); this.ValidatedUserChat = responseChat; @@ -143,6 +138,47 @@ export class AuthService { } } + private loginToChatWs() { + setTimeout(()=>{ + + this.WsChatService.connect(); + this.WsChatService.login().then((message) => { + console.log('rocket chat login successfully', message) + this.WsChatService.setStatus('online') + }).catch((message)=>{ + console.log('rocket chat login failed', message) + }) + + + this.NfService.beforeSendAttachment = async (message: MessageService, room?: RoomService) => { + + if(message.hasFile) { + if(message.file.type != 'application/webtrix') { + const formData = message.temporaryData + let guid: any = await this.AttachmentsService.uploadFile(formData).toPromise() + message.file.guid = guid.path + await this.storage.set(guid.path, message.file.image_url).then(() => { + console.log('add picture to chat IMAGE SAVED') + message.getFileFromDb() + }); + + return true + } else { + const res = message.temporaryData + 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"); + message.attachments[0].title_link = url_no_options + message.attachments[0].message_link = url_no_options + + return true + } + } + + return false + } + }, 1) + } + autologout(expirationDate:number){ setTimeout(()=>{ this.logout(); diff --git a/src/app/services/chat/message.service.ts b/src/app/services/chat/message.service.ts index e803e3beb..d34f0caa6 100644 --- a/src/app/services/chat/message.service.ts +++ b/src/app/services/chat/message.service.ts @@ -3,6 +3,7 @@ import { Message } from 'src/app/models/chatMethod'; import { Storage } from '@ionic/storage'; import { SessionStore } from 'src/app/store/session.service'; import { capitalizeTxt } from 'src/plugin/text' +import { NfService } from 'src/app/services/chat/nf.service' @Injectable({ providedIn: 'root' @@ -23,9 +24,12 @@ export class MessageService { attachments offline = true displayType = '' - temporaryData = {} + temporaryData: any = {} + hasFile = false + hasSendAttachment = false - constructor(private storage: Storage) { + constructor(private storage: Storage, + private NfService: NfService) { } setData({customFields, channels, mentions, msg ,rid ,ts, u, t, _id, _updatedAt, file, attachments, temporaryData}:Message) { @@ -49,18 +53,20 @@ export class MessageService { this.offline = false } - if (this.file) { - this.getFileFromDb() if(this.file.type) { - if(this.file.type != 'application/webtrix' && typeof(this.file.type) == 'string') { - this.displayType = this.file.type.replace('application/','').toUpperCase() + if(typeof(this.file.type) == 'string') { + this.hasFile = true } } - } - + if(this.hasFile) { + this.getFileFromDb() + if(this.file.type != 'application/webtrix') { + this.displayType = this.file.type.replace('application/','').toUpperCase() + } + } } private usernameToDisplayName(username) { @@ -71,13 +77,13 @@ export class MessageService { } getFileFromDb() { - if (this.file) { + + if(this.hasFile) { if (this.file.guid) { this.storage.get(this.file.guid).then((image) => { if(image != null) { this.file.image_url = image } - }); } } diff --git a/src/app/services/chat/nf.service.ts b/src/app/services/chat/nf.service.ts index ea45b17e5..d22bd877b 100644 --- a/src/app/services/chat/nf.service.ts +++ b/src/app/services/chat/nf.service.ts @@ -1,9 +1,14 @@ import { Injectable } from '@angular/core'; +import { MessageService } from './message.service'; +import { RoomService } from './room.service'; @Injectable({ providedIn: 'root' }) export class NfService { + beforeSendAttachment = (message: MessageService, room?: RoomService): Promise => new Promise ((resolve, reject)=> (resolve(true))) + + constructor() { } } diff --git a/src/app/services/chat/room.service.ts b/src/app/services/chat/room.service.ts index 332263585..5566246f0 100644 --- a/src/app/services/chat/room.service.ts +++ b/src/app/services/chat/room.service.ts @@ -14,6 +14,7 @@ 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'; +import { NfService } from 'src/app/services/chat/nf.service' @Injectable({ providedIn: 'root' @@ -63,11 +64,12 @@ export class RoomService { private NativeNotificationService: NativeNotificationService, private sortService: SortService, private chatService: ChatService, + private NfService: NfService ) { this.NativeNotificationService.askForPermission() } - setData({ customFields, id, name, t, lastMessage = new MessageService(this.storage), _updatedAt }) { + setData({ customFields, id, name, t, lastMessage = new MessageService(this.storage, this.NfService), _updatedAt }) { this.customFields = customFields this.id = id this.name = name @@ -232,19 +234,21 @@ export class RoomService { }) } else { console.log('complex send') - return { - message: message, - updateMessage: (update)=> { - offlineChatMessage = Object.assign(offlineChatMessage, update) + + const result = this.NfService.beforeSendAttachment(message, this) + + delete message.temporaryData; + + if(result) { + message.hasSendAttachment = true - this.WsChatService.send({roomId:this.id, msg:message.msg,attachments:offlineChatMessage.attachments, file:offlineChatMessage.file}).then((data: any) => { - console.log('send sucees', data.result) - let ChatMessage = data.result - this.redefinedMessage(message, ChatMessage) - }) - - } + this.WsChatService.send({roomId:this.id, msg:message.msg, attachments:offlineChatMessage.attachments, file:offlineChatMessage.file}).then((data: any) => { + console.log('send sucees', data.result) + let ChatMessage = data.result + this.redefinedMessage(message, ChatMessage) + }) } + } @@ -398,7 +402,7 @@ export class RoomService { prepareMessage(message): MessageService { message = this.fix_updatedAt(message) - const wewMessage = new MessageService(this.storage) + const wewMessage = new MessageService(this.storage, this.NfService) wewMessage.setData(message) this.messages.push(wewMessage) diff --git a/src/app/services/chat/ws-chat-methods.service.ts b/src/app/services/chat/ws-chat-methods.service.ts index 2926c42c3..b83120169 100644 --- a/src/app/services/chat/ws-chat-methods.service.ts +++ b/src/app/services/chat/ws-chat-methods.service.ts @@ -12,7 +12,7 @@ import { ChatService } from 'src/app/services/chat.service'; import { NativeNotificationService } from 'src/app/services/native-notification.service'; import { SortService } from '../functions/sort.service'; import { chatUser } from 'src/app/models/chatMethod'; - +import { NfService } from 'src/app/services/chat/nf.service' @Injectable({ providedIn: 'root' }) @@ -41,7 +41,8 @@ export class WsChatMethodsService { private sqlservice: SqliteService, private NativeNotificationService: NativeNotificationService, private sortService: SortService, - private ChatService: ChatService + private ChatService: ChatService, + private NfService: NfService ) { (async()=>{ await this.getAllRooms(); @@ -203,7 +204,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, this.ChatService) + room = new RoomService(this.WsChatService, new MessageService(this.storage, this.NfService), this.storage, this.platform, this.sqlservice, this.NativeNotificationService, this.sortService, this.ChatService, this.NfService) room.setData({ customFields: roomData.customFields, diff --git a/src/app/services/processes.service.ts b/src/app/services/processes.service.ts index c68ad489f..c5a108962 100644 --- a/src/app/services/processes.service.ts +++ b/src/app/services/processes.service.ts @@ -1,6 +1,5 @@ import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'; -import { AuthService } from '../services/auth.service'; import { LoginUserRespose } from '../models/user.model'; import { environment } from 'src/environments/environment'; import { Observable } from 'rxjs'; @@ -10,7 +9,7 @@ import { ExpedienteFullTask } from '../models/Expediente'; import { GetTasksListType } from '../models/GetTasksListType'; import { fullTaskList } from '../models/dailyworktask.model'; import { ChangeProfileService } from './change-profile.service'; - +import { SessionStore } from '../store/session.service'; @Injectable({ providedIn: 'root' }) @@ -22,15 +21,14 @@ export class ProcessesService { constructor( private http: HttpClient, - public user: AuthService, private changeProfileService: ChangeProfileService ) { - this.loggeduser = this.user.ValidatedUser; + this.loggeduser = SessionStore.user; this.setHeader() this.changeProfileService.registerCallback(()=>{ - this.loggeduser = this.user.ValidatedUser; + this.loggeduser = SessionStore.user; this.setHeader() }) diff --git a/src/app/shared/chat/group-messages/group-messages.page.ts b/src/app/shared/chat/group-messages/group-messages.page.ts index eb6fdda08..ef53b1210 100644 --- a/src/app/shared/chat/group-messages/group-messages.page.ts +++ b/src/app/shared/chat/group-messages/group-messages.page.ts @@ -550,7 +550,12 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe const lastphoto: any = await this.fileService.loadFiles(); const { capturedImage, capturedImageTitle} = await this.fileService.loadFileData(lastphoto); - const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(roomId).send({ + const base64 = await fetch(capturedImage); + const blob = await base64.blob(); + const formData = new FormData(); + formData.append("blobFile", blob); + + this.wsChatMethodsService.getDmRoom(roomId).send({ file: { "type": "application/img", "guid": '', @@ -563,40 +568,6 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe }] }) - - 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() - updateMessage({ - file: { - type: "application/img", - guid: guid.path, - image_url: capturedImage - } - }) - - 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', capturedImage); - await this.storage.set(guid.path, capturedImage).then(() => { - console.log('add picture to chat IMAGE SAVED') - message.getFileFromDb() - }); - - } - - }); - } async addImage() { @@ -626,7 +597,7 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe if(data.selected) { const loader = this.toastService.loading(); - const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(roomId).send({ + this.wsChatMethodsService.getDmRoom(roomId).send({ file:{ "name": res.data.selected.Assunto, "type": "application/webtrix", @@ -641,23 +612,8 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe "title_link_download": true, //"thumb_url": "assets/images/webtrix-logo.png", // "message_link": url_no_options, - "type": "webtrix" - }] - }) - - 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); - - updateMessage({ - 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", + //"thumb_url": "assets/images/webtrix-logo.png", "text": res.data.selected.DocTypeDesc, "thumb_url": "https://static.ichimura.ed.jp/uploads/2017/10/pdf-icon.png", }] @@ -680,43 +636,19 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe const formData = new FormData(); formData.append("blobFile", file); - const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(roomId).send({ + this.wsChatMethodsService.getDmRoom(roomId).send({ file: { "type": "application/img", "guid": '', "image_url": imageData }, + temporary: formData, attachments: [{ "title": file.name , "text": "description", "title_link_download": false, }] }) - - let guid: any = await this.AttachmentsService.uploadFile(formData).toPromise() - updateMessage({ - file: { - type: "application/img", - guid: guid.path, - image_url: imageData - } - }) - - 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') - message.getFileFromDb() - }); - } - - }); } bookMeeting() { diff --git a/src/app/shared/chat/messages/messages.page.ts b/src/app/shared/chat/messages/messages.page.ts index 7d388fdaf..f95cdd2b7 100644 --- a/src/app/shared/chat/messages/messages.page.ts +++ b/src/app/shared/chat/messages/messages.page.ts @@ -450,13 +450,18 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy await this.fileService.saveImage(image) const lastphoto: any = await this.fileService.loadFiles(); const { capturedImage, capturedImageTitle} = await this.fileService.loadFileData(lastphoto); + const base64 = await fetch(capturedImage); + const blob = await base64.blob(); + const formData = new FormData(); + formData.append("blobFile", blob); - const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(roomId).send({ + this.wsChatMethodsService.getDmRoom(roomId).send({ file: { "type": "application/img", "guid": '', "image_url": capturedImage }, + temporary: formData, attachments: [{ "title": capturedImageTitle , "text": "description", @@ -464,40 +469,6 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy }] }) - - 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() - updateMessage({ - file: { - type: "application/img", - guid: guid.path, - image_url: capturedImage - } - }) - - 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', capturedImage); - await this.storage.set(guid.path, capturedImage).then(() => { - console.log('add picture to chat IMAGE SAVED') - message.getFileFromDb() - }); - - } - - }); - } async addImage() { @@ -526,7 +497,7 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy if(data.selected) { const loader = this.toastService.loading(); - const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(roomId).send({ + this.wsChatMethodsService.getDmRoom(roomId).send({ file:{ "name": res.data.selected.Assunto, "type": "application/webtrix", @@ -537,31 +508,12 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy 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" - }], - temporary: res - }) - - 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); - - updateMessage({ - 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", "text": res.data.selected.DocTypeDesc, "thumb_url": "https://static.ichimura.ed.jp/uploads/2017/10/pdf-icon.png", - }] + }], + temporary: res }) loader.remove(); @@ -581,7 +533,7 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy const formData = new FormData(); formData.append("blobFile", file); - const { message, updateMessage} = this.wsChatMethodsService.getDmRoom(roomId).send({ + this.wsChatMethodsService.getDmRoom(roomId).send({ file: { "type": "application/img", "guid": '', @@ -594,30 +546,6 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy }] }) - let guid: any = await this.AttachmentsService.uploadFile(formData).toPromise() - updateMessage({ - file: { - type: "application/img", - guid: guid.path, - image_url: imageData - } - }) - - 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') - message.getFileFromDb() - }); - } - - }); } From 202b430966861d1bd82a248f1e3413e4fc610325 Mon Sep 17 00:00:00 2001 From: Peter Maquiran Date: Mon, 7 Feb 2022 18:48:33 +0100 Subject: [PATCH 24/27] improve --- src/app/services/chat/room.service.ts | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/src/app/services/chat/room.service.ts b/src/app/services/chat/room.service.ts index 5566246f0..e4ac8208f 100644 --- a/src/app/services/chat/room.service.ts +++ b/src/app/services/chat/room.service.ts @@ -15,7 +15,7 @@ import { chatUser } from 'src/app/models/chatMethod'; import { environment } from 'src/environments/environment'; import { ChatService } from 'src/app/services/chat.service'; import { NfService } from 'src/app/services/chat/nf.service' - +import alasql from 'alasql' @Injectable({ providedIn: 'root' }) @@ -238,7 +238,7 @@ export class RoomService { const result = this.NfService.beforeSendAttachment(message, this) delete message.temporaryData; - + if(result) { message.hasSendAttachment = true @@ -341,25 +341,26 @@ export class RoomService { restoreMessageFromDB() { this.storage.get('chatmsg' + this.id).then((messages = []) => { - let localMessages = [] + let localMessages: MessageService[] = [] if(messages==null) messages = [] - messages.reverse().forEach((ChatMessage, index) => { + messages.forEach((ChatMessage, index) => { const wewMessage = this.prepareMessage(ChatMessage) if(wewMessage.offline == true) { - this.WsChatService.send({roomId:this.id, msg:wewMessage.msg, attachments:wewMessage.attachments, file: wewMessage.file}).then((data: any) => { - let _ChatMessage = data.result - this.redefinedMessage(wewMessage, _ChatMessage) - this.storage.set('chatmsg' + this.id, messages) - }) + // this.WsChatService.send({roomId:this.id, msg:wewMessage.msg, attachments:wewMessage.attachments, file: wewMessage.file}).then((data: any) => { + // let _ChatMessage = data.result + // this.redefinedMessage(wewMessage, _ChatMessage) + // this.storage.set('chatmsg' + this.id, messages) + // }) } localMessages.push(wewMessage) }); - this.messages = localMessages + this.messages = alasql('SELECT * FROM ? ORDER BY _updatedAt',[localMessages]); + }) } @@ -386,7 +387,6 @@ export class RoomService { console.log(chatHistory.result.messages); - this.storage.set('chatmsg' + this.id, chatHistory.result.messages.reverse()) }) From 0d9adb0bb832b6e93e4d034a07d9cd96d34b3ecd Mon Sep 17 00:00:00 2001 From: Peter Maquiran Date: Mon, 7 Feb 2022 20:18:48 +0100 Subject: [PATCH 25/27] fix --- .../group-messages/group-messages.page.ts | 4 +- src/app/pages/chat/messages/messages.page.ts | 6 +- src/app/services/auth.service.ts | 32 ++++++----- src/app/services/chat/message.service.ts | 35 ++++++++++-- src/app/services/chat/nf.service.ts | 2 +- src/app/services/chat/room.service.ts | 57 ++++++++++--------- .../services/chat/ws-chat-methods.service.ts | 2 +- .../group-messages/group-messages.page.ts | 8 ++- src/app/shared/chat/messages/messages.page.ts | 8 ++- 9 files changed, 97 insertions(+), 57 deletions(-) diff --git a/src/app/pages/chat/group-messages/group-messages.page.ts b/src/app/pages/chat/group-messages/group-messages.page.ts index f3195f633..f439a2811 100644 --- a/src/app/pages/chat/group-messages/group-messages.page.ts +++ b/src/app/pages/chat/group-messages/group-messages.page.ts @@ -457,7 +457,7 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy { "guid": '', "image_url": capturedImage }, - temporary: formData, + temporaryData: formData, attachments: [{ "title": capturedImageTitle , "text": "description", @@ -535,7 +535,7 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy { "guid": '', "image_url": imageData }, - temporary: formData, + temporaryData: formData, attachments: [{ "title": file.name , "text": "description", diff --git a/src/app/pages/chat/messages/messages.page.ts b/src/app/pages/chat/messages/messages.page.ts index 7b17085bb..da1621467 100644 --- a/src/app/pages/chat/messages/messages.page.ts +++ b/src/app/pages/chat/messages/messages.page.ts @@ -547,7 +547,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { "text": "description", "title_link_download": false, }], - temporary: formData + temporaryData: formData }) } @@ -595,7 +595,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { // "message_link": url_no_options, "text": res.data.selected.DocTypeDesc, "type": "webtrix" - }] + }], }) loader.remove(); @@ -621,7 +621,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { "guid": '', "image_url": imageData }, - temporary: formData, + temporaryData: formData, attachments: [{ "title": file.name , "text": "description", diff --git a/src/app/services/auth.service.ts b/src/app/services/auth.service.ts index 700c24c46..54ddc9847 100644 --- a/src/app/services/auth.service.ts +++ b/src/app/services/auth.service.ts @@ -155,22 +155,28 @@ export class AuthService { if(message.hasFile) { if(message.file.type != 'application/webtrix') { const formData = message.temporaryData - let guid: any = await this.AttachmentsService.uploadFile(formData).toPromise() - message.file.guid = guid.path - await this.storage.set(guid.path, message.file.image_url).then(() => { - console.log('add picture to chat IMAGE SAVED') - message.getFileFromDb() - }); - return true + try { + let guid: any = await this.AttachmentsService.uploadFile(formData).toPromise() + message.file.guid = guid.path + await this.storage.set(guid.path, message.file.image_url).then(() => { + console.log('add picture to chat IMAGE SAVED') + message.getFileFromDb() + return true + }); + } catch(e) {} + } else { - const res = message.temporaryData - 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"); - message.attachments[0].title_link = url_no_options - message.attachments[0].message_link = url_no_options + try { + const res = message.temporaryData + 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"); + message.attachments[0].title_link = url_no_options + message.attachments[0].message_link = url_no_options + return true - return true + } catch(e) {} + } } diff --git a/src/app/services/chat/message.service.ts b/src/app/services/chat/message.service.ts index d34f0caa6..976a81e21 100644 --- a/src/app/services/chat/message.service.ts +++ b/src/app/services/chat/message.service.ts @@ -4,7 +4,7 @@ import { Storage } from '@ionic/storage'; import { SessionStore } from 'src/app/store/session.service'; import { capitalizeTxt } from 'src/plugin/text' import { NfService } from 'src/app/services/chat/nf.service' - +import { WsChatService } from 'src/app/services/chat/ws-chat.service'; @Injectable({ providedIn: 'root' }) @@ -29,7 +29,8 @@ export class MessageService { hasSendAttachment = false constructor(private storage: Storage, - private NfService: NfService) { + private NfService: NfService, + private WsChatService: WsChatService) { } setData({customFields, channels, mentions, msg ,rid ,ts, u, t, _id, _updatedAt, file, attachments, temporaryData}:Message) { @@ -45,7 +46,7 @@ export class MessageService { this._updatedAt = _updatedAt || new Date().getTime() this.file = file this.attachments = attachments - this,temporaryData = {} + this.temporaryData = temporaryData if(!this.ts) { this.offline = true @@ -90,7 +91,33 @@ export class MessageService { } sendFile() { - + if(this.file == null && this.attachments == null) { + console.log('simple send') + this.WsChatService.send({roomId:this.rid, msg:this.msg}).then((data: any) => { + let ChatMessage = data.result + this.redefinedMessage(this, ChatMessage) + }) + } else { + console.log('complex send') + + const result = this.NfService.beforeSendAttachment(this) + + + if(result) { + this.hasSendAttachment = true + + this.WsChatService.send({roomId:this.rid, msg: this.msg, attachments: this.attachments, file: this.file}).then((data: any) => { + console.log('send sucees', data.result) + let ChatMessage = data.result + this.redefinedMessage(this, ChatMessage) + }) + } + + } + } + + redefinedMessage(messagem, ChatMessage){ + this.setData(ChatMessage) } } diff --git a/src/app/services/chat/nf.service.ts b/src/app/services/chat/nf.service.ts index d22bd877b..7bfbd26be 100644 --- a/src/app/services/chat/nf.service.ts +++ b/src/app/services/chat/nf.service.ts @@ -7,7 +7,7 @@ import { RoomService } from './room.service'; }) export class NfService { - beforeSendAttachment = (message: MessageService, room?: RoomService): Promise => new Promise ((resolve, reject)=> (resolve(true))) + beforeSendAttachment = async (message: MessageService, room?: RoomService): Promise => new Promise ((resolve, reject)=> (resolve(true))) constructor() { } diff --git a/src/app/services/chat/room.service.ts b/src/app/services/chat/room.service.ts index e4ac8208f..c2a61a60a 100644 --- a/src/app/services/chat/room.service.ts +++ b/src/app/services/chat/room.service.ts @@ -69,7 +69,7 @@ export class RoomService { this.NativeNotificationService.askForPermission() } - setData({ customFields, id, name, t, lastMessage = new MessageService(this.storage, this.NfService), _updatedAt }) { + setData({ customFields, id, name, t, lastMessage = new MessageService(this.storage, this.NfService, this.WsChatService), _updatedAt }) { this.customFields = customFields this.id = id this.name = name @@ -138,6 +138,7 @@ export class RoomService { addMessageDB(ChatMessage) { this.storage.get('chatmsg' + this.id).then((messages: any = []) => { + delete ChatMessage.temporaryData messages.push(ChatMessage) this.storage.set('chatmsg' + this.id, messages) @@ -205,7 +206,7 @@ export class RoomService { /** * @description sen text message */ - send({file = null, attachments = null, temporary= {}}) { + async send({file = null, attachments = null, temporaryData = {}}) { let offlineChatMessage = { @@ -213,8 +214,10 @@ export class RoomService { msg: this.message, attachments, file, - temporary + temporaryData } + + console.log('offlineChatMessage', offlineChatMessage) this.addMessageDB(offlineChatMessage) const message: MessageService = this.prepareMessage(offlineChatMessage) @@ -235,9 +238,8 @@ export class RoomService { } else { console.log('complex send') - const result = this.NfService.beforeSendAttachment(message, this) - - delete message.temporaryData; + const result = await this.NfService.beforeSendAttachment(message, this) + if(result) { message.hasSendAttachment = true @@ -338,57 +340,58 @@ export class RoomService { } - restoreMessageFromDB() { - this.storage.get('chatmsg' + this.id).then((messages = []) => { - - let localMessages: MessageService[] = [] + async restoreMessageFromDB() { + await this.storage.get('chatmsg' + this.id).then( async (messages = []) => { if(messages==null) messages = [] - messages.forEach((ChatMessage, index) => { + await messages.forEach( async (ChatMessage, index) => { const wewMessage = this.prepareMessage(ChatMessage) if(wewMessage.offline == true) { // this.WsChatService.send({roomId:this.id, msg:wewMessage.msg, attachments:wewMessage.attachments, file: wewMessage.file}).then((data: any) => { // let _ChatMessage = data.result // this.redefinedMessage(wewMessage, _ChatMessage) + // messages[index] = _ChatMessage // this.storage.set('chatmsg' + this.id, messages) // }) } - localMessages.push(wewMessage) }); - this.messages = alasql('SELECT * FROM ? ORDER BY _updatedAt',[localMessages]); + this.messages = alasql('SELECT * FROM ? ORDER BY _updatedAt',[ this.messages]); + setTimeout(()=> { + this.scrollDown() + }, 50) + }) } // runs onces only - loadHistory(limit = 100) { + async loadHistory(limit = 100) { if (this.hasLoadHistory) { return false } - this.restoreMessageFromDB() + await this.restoreMessageFromDB() - this.WsChatService.loadHistory(this.id, limit).then((chatHistory:chatHistory) => { + await this.WsChatService.loadHistory(this.id, limit).then( async (chatHistory:chatHistory) => { console.log('loadHistory', chatHistory) + this.messages = [] - let localMessages = [] + await chatHistory.result.messages.reverse().forEach( async (message) => { + this.prepareMessage(message) - chatHistory.result.messages.reverse().forEach(message => { - - const wewMessage = this.prepareMessage(message) - - localMessages.push(wewMessage) + // const result = alasql(`SELECT * FROM ? WHERE _id = "${message._id}" `,[ this.messages]); + // if(result.length == 0) { + // this.prepareMessage(message) + // this.storage.set('chatmsg' + this.id, chatHistory.result.messages.concat([message])) + // } + }); - this.messages = localMessages - console.log(chatHistory.result.messages); - this.storage.set('chatmsg' + this.id, chatHistory.result.messages.reverse()) - }) setTimeout(() => { @@ -402,7 +405,7 @@ export class RoomService { prepareMessage(message): MessageService { message = this.fix_updatedAt(message) - const wewMessage = new MessageService(this.storage, this.NfService) + const wewMessage = new MessageService(this.storage, this.NfService, this.WsChatService) wewMessage.setData(message) this.messages.push(wewMessage) diff --git a/src/app/services/chat/ws-chat-methods.service.ts b/src/app/services/chat/ws-chat-methods.service.ts index b83120169..6ea061412 100644 --- a/src/app/services/chat/ws-chat-methods.service.ts +++ b/src/app/services/chat/ws-chat-methods.service.ts @@ -204,7 +204,7 @@ export class WsChatMethodsService { prepareRoom(roomData) { let room:RoomService; - room = new RoomService(this.WsChatService, new MessageService(this.storage, this.NfService), this.storage, this.platform, this.sqlservice, this.NativeNotificationService, this.sortService, this.ChatService, this.NfService) + room = new RoomService(this.WsChatService, new MessageService(this.storage, this.NfService, this.WsChatService), this.storage, this.platform, this.sqlservice, this.NativeNotificationService, this.sortService, this.ChatService, this.NfService) room.setData({ customFields: roomData.customFields, diff --git a/src/app/shared/chat/group-messages/group-messages.page.ts b/src/app/shared/chat/group-messages/group-messages.page.ts index ef53b1210..58425894a 100644 --- a/src/app/shared/chat/group-messages/group-messages.page.ts +++ b/src/app/shared/chat/group-messages/group-messages.page.ts @@ -565,7 +565,8 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe "title": capturedImageTitle , "text": "description", "title_link_download": false, - }] + }], + temporaryData: formData }) } @@ -616,7 +617,8 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe //"thumb_url": "assets/images/webtrix-logo.png", "text": res.data.selected.DocTypeDesc, "thumb_url": "https://static.ichimura.ed.jp/uploads/2017/10/pdf-icon.png", - }] + }], + temporaryData: res }) loader.remove(); @@ -642,7 +644,7 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe "guid": '', "image_url": imageData }, - temporary: formData, + temporaryData: formData, attachments: [{ "title": file.name , "text": "description", diff --git a/src/app/shared/chat/messages/messages.page.ts b/src/app/shared/chat/messages/messages.page.ts index f95cdd2b7..be848d425 100644 --- a/src/app/shared/chat/messages/messages.page.ts +++ b/src/app/shared/chat/messages/messages.page.ts @@ -455,13 +455,15 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy const formData = new FormData(); formData.append("blobFile", blob); + console.log('formData', formData) + this.wsChatMethodsService.getDmRoom(roomId).send({ file: { "type": "application/img", "guid": '', "image_url": capturedImage }, - temporary: formData, + temporaryData: formData, attachments: [{ "title": capturedImageTitle , "text": "description", @@ -513,7 +515,6 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy "text": res.data.selected.DocTypeDesc, "thumb_url": "https://static.ichimura.ed.jp/uploads/2017/10/pdf-icon.png", }], - temporary: res }) loader.remove(); @@ -543,7 +544,8 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy "title": file.name , "text": "description", "title_link_download": false, - }] + }], + temporaryData: formData }) } From c74594fe49e14be37243ce8ef51be53f2ad85bd4 Mon Sep 17 00:00:00 2001 From: Peter Maquiran Date: Mon, 7 Feb 2022 20:35:52 +0100 Subject: [PATCH 26/27] improve --- src/app/shared/chat/messages/messages.page.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/app/shared/chat/messages/messages.page.ts b/src/app/shared/chat/messages/messages.page.ts index be848d425..6ecc64c53 100644 --- a/src/app/shared/chat/messages/messages.page.ts +++ b/src/app/shared/chat/messages/messages.page.ts @@ -536,18 +536,21 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy this.wsChatMethodsService.getDmRoom(roomId).send({ file: { - "type": "application/img", + "type": file.type, "guid": '', - "image_url": imageData + "image_url": imageData, }, attachments: [{ "title": file.name , - "text": "description", + "name": file.name , + // "text": "description", + "image_url": imageData, "title_link_download": false, }], temporaryData: formData }) + } From cef4c39d6eb05937fcf613d31017be843d4bd08c Mon Sep 17 00:00:00 2001 From: Peter Maquiran Date: Mon, 7 Feb 2022 20:52:07 +0100 Subject: [PATCH 27/27] fix file --- .../pages/chat/group-messages/group-messages.page.ts | 2 ++ src/app/pages/chat/messages/messages.page.ts | 2 ++ src/app/services/auth.service.ts | 11 ++++++++--- .../shared/chat/group-messages/group-messages.page.ts | 2 ++ src/app/shared/chat/messages/messages.page.ts | 7 ++++--- 5 files changed, 18 insertions(+), 6 deletions(-) diff --git a/src/app/pages/chat/group-messages/group-messages.page.ts b/src/app/pages/chat/group-messages/group-messages.page.ts index f439a2811..eb3bcce11 100644 --- a/src/app/pages/chat/group-messages/group-messages.page.ts +++ b/src/app/pages/chat/group-messages/group-messages.page.ts @@ -460,6 +460,7 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy { temporaryData: formData, attachments: [{ "title": capturedImageTitle , + "image_url": capturedImage, // rocketchat "text": "description", "title_link_download": false, }] @@ -539,6 +540,7 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy { attachments: [{ "title": file.name , "text": "description", + "image_url": imageData, "title_link_download": false, }] }) diff --git a/src/app/pages/chat/messages/messages.page.ts b/src/app/pages/chat/messages/messages.page.ts index da1621467..52db3b6ea 100644 --- a/src/app/pages/chat/messages/messages.page.ts +++ b/src/app/pages/chat/messages/messages.page.ts @@ -543,6 +543,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { "image_url": capturedImage }, attachments: [{ + "image_url": capturedImage, "title": capturedImageTitle , "text": "description", "title_link_download": false, @@ -624,6 +625,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { temporaryData: formData, attachments: [{ "title": file.name , + "image_url": imageData, "text": "description", "title_link_download": false, }] diff --git a/src/app/services/auth.service.ts b/src/app/services/auth.service.ts index 54ddc9847..6620a316c 100644 --- a/src/app/services/auth.service.ts +++ b/src/app/services/auth.service.ts @@ -162,9 +162,12 @@ export class AuthService { await this.storage.set(guid.path, message.file.image_url).then(() => { console.log('add picture to chat IMAGE SAVED') message.getFileFromDb() - return true }); - } catch(e) {} + + return true + } catch(e) { + return false + } } else { try { @@ -175,7 +178,9 @@ export class AuthService { message.attachments[0].message_link = url_no_options return true - } catch(e) {} + } catch(e) { + return false + } } } diff --git a/src/app/shared/chat/group-messages/group-messages.page.ts b/src/app/shared/chat/group-messages/group-messages.page.ts index 58425894a..7be23ce8a 100644 --- a/src/app/shared/chat/group-messages/group-messages.page.ts +++ b/src/app/shared/chat/group-messages/group-messages.page.ts @@ -563,6 +563,7 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe }, attachments: [{ "title": capturedImageTitle , + "image_url": capturedImage, "text": "description", "title_link_download": false, }], @@ -647,6 +648,7 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe temporaryData: formData, attachments: [{ "title": file.name , + "image_url": imageData, "text": "description", "title_link_download": false, }] diff --git a/src/app/shared/chat/messages/messages.page.ts b/src/app/shared/chat/messages/messages.page.ts index 6ecc64c53..29e55cbb0 100644 --- a/src/app/shared/chat/messages/messages.page.ts +++ b/src/app/shared/chat/messages/messages.page.ts @@ -466,6 +466,7 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy temporaryData: formData, attachments: [{ "title": capturedImageTitle , + "image_url": capturedImage, "text": "description", "title_link_download": false, }] @@ -536,15 +537,15 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy this.wsChatMethodsService.getDmRoom(roomId).send({ file: { - "type": file.type, + "type": "application/img", "guid": '', - "image_url": imageData, + "image_url": imageData, // GPR }, attachments: [{ "title": file.name , "name": file.name , // "text": "description", - "image_url": imageData, + "image_url": imageData, // rocketchat "title_link_download": false, }], temporaryData: formData