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..e07c42b7d 100644 --- a/src/app/pages/publications/view-publications/view-publications.page.ts +++ b/src/app/pages/publications/view-publications/view-publications.page.ts @@ -68,15 +68,16 @@ export class ViewPublicationsPage implements OnInit { if (typeof (this.folderId) == 'object') { this.folderId = this.folderId['ProcessId'] } - this.testForkJoin() + //this.testForkJoin() this.getPublicationDetail(); - setTimeout(() => { + this.getPublicationsIds(); + /* setTimeout(() => { this.getPublicationsIds(); - }, 1000); + }, 1000); */ this.backgroundservice.registerBackService('Online', () => { this.getPublicationDetail(); - this.testForkJoin() + //this.testForkJoin() }) @@ -91,18 +92,18 @@ export class ViewPublicationsPage implements OnInit { // if (typeof (this.id == 'object') { // this.id = this.id['ProcessId'] // } - this.testForkJoin() - this.getPublicationDetail(); + //this.testForkJoin() + //this.getPublicationDetail(); // this.getPublicationsIds(); } doRefresh = (event) => { - setTimeout(() => { - this.testForkJoin() + //setTimeout(() => { + //this.testForkJoin() this.getPublicationDetail(); - // this.getPublicationsIds(); + this.getPublicationsIds(); event.target.complete(); - }, 3000); + //}, 3000); } @@ -116,13 +117,14 @@ 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; + this.sqliteservice.updatePublicationsDetails(this.folderId, JSON.stringify(res)); }); } -// goes to fork + // goes to fork // getPublicationsIds() { // this.showLoader = true; @@ -138,22 +140,22 @@ 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 = 0; i < res.length; i++) { + this.publications.GetPublicationById(res[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 => { + /* res.forEach(element => { console.log('publications elements', element) this.publications.GetPublicationById(element).subscribe(ress => { console.log('publications by ids', ress) @@ -162,13 +164,13 @@ export class ViewPublicationsPage implements OnInit { this.publicationList.push(ress); }) - }); - + }); */ + console.log('PUBLICATIONS IMAGEs',this.publicationList) this.sqliteservice.updateactions(this.folderId, JSON.stringify(this.publicationList)); + console.log('PUBLICATIONS IMAGEs',this.publicationList) this.publicationListStorage.add(folderId, this.publicationList) this.getpublication = this.publicationList; - this.showLoader = false; /* this.publicationList = new Array(); @@ -189,7 +191,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 +225,13 @@ export class ViewPublicationsPage implements OnInit { }); } - testForkJoin(){ + testForkJoin() { forkJoin([ this.getPublicationsIds(), this.getPublications(), - ]).subscribe(allResults =>{ + ]).subscribe(allResults => { this.publicationList = allResults[2] }) } @@ -238,7 +240,7 @@ export class ViewPublicationsPage implements OnInit { this.sqliteservice.getActionById(this.folderId).then((publications) => { console.log('publications', publications) - let item = { + /* let item = { ActionType: publications[0].ActionType, DateBegin: publications[0].DateBegin, DateEnd: publications[0].DateEnd, @@ -246,10 +248,11 @@ export class ViewPublicationsPage implements OnInit { Detail: publications[0].Detail, ProcessId: publications[0].ProcessId } - this.publicationDitails = item; + this.publicationDitails = item; */ + 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, @@ -264,11 +267,20 @@ export class ViewPublicationsPage implements OnInit { publicationArray.push(publicationlis); }); - + this.getpublication = publicationArray; }) } + 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, diff --git a/src/app/services/attachments.service.ts b/src/app/services/attachments.service.ts index fa0be2ba1..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,12 +14,53 @@ 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) { + + 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/auth.service.ts b/src/app/services/auth.service.ts index 5a04f1b6d..be564c886 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() } @@ -119,16 +123,17 @@ export class AuthService { let responseChat = await this.httpService.post('login', postData).toPromise(); if(responseChat) { - console.log('Login to Rocket chat OK', responseChat); + + this.loginToChatWs() + + console.log('Login to Rocket chat OK'); this.ValidatedUserChat = responseChat; localStorage.setItem('userChat', JSON.stringify(responseChat)); this.storageService.store(AuthConnstants.AUTH, responseChat); - //return true; } else{ console.log('Network error'); this.presentAlert('Network error'); - //return false; } this.autoLoginChat(expirationDate.getTime() - date, user); @@ -140,6 +145,58 @@ export class AuthService { }, expirationDate) } + 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 + + 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) { + return false + } + + } else { + 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 + + } catch(e) { + return false + } + + } + } + + return false + } + }, 1) + } + autologout(expirationDate:number){ setTimeout(()=>{ this.logout(); diff --git a/src/app/services/chat/chat-user.service.spec.ts b/src/app/services/camera.service.spec.ts similarity index 53% rename from src/app/services/chat/chat-user.service.spec.ts rename to src/app/services/camera.service.spec.ts index 089b979cf..73b57d3a5 100644 --- a/src/app/services/chat/chat-user.service.spec.ts +++ b/src/app/services/camera.service.spec.ts @@ -1,13 +1,13 @@ import { TestBed } from '@angular/core/testing'; -import { ChatUserService } from './chat-user.service'; +import { CameraService } from './camera.service'; -describe('ChatUserService', () => { - let service: ChatUserService; +describe('CameraService', () => { + let service: CameraService; beforeEach(() => { TestBed.configureTestingModule({}); - service = TestBed.inject(ChatUserService); + service = TestBed.inject(CameraService); }); it('should be created', () => { 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/chat-user.service.ts b/src/app/services/chat/chat-user.service.ts deleted file mode 100644 index 7a8fd0a8d..000000000 --- a/src/app/services/chat/chat-user.service.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { Injectable } from '@angular/core'; - -@Injectable({ - providedIn: 'root' -}) -export class ChatUserService { - - constructor() { } -} diff --git a/src/app/services/chat/message.service.ts b/src/app/services/chat/message.service.ts index bde3ef601..976a81e21 100644 --- a/src/app/services/chat/message.service.ts +++ b/src/app/services/chat/message.service.ts @@ -1,8 +1,10 @@ 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' +import { NfService } from 'src/app/services/chat/nf.service' +import { WsChatService } from 'src/app/services/chat/ws-chat.service'; @Injectable({ providedIn: 'root' }) @@ -17,40 +19,105 @@ export class MessageService { u = {} t = '' _id ='' - _updatedAt = {} + _updatedAt file attachments + offline = true + displayType = '' + temporaryData: any = {} + hasFile = false + hasSendAttachment = false - constructor(private storage: Storage) { - } + constructor(private storage: Storage, + private NfService: NfService, + private WsChatService: WsChatService) { + } - 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 + setData({customFields, channels, mentions, msg ,rid ,ts, u, t, _id, _updatedAt, file, attachments, temporaryData}:Message) { + 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 + this.temporaryData = temporaryData + if(!this.ts) { + this.offline = true + } else { + this.offline = false + } if (this.file) { + if(this.file.type) { + 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) { + + const firstName = capitalizeTxt(username.split('.')[0]) + const lastName = capitalizeTxt(username.split('.')[1]) + return firstName + ' ' + lastName + } + + getFileFromDb() { + + if(this.hasFile) { if (this.file.guid) { this.storage.get(this.file.guid).then((image) => { - // console.log('IMAGE FROM STORAGE', image) - this.file.image_url = image + if(image != null) { + this.file.image_url = image + } }); } } } - delete() {} + 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') - showDateDuration() {} + 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.spec.ts b/src/app/services/chat/nf.service.spec.ts new file mode 100644 index 000000000..b8546cad7 --- /dev/null +++ b/src/app/services/chat/nf.service.spec.ts @@ -0,0 +1,16 @@ +import { TestBed } from '@angular/core/testing'; + +import { NfService } from './nf.service'; + +describe('NfService', () => { + let service: NfService; + + beforeEach(() => { + TestBed.configureTestingModule({}); + service = TestBed.inject(NfService); + }); + + it('should be created', () => { + expect(service).toBeTruthy(); + }); +}); diff --git a/src/app/services/chat/nf.service.ts b/src/app/services/chat/nf.service.ts new file mode 100644 index 000000000..7bfbd26be --- /dev/null +++ b/src/app/services/chat/nf.service.ts @@ -0,0 +1,14 @@ +import { Injectable } from '@angular/core'; +import { MessageService } from './message.service'; +import { RoomService } from './room.service'; + +@Injectable({ + providedIn: 'root' +}) +export class NfService { + + 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 42f80a4a2..c2a61a60a 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'; @@ -13,7 +12,10 @@ 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'; +import { ChatService } from 'src/app/services/chat.service'; +import { NfService } from 'src/app/services/chat/nf.service' +import alasql from 'alasql' @Injectable({ providedIn: 'root' }) @@ -22,8 +24,7 @@ export class RoomService { messages: MessageService[] = [] storageMessage: any[] = []; lastMessage: MessageService; - - chatUser: ChatUserService[] = [] + customFields: any; id = '' t = '' @@ -51,6 +52,9 @@ export class RoomService { return [] } + sortRoomList = () => {} + uploadAttachment = (formData) => {} + constructor( public WsChatService: WsChatService, private MessageService: MessageService, @@ -59,11 +63,13 @@ export class RoomService { private sqlservice: SqliteService, 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, this.WsChatService), _updatedAt }) { this.customFields = customFields this.id = id this.name = name @@ -74,6 +80,11 @@ export class RoomService { this.calDateDuration() } + + isSenderIsNotMe(ChatMessage) { + return SessionStore.user.RochetChatUser != ChatMessage.u.username + } + receiveMessage() { this.WsChatService.updateRoomEventss( @@ -81,40 +92,30 @@ export class RoomService { "stream-room-messages", (ChatMessage) => { ChatMessage = ChatMessage.fields.args[0] - ChatMessage = this.fix_updatedAt(ChatMessage) - console.log('recivemessage', ChatMessage) - const message = this.prepareMessage(ChatMessage) + if(environment.chatOffline == false || this.isSenderIsNotMe(ChatMessage)) { + + ChatMessage = this.fix_updatedAt(ChatMessage) + console.log('recivemessage', ChatMessage) + + const message = this.prepareMessage(ChatMessage) - if(message._updatedAt == undefined){ - message._updatedAt = new Date().getTime(); - } - - this.lastMessage = message - if (message.t == 'r') { this.name = message.msg } - this.calDateDuration(message._updatedAt) - this.messages.push(message) - - setTimeout(() => { - this.scrollDown() - }, 100) - - if(SessionStore.user.RochetChatUser != ChatMessage.u.username) { + this.lastMessage = message + if (message.t == 'r') { this.name = message.msg } + this.calDateDuration(ChatMessage._updatedAt) + + setTimeout(() => { + this.scrollDown() + }, 100) + 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) - }); - }) - } ) @@ -134,6 +135,16 @@ export class RoomService { this.WsChatService.registerCallback } + + addMessageDB(ChatMessage) { + this.storage.get('chatmsg' + this.id).then((messages: any = []) => { + delete ChatMessage.temporaryData + messages.push(ChatMessage) + + this.storage.set('chatmsg' + this.id, messages) + }) + } + async receiveMessageDelete() { this.WsChatService.updateRoomEventss( @@ -195,11 +206,73 @@ export class RoomService { /** * @description sen text message */ - send() { - this.WsChatService.send(this.id, this.message) + async send({file = null, attachments = null, temporaryData = {}}) { + + + let offlineChatMessage = { + rid: this.id, + msg: this.message, + attachments, + file, + temporaryData + } + + console.log('offlineChatMessage', offlineChatMessage) + + this.addMessageDB(offlineChatMessage) + const message: MessageService = this.prepareMessage(offlineChatMessage) + + setTimeout(() => { + this.scrollDown() + }, 150) + + 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') + + const result = await this.NfService.beforeSendAttachment(message, this) + + + 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.calDateDuration(message._updatedAt) + this.sortRoomList() + this.message= '' } + 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() + } + typing(text:string = this.message) { @@ -267,42 +340,58 @@ export class RoomService { } + async restoreMessageFromDB() { + await this.storage.get('chatmsg' + this.id).then( async (messages = []) => { + + if(messages==null) messages = [] + + 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) + // }) + } + + }); + + 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.storage.get('chatmsg' + this.id).then((messages = []) => { + await this.restoreMessageFromDB() - let localMessages = [] - - messages.forEach(message => { - const wewMessage = this.prepareMessage(message) - localMessages.push(wewMessage) - }); - - this.messages = localMessages - }) - - 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(() => { @@ -314,11 +403,12 @@ export class RoomService { - prepareMessage(message) { + prepareMessage(message): MessageService { message = this.fix_updatedAt(message) - const wewMessage = new MessageService(this.storage) + const wewMessage = new MessageService(this.storage, this.NfService, this.WsChatService) wewMessage.setData(message) - + this.messages.push(wewMessage) + return wewMessage } @@ -344,9 +434,11 @@ export class RoomService { if (message.result) { //console.log('FIX UPDATE ', message.result) message.result._updatedAt = message.result._updatedAt['$date'] - } else { - //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 7e458ed1f..6ea061412 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(); @@ -68,6 +69,13 @@ export class WsChatMethodsService { } + getRoomFromDb() { + this.storage.get('Rooms').then((rooms) => { + rooms.result.update.forEach((roomData: room) => { + this.prepareRoom(roomData); + }); + }) + }; openRoom(roomId) { if(this.currentRoom) { @@ -92,9 +100,12 @@ export class WsChatMethodsService { async getAllRooms () { this.loadingWholeList = true - + //this.getRoomFromDb(); const rooms = await this.WsChatService.getRooms(); + await this.storage.remove('Rooms'); + await this.storage.set('Rooms', rooms); + // console.log("ROOMS" + JSON.stringify(rooms)) this.WsChatService.registerCallback({ type:'Onmessage', funx:(message)=>{ @@ -131,7 +142,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() } @@ -193,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) + 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, @@ -207,6 +218,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 61cf2096f..593b79276 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 @@ -30,8 +38,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 +73,7 @@ export class WsChatService { } ] } - this.ws.send({message, requestId, loginRequired: false}) + this.ws.send({message, requestId: 'login', loginRequired: false}) return new Promise((resolve, reject) => { @@ -154,7 +162,7 @@ export class WsChatService { } // send message to room - send(roomId, msg) { + send({roomId, msg, attachments = null, file = null}) { const requestId = uuidv4() @@ -163,9 +171,10 @@ export class WsChatService { method: "sendMessage", id: requestId, params: [{ - _id: uuidv4(), rid: roomId, - msg: msg + msg: msg, + attachments, + file }] } @@ -173,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 } @@ -198,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 } @@ -224,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 } @@ -247,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 } @@ -302,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 } @@ -329,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 } @@ -409,7 +418,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)=>{ @@ -557,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 } @@ -584,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 } @@ -662,7 +671,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/app/services/functions/file.service.ts b/src/app/services/functions/file.service.ts index d696224de..2554b51d6 100644 --- a/src/app/services/functions/file.service.ts +++ b/src/app/services/functions/file.service.ts @@ -1,21 +1,13 @@ 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 { 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 { LoadingController, Platform } from '@ionic/angular'; +import {Photo} from '@capacitor/camera'; +import { FileType } from 'src/app/models/fileType'; 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'; -const IMAGE_DIR = 'stored-images'; +import { FileToBase64Service } from 'src/app/services/file/file-to-base64.service'; +const IMAGE_DIR = 'stored-images'; interface LocalFile { name: string; @@ -31,111 +23,24 @@ 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; + convertBlobToBase64Worker; constructor( private fileLoaderService: FileLoaderService, - private fileToBase64Service: FileToBase64Service, private iab: InAppBrowser, - private chatService: ChatService, - 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 platform: Platform, + private fileToBase64Service: FileToBase64Service + ) {} - 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 = ''; - 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 ); -} - - - 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; @@ -146,31 +51,9 @@ 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; - }; - } - - //new method1 - async saveImage(photo: Photo, roomid: any) { + async saveImage(photo: Photo) { const base64Data = await this.readAsBase64(photo); const fileName = new Date().getTime() + '.jpeg'; @@ -180,9 +63,42 @@ export class FileService { directory: Directory.Data }); - this.loadFiles(roomid); } + //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')) { @@ -201,345 +117,61 @@ export class FileService { } } - //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, + async readFile(filePath) { + return await Filesystem.readFile({ + path: filePath, 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) { + async loadFileData(fileName: string) { 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, - }); + const readFile = await this.readFile(filePath) - this.images.push({ + const image ={ name: fileName, path: filePath, data: `data:image/jpeg;base64,${readFile.data}`, - }); + }; - console.log('ALL IMAGE', this.images) + console.log('ALL IMAGE', image) - this.capturedImage = this.images[0].data + const capturedImage = image.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); + const capturedImageTitle = new Date().getTime() + '.jpeg'; - 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; - + return { capturedImage, capturedImageTitle} } - async addPictureToChatMobile(roomId) { - - const capturedImage = await Camera.getPhoto({ - quality: 50, - // allowEditing: true, - resultType: CameraResultType.Uri, - source: CameraSource.Photos - - }); - - if (capturedImage) { - await this.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) { + getFileFromDevice(types: typeof FileType[]) { const input = this.fileLoaderService.createInput({ - accept: ['.doc', '.docx', '.pdf'] + accept: types }) - input.onchange = async () => { - const loader = this.toastService.loading(); - const file = this.fileLoaderService.getFirstFile(input) + return new Promise((resolve, reject)=>{ + input.onchange = async () => { + const file = this.fileLoaderService.getFirstFile(input) - console.log(file); + resolve(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) - }; } - 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(); - } - }); - } viewDocumentByUrl(url) { const browser = this.iab.create(url,"_parent"); browser.show(); } + } 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/services/sqlite.service.ts b/src/app/services/sqlite.service.ts index 37638c4c0..1cf19d6e6 100644 --- a/src/app/services/sqlite.service.ts +++ b/src/app/services/sqlite.service.ts @@ -127,7 +127,8 @@ export class SqliteService { DateEnd varchar(255), Detail varchar(255), Description varchar(255), - publications Text + publications Text, + publicationsDetails Text )`, []) .then((res) => { console.log("Sucess action Table created: ", res) @@ -195,8 +196,8 @@ export class SqliteService { public addactions(data) { console.log('Action insert', data) this.dbInstance.executeSql(` - INSERT OR IGNORE INTO ${this.actions} (ActionType,DateBegin,DateEnd,Description,Detail,ProcessId,publications) - VALUES ('${data.ActionType}','${data.DateBegin}', '${data.DateEnd}','${data.Description}','${data.Detail}','${data.ProcessId}','${data.publications}')`, []) + INSERT OR IGNORE INTO ${this.actions} (ActionType,DateBegin,DateEnd,Description,Detail,ProcessId,publications,publicationsDetails) + VALUES ('${data.ActionType}','${data.DateBegin}', '${data.DateEnd}','${data.Description}','${data.Detail}','${data.ProcessId}','${data.publications}','${data.publicationsDetails}')`, []) .then(() => { console.log("action add with Success"); @@ -319,6 +320,22 @@ export class SqliteService { } + //updatePublicationsDetails + public updatePublicationsDetails(id, data) { + try { + console.log("update action data", data) + this.dbInstance.executeSql(` + UPDATE ${this.actions} SET publicationsDetails = ? WHERE ProcessId = ${id}`, [data]) + .then(() => { + console.log("action update with Success"); + + }, (e) => { + console.log(JSON.stringify(e.err)); + }); + } catch(error) {} + + } + //updateChatMsg public updateChatMsg(id, data) { let jsonId = JSON.stringify(id) 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..99162985b 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
@@ -97,7 +97,7 @@ {{file.description}} - {{msg.file.type.replace('application/','').toUpperCase()}} + {{msg.displayType}}
@@ -222,7 +222,7 @@ - + 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..7be23ce8a 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 { 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 CameraService: CameraService, + private toastService: ToastService, ) { console.log('OnCONSTRUCTOR'); @@ -129,7 +139,6 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe setTimeout(() => { this.getRoomInfo(); }, 1000); - this.setStatus('online'); this.getChatMembers(); //this.getMessageDB(); @@ -216,7 +225,6 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe } ngOnDestroy() { - this.setStatus('away'); window.removeEventListener('scroll', this.scrollChangeCallback, true); } @@ -297,17 +305,8 @@ 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() + this.wsChatMethodsService.getGroupRoom(this.roomId).send({}) } deleteMessage(msgId: string, room:any) { @@ -388,10 +387,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(); }; }); @@ -423,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(); }; @@ -464,89 +458,9 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe modal.onDidDismiss().then(() => { //this.getRoomInfo(); - this.loadGroupMessages(this.roomId) }); } - 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({ @@ -563,36 +477,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() } }); } @@ -656,18 +542,119 @@ 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.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); + + this.wsChatMethodsService.getDmRoom(roomId).send({ + file: { + "type": "application/img", + "guid": '', + "image_url": capturedImage + }, + attachments: [{ + "title": capturedImageTitle , + "image_url": capturedImage, + "text": "description", + "title_link_download": false, + }], + temporaryData: formData + }) + } - 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 roomId = this.roomId + + 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.wsChatMethodsService.getDmRoom(roomId).send({ + 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", + //"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(); + + } + }); } + + + + async addFileToChat(types: typeof FileType[] ) { + const roomId = this.roomId + + const file: any = await this.fileService.getFileFromDevice(types); + const imageData = await this.fileToBase64Service.convert(file) + + const formData = new FormData(); + formData.append("blobFile", file); + + this.wsChatMethodsService.getDmRoom(roomId).send({ + file: { + "type": "application/img", + "guid": '', + "image_url": imageData + }, + temporaryData: formData, + attachments: [{ + "title": file.name , + "image_url": imageData, + "text": "description", + "title_link_download": false, + }] + }) + } + bookMeeting() { let data = { roomId: this.roomId, @@ -693,7 +680,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 +698,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,73 +712,36 @@ 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(); + + this.takePicture() + } 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); }); } - 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 = ""; 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.html b/src/app/shared/chat/messages/messages.page.html index 37c723586..16c0804e9 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 @@