This commit is contained in:
Peter Maquiran
2024-02-23 12:39:59 +01:00
29 changed files with 1742 additions and 877 deletions
+425 -21
View File
@@ -1,46 +1,450 @@
import { Injectable } from '@angular/core';
import * as signalR from "@microsoft/signalr"
import { SessionStore } from '../store/session.service';
import { v4 as uuidv4 } from 'uuid'
import { HttpClient, HttpHeaders, HttpEventType } from '@angular/common/http';
import { CMAPIService } from '../shared/repository/CMAPI/cmapi.service';
import { HubConnectionBuilder } from '@microsoft/signalr';
import { ok, err, Result } from 'neverthrow';
@Injectable({
providedIn: 'root'
})
export class SocketConnectionMCRService {
// private callbacks: Function[] = []
// private onDisconnect: Function[] = []
// private onConnect: Function[] = []
constructor() { }
constructor(private http: HttpClient, private _CMAPIService: CMAPIService) {
window["http"] = this.http
}
// connect() {
// var connection = new signalR.HubConnectionBuilder()
// .withUrl("https://gdcmapi-dev.dyndns.info/FileHub", {
// accessTokenFactory: () => "Bearer "+SessionStore.user.Authorization
// }).configureLogging(signalR.LogLevel.Information)
// .build();
// connection.on("ReceiveMessage", (message) => {
// console.log("ReceiveMessage", message)
// })
// connection.onreconnected((connectionId) => {
// console.assert(connection.state === signalR.HubConnectionState.Connected);
// console.log(`Reconnected with connectionId: ${connectionId}`);
// });
// connection.start()
// .then(() => {
// console.log("SignalR connection started.");
// })
// .catch((error) => {
// console.error("Error starting SignalR connection:", error);
// });
// connection.onclose((error) => {
// connection.start()
// console.log("SignalR connection closed:", error);
// });
// }
// subscribe(callback) {
// this.callbacks.push(callback);
// }
// unsubscribe(callback) {
// this.callbacks = this.callbacks.filter(cb => cb !== callback);
// }
// onDisconnectCallback(callback) {
// this.onDisconnect.push(callback)
// }
// onConnectCallback(callback) {
// this.onConnect.push(callback)
// }
}
class ReconnectingWebSocketSignalR {
private connection: any
isOpen: boolean = false
private callbacks: Function[] = []
private onDisconnect: Function[] = []
private onConnect: Function[] = []
private whenConnected: Function[] = []
stop = true
constructor() {}
connect() {
console.log("try to connect=================================")
this.stop = false
var connection = new signalR.HubConnectionBuilder()
this.connection = new signalR.HubConnectionBuilder()
.withUrl("https://gdcmapi-dev.dyndns.info/FileHub", {
accessTokenFactory: () => SessionStore.user.Authorization
transport: signalR.HttpTransportType.LongPolling,
accessTokenFactory: () => SessionStore.user.Authorization
}).configureLogging(signalR.LogLevel.Information)
.build();
connection.on("ReceiveMessage", (message) => {
console.log("ReceiveMessage", message)
})
connection.onreconnected((connectionId) => {
console.assert(connection.state === signalR.HubConnectionState.Connected);
console.log(`Reconnected with connectionId: ${connectionId}`);
});
connection.start()
this.connection.start()
.then(() => {
console.log("SignalR connection started.");
this.isOpen = true;
console.log('WebSocket connection established');
this.onConnect.forEach(callback => callback());
this.whenConnected.forEach(callback => callback())
})
.catch((error) => {
console.error("Error starting SignalR connection:", error);
console.error("Error starting SignalR connection:", error);
});
connection.onclose((error) => {
connection.start()
console.log("SignalR connection closed:", error);
});
this.connection.on("ReceiveMessage", (message) => {
const data: any = JSON.parse(message)
console.log("ReceiveMessage", data)
this.callbacks.forEach(callback => callback(data));
})
this.connection.onclose((error) => {
console.log('WebSocket connection closed..');
this.isOpen = false;
this.onDisconnect.forEach(callback => callback());
// Attempt to reconnect after a delay
if(this.stop == false) {
setTimeout(() => {
this.connect();
}, 1000); // Adjust the delay as needed
}
});
}
commit(path): Promise<Result<true, false>> {
return new Promise((resolve, reject) => {
this.connection.invoke("CommitUpload", path).then((e) => {
console.log("commit message", e)
resolve(ok(true))
}).catch(err => {
resolve(err(false))
console.error(err.toString())
});
})
}
disconnect() {
this.stop = true
if(this.isOpen == true) {
this.connection.stop()
.then(() => {
console.log('WebSocket connection was closed by client');
this.isOpen = false;
this.onDisconnect.forEach(callback => callback());
console.log("SignalR connection stopped.");
})
.catch((error) => {
console.error("Error stopping SignalR connection by client:", error);
});
}
}
subscribe(callback) {
this.callbacks.push(callback);
}
unsubscribe(callback) {
this.callbacks = this.callbacks.filter(cb => cb !== callback);
}
onDisconnectCallback(callback) {
this.onDisconnect.push(callback)
}
onConnectCallback(callback) {
this.onConnect.push(callback)
}
registerWhenConnected(f: Function) {
if(this.isOpen) {
f();
} else {
this.whenConnected.push(f);
}
}
}
interface socketResponse {
index: string
Guid: string
IsCompleted: Boolean
}
// class ReconnectingWebSocket {
// private url: string
// private socket
// isOpen: boolean
// private callbacks: Function[] = []
// private onDisconnect: Function[] = []
// private onConnect: Function[] = []
// private whenConnected: Function[] = []
// private stop = true
// http: HttpClient = window["http"]
// constructor(url) {
// this.url = url;
// this.socket = null;
// this.isOpen = false;
// }
// connect() {
// this.socket = new WebSocket(this.url);
// this.socket.addEventListener('open', (event) => {
// this.isOpen = true;
// console.log('WebSocket connection established');
// // Example: Send a message to the server
// this.socket.send('Hello, WebSocket Server!');
// this.onConnect.forEach(callback => callback());
// this.whenConnected.forEach(callback => callback())
// });
// this.socket.addEventListener('message', (event) => {
// const data: socketResponse = JSON.parse(event.data)
// this.callbacks.forEach(callback => callback(data));
// });
// this.socket.addEventListener('close', (event) => {
// console.log('WebSocket connection closed');
// this.isOpen = false;
// this.onDisconnect.forEach(callback => callback());
// // Attempt to reconnect after a delay
// if(this.stop == false) {
// setTimeout(() => {
// this.connect();
// }, 1000); // Adjust the delay as needed
// }
// });
// }
// send(message) {
// if (this.isOpen) {
// this.socket.send(message);
// } else {
// console.error('WebSocket connection is not open. Unable to send message.');
// }
// }
// disconnect() {
// this.stop = true
// if (this.isOpen) {
// this.isOpen = false;
// this.socket.close();
// }
// }
// subscribe(callback) {
// this.callbacks.push(callback);
// }
// unsubscribe(callback) {
// this.callbacks = this.callbacks.filter(cb => cb !== callback);
// }
// onDisconnectCallback(callback) {
// this.onDisconnect.push(callback)
// }
// onConnectCallback(callback) {
// this.onConnect.push(callback)
// }
// registerWhenConnected(f: Function) {
// if(this.isOpen) {
// f();
// } else {
// this.whenConnected.push(f);
// }
// }
// }
// export class ObjectMergeNotification{
// socket = new ReconnectingWebSocket('ws://localhost:3002');
// callbacks: {[GUID: string]: Function} = {}
// runWatch = true
// CMAPIService: CMAPIService = window["CMAPIAPIRepository"]
// watchCount = 0
// constructor() {
// this.socket.onDisconnectCallback(()=> {
// console.log("run watch")
// this.runWatch = true
// this.watch()
// })
// this.socket.onConnectCallback(()=> {
// console.log("open trigger")
// this.runWatch = false
// })
// this.socket.subscribe((data: socketResponse) => {
// if(data.IsCompleted == true) {
// console.log("==================!!!====================")
// try {
// this.callbacks[data.Guid](data)
// delete this.callbacks[data.Guid]
// } catch (error) {}
// } else {
// console.log("else", data)
// }
// })
// this.watch()
// }
// connect() {
// this.socket.connect()
// }
// async watch() {
// this.watchCount = 0;
// if(this.runWatch) {
// setTimeout(async () => {
// for(const [key, funx] of Object.entries(this.callbacks)) {
// const request = await this.CMAPIService.getVideoHeader(key)
// if(request.isOk()) {
// funx()
// delete this.callbacks[key]
// }
// }
// this.watchCount++
// if(this.watchCount <= 15) {
// this.watch()
// } else {
// this.runWatch = false
// }
// }, 1000)
// } else {
// console.log("end loop============================")
// }
// }
// close() {
// this.socket.disconnect();
// this.watchCount = 0;
// this.runWatch = false
// }
// subscribe(GUID, callback:Function) {
// this.callbacks[GUID] = callback;
// }
// unsubscribe(GUID) {
// delete this.callbacks[GUID]
// }
// }
export class ObjectMergeNotification{
socket = new ReconnectingWebSocketSignalR()
callbacks: {[GUID: string]: Function} = {}
runWatch = true
CMAPIService: CMAPIService = window["CMAPIAPIRepository"]
watchCount = 0
constructor() {
this.socket.onDisconnectCallback(()=> {
console.log("run watch")
this.runWatch = true
this.watch()
})
this.socket.onConnectCallback(()=> {
console.log("open trigger")
this.runWatch = false
})
this.socket.subscribe((data: socketResponse) => {
if(data.IsCompleted == true) {
console.log("==================!!!====================")
try {
this.callbacks[data.Guid](data)
delete this.callbacks[data.Guid]
} catch (error) {}
} else {
console.log("else", data)
}
})
this.socket.connect();
this.watch()
}
connect() {
this.socket.connect();
}
close() {
this.socket.disconnect();
this.watchCount = 0;
this.runWatch = false
}
async watch() {
// this.watchCount = 0;
// if(this.runWatch) {
// setTimeout(async () => {
// for(const [key, funx] of Object.entries(this.callbacks)) {
// const request = await this.CMAPIService.getVideoHeader(key)
// if(request.isOk()) {
// funx()
// delete this.callbacks[key]
// }
// }
// this.watchCount++
// if(this.watchCount <= 15) {
// this.watch()
// } else {
// this.runWatch = false
// }
// }, 1000)
// } else {
// console.log("end loop============================")
// }
}
subscribe(GUID, callback:Function) {
this.callbacks[GUID] = callback;
}
unsubscribe(GUID) {
delete this.callbacks[GUID]
}
}
-91
View File
@@ -12,97 +12,6 @@ export class StreamService {
window["StreamService"] = this
}
async uploadFile() {
const API_URL = 'http://localhost:3000/upload'; // Replace with your server URL
const filePath = 'path/to/large-file.zip'; // Replace with the path to your file
const fileName = 'my-file'; // Specify your desired filename
const fileExtension = 'zip'; // Specify the file extension
const headers = new HttpHeaders()
.append('X-File-Name', fileName)
.append('X-File-Extension', fileExtension);
const file = await this.readFileInChunks(filePath);
const chunkSize = 1024 * 1024; // 1 MB chunk size (adjust as needed)
for (let offset = 0; offset < file.length; offset += chunkSize) {
const chunk = file.slice(offset, offset + chunkSize);
// await this.uploadChunk(API_URL, chunk, headers);
}
console.log('Upload completed.');
}
async readFileInChunks(filePath: string): Promise<Uint8Array> {
const response = await fetch(filePath);
const reader = response.body.getReader();
const chunks: Uint8Array[] = [];
let done = false;
while (!done) {
const { value, done: isDone } = await reader.read();
if (!isDone) {
chunks.push(value);
}
done = isDone;
}
return new Uint8Array([].concat(...chunks.map((chunk) => Array.from(chunk))));
}
async uploadChunk(url: string, chunks: Uint8Array[], fileName, fileExtension): Promise<void> {
let i = 1
console.log('123', chunks.length)
for(const chunk of chunks) {
try {
console.log("iterate")
const headers = new HttpHeaders()
.append('X-File-Name', fileName)
.append('X-File-Extension', fileExtension)
.append('X-File-Content-Length', chunks.length.toString())
.append('X-File-Index', i.toString())
await this.http.post('http://localhost:3001/upload', chunk.buffer, { headers, responseType: 'blob' }).toPromise();
i++
} catch (error) {
console.error('Upload error:', error);
}
}
}
async uploadChunkNoLoop(url: string, chunk: Uint8Array, fileName, fileExtension, i, length): Promise<void> {
console.log("iterate")
const headers = new HttpHeaders()
.append('X-File-Name', fileName)
.append('X-File-Extension', fileExtension)
.append('X-File-Content-Length', length)
.append('X-File-Index', i.toString())
await this.http.post('http://localhost:3001/upload', chunk.buffer, { headers, responseType: 'blob' }).toPromise();
}
uploadChunk1(chunk: Blob, chunkNumber: number, totalChunks: number, filename: string) {
console.log(chunk)
const headers = new HttpHeaders()
.append('X-File-Name', filename)
.append('X-File-Content-Length', totalChunks.toString())
.append('X-File-Index', chunkNumber.toString())
return this.http.post('http://localhost:3001/upload-chunk', Blob, { headers, responseType: 'blob' });
}
}
// const text = 'Hello, World00120301010asdf1002sdf 0fsdfasf0001230 12300!\n';