View difference between Paste ID: Mub9zSWQ and Gt0LUrHB
SHOW: | | - or go back to the newest paste.
1
import {Injectable} from "@angular/core";
2
import {Storage} from '@ionic/storage';
3
import Socket = SocketIOClient.Socket;
4
import {Observable, ReplaySubject} from "rxjs";
5
import * as io from 'socket.io-client';
6
7
@Injectable()
8
export class SocketService {
9
  public socket: Socket;
10
  private connected: Promise<boolean>;
11
  private asyncSocket = new AsyncSocket();
12
13
  constructor(public storage: Storage) {
14
    this.reconnect();
15
  }
16
17
// Waits for successful socket connection, gets the token out of local storage and then authenticates the user with the server
18
  authenticate() {
19
    console.log('%cBeginning socket authentication', 'color: grey');
20
    this.storage.get('token').then(token => {
21
      console.log('%cToken was returned: ', 'color: grey', token);
22
      if (token) {
23
        this.connected.then(() => {
24
          console.log('%cSocket connection established', 'color: grey');
25
          this.socket
26
            .emit('authenticate', {token: token})
27
            .once('authenticated', () => {
28
              console.log('%cSocket auth successful', 'color:green; font-size:larger; font-weight: 700');
29
              this.asyncSocket.connect(this.socket);
30
              this.socket.emit('app:init', {});
31
            })
32
            .once('unauthorized', function (msg) {
33
              console.error('Socket auth failed: ', msg);
34
            });
35
          console.log('%cEmitted socket authentication', 'color: grey');
36
        });
37
      } else {
38
        console.warn('No token found');
39
      }
40
    });
41
  }
42
43
  observe(event: string): Observable<any> {
44
    console.debug('SocketService.observe(', event,')');
45
    return Observable.bindCallback((event: string, f) => this.asyncSocket.on(event, f))(event);
46
  }
47
48
  observeOnce(event: string): Observable<any> {
49
    return Observable.bindCallback((event: string, f) => this.asyncSocket.once(event, f))(event);
50
  }
51
52
  emit(event: string, payload: any = {}) {
53
    this.asyncSocket.emit(event, payload);
54
  }
55
56
  emitOnce(event: string, payload: any = {}) {
57
    this.emit(event, payload);
58
    return this.observeOnce(event);
59
  }
60
61
  // Will connect the socket and resolve the internal promise once successful
62
  reconnect() {
63
    console.log('%cStarting socket reconnect', 'color: grey');
64
    this.connected = new Promise(resolve => {
65-
      this.socket = io('https://app.getflip.de:3010', {
65+
      this.socket = io('https://example.com', {
66
        forceNew: true,
67
        secure: true,
68
        reconnectionDelay: 500,
69
        reconnectionDelayMax: 2000
70
      });
71
      this.socket.once('connect', () => {
72
        resolve(true);
73
        console.log('%cResolving socket connection promise', 'color: grey');
74
      });
75
    });
76
  }
77
}
78
79
class AsyncSocket {
80
  private onCalls = new ReplaySubject<{event: string, f: Function}>();
81
  private onceCalls = new ReplaySubject<{event: string, f: Function}>();
82
  private emits = new ReplaySubject<{event: string, payload: any}>();
83
  private socket: Socket;
84
85
  on(event: string, f: any) {
86
    console.debug('Queueing on for: ', event, f);
87
    this.onCalls.next({event: event, f: f});
88
  }
89
90
  once(event: string, f: any) {
91
    console.debug('Queueing once for: ', event, f);
92
    this.onceCalls.next({event: event, f: f});
93
  }
94
95
  emit(event: string, payload: any) {
96
    console.debug('Queueing emit for: ', event, payload);
97
    this.emits.next({event: event, payload: payload});
98
  }
99
100
  connect(socket: Socket) {
101
    console.log('%cConnecting queued socket things to actual socket', 'color: grey');
102
    this.socket = socket;
103
    this.socket.on('likePost', (res => console.info(res)));
104
    this.onCalls.do(call => console.debug('Calling on for ', call)).subscribe(call => this.socket.on(call.event, call.f));
105
    this.onceCalls.do(call => console.debug('Calling once for ', call)).subscribe(call => this.socket.once(call.event, call.f));
106
    this.emits.do(call => console.debug('Calling emit for ', call)).subscribe(call => this.socket.emit(call.event, call.payload));
107
  }
108
}