File size: 5,376 Bytes
b39afbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
/**
 * Copyright (c) 2023 MERCENARIES.AI PTE. LTD.
 * All rights reserved.
 */

import CustomSocket from './CustomSocket';
import { type WorkerContext } from '../openapi/types';
import { type Socket } from 'rete';
interface ICdnResource {
  ticket: { fid: string; url: string; publicUrl: string; count?: number };
  fileName: string;
  size: number;
  data?: any;
  url: string;
  furl: string;
  expires?: number;
  mimeType?: string;
  fileType?: string;
  meta: {
    type?: string;
    dimensions?: { width: number; height: number };
    created?: number;
    creator?: string;
  };
}

class FileObjectSocket extends CustomSocket {
  override compatibleWith(socket: Socket, noReverse: boolean): boolean {
    const cs: Partial<CustomSocket> = this;

    if (cs.type) {
      return ['string', 'image', 'audio', 'document', 'file'].includes(cs.type);
    } else {
      return socket instanceof FileObjectSocket;
    }
  }

  detectMimeType(ctx: WorkerContext, value: any): string | undefined {
    return undefined;
  }

  async persistObject(ctx: WorkerContext, value: any, opts?: any): Promise<ICdnResource> {
    if ((value.ticket || value.fid) && value.url && !value.data) {
      // If we don't have data, it means we are already persisted
      return await Promise.resolve(value);
    }

    opts ??= {};
    opts.mimeType ??= this.detectMimeType?.(ctx, value);

    const finalOpts = { userId: ctx.userId, jobId: ctx.jobId, ...opts };
    return ctx.app.cdn.putTemp(value, finalOpts) as ICdnResource;
  }

  async persistObjects(ctx: WorkerContext, value: any, opts?: any): Promise<ICdnResource[]> {
    return await Promise.all(
      value.map(async (v: any) => {
        return await this.persistObject(ctx, v, opts);
      })
    );
  }

  protected async _inputFromString(ctx: WorkerContext, value: any): Promise<ICdnResource[]> {
    if (typeof value !== 'string') {
      return value;
    }

    const objects = value.split('\n');
    const ret = objects.map((x) => x.trim()).filter((x) => x.length);
    return await Promise.all(
      ret.map(async (v: string) => {
        return await this.persistObject(ctx, v);
      })
    );
  }

  private async _handleSingleObject(
    ctx: WorkerContext,
    value: any,
    getValue: boolean = false
  ): Promise<ICdnResource | string | null> {
    if (!value) {
      return null;
    }
 
    let cdnResource = null
    const format = this.format?.includes('base64') ? 'base64' : undefined
    const addHeader = format && this.format?.includes('withHeader')

    // Case 1: We have an object with a fid:
    if (value.fid)
    {
      // If it's base64, we always have to pull data to convert it
      if (!getValue  && format !== 'base64')
      {
        cdnResource = await ctx.app.cdn.find(value.fid)
      }
      else
      {
        cdnResource = await ctx.app.cdn.get(value, null, format)        
      }
    }
    else if (value instanceof Buffer)
    {
      cdnResource = await this.persistObject(ctx, value)      
    }
    else if (typeof value === 'string')
    {
      if ( this.isValidUrl(value))
      {
        cdnResource = await this.persistObject(ctx, value.trim());
      }
      else if (value?.startsWith?.('fid://'))
      {
        const [fid, extension] = value.split('://')[1].split('.');
        cdnResource = await ctx.app.cdn.get({ fid }, null, format);
      }
      else (value.length>0)
      {     
        cdnResource = await this.persistObject(ctx, value);      
      }
    }

    let socketValue = null
    
    if (cdnResource && cdnResource.fid)
    {
      if (format === "base64")
      {
        
        socketValue = cdnResource.asBase64(addHeader)       
      }
      else
      {
        socketValue = cdnResource
      }
    }
    else
    {
      console.error("File socket: Failure to process value", value)
    }
    

    // wipe data if needed
    if (socketValue !== null && this.customSettings?.do_no_return_data  && format !== 'base64') {
      delete socketValue.data;
    } 

    return socketValue 
  }

  private async _handleObjectArray(
    ctx: WorkerContext,
    value: any[],
    getValue: boolean = false
  ): Promise<ICdnResource[] | null> {
    if (!value) {
      return null;
    }

    if (!Array.isArray(value)) {
      value = [value];
    }

    value = value.filter((x) => x !== null);

    return (await Promise.all(
      value.map(async (v: any) => {
        return await this._handleSingleObject(ctx, v, getValue);
      })
    )) as ICdnResource[];
  }

  async _handlePort(
    ctx: WorkerContext,
    value: any,
    getValue: boolean
  ): Promise<ICdnResource[] | ICdnResource | string | null> {
    value = await this._inputFromString(ctx, value);

    if (!Array.isArray(value)) {
      value = [value];
    }

    if (this.array) {
      return await this._handleObjectArray(ctx, value, getValue);
    }
    return await this._handleSingleObject(ctx, value[0], getValue);
  }

  async handleInput(ctx: WorkerContext, value: any): Promise<ICdnResource[] | ICdnResource | string | null> {
    return await this._handlePort(ctx, value, true);
  }

  async handleOutput(ctx: WorkerContext, value: any): Promise<ICdnResource[] | ICdnResource | string | null> {
    // Don't get data on output, any input port will get data as needed
    return await this._handlePort(ctx, value, false);
  }
}

export default FileObjectSocket;