Mythus commited on
Commit
35ee763
·
1 Parent(s): a88af99

Upload 225 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +2 -0
  2. .github/FUNDING.yml +12 -0
  3. .github/ISSUE_TEMPLATE/bug_report.md +38 -0
  4. .github/ISSUE_TEMPLATE/feature_request.md +20 -0
  5. .github/workflows/build-prod.yml +491 -0
  6. .github/workflows/build-staging.yml +55 -0
  7. .gitignore +15 -0
  8. Dockerfile +18 -0
  9. LICENSE.md +674 -0
  10. Procfile +3 -0
  11. README.md +66 -10
  12. android/Icons/logoteledriveblack-onblue.png +0 -0
  13. android/Icons/logoteledriveblack-ongradientblack.png +0 -0
  14. android/Icons/logoteledriveblue-onblack.png +0 -0
  15. android/Icons/logoteledrivewhite-onblack.png +0 -0
  16. android/Icons/logoteledrivewhite-onblue.png.png +0 -0
  17. android/Icons/logoteledrivewhite-ongradientblueblack.png +0 -0
  18. android/Teledrive-Expo/.gitignore +14 -0
  19. android/Teledrive-Expo/App.js +21 -0
  20. android/Teledrive-Expo/app.json +34 -0
  21. android/Teledrive-Expo/assets/adaptive-icon.png +0 -0
  22. android/Teledrive-Expo/assets/favicon.png +0 -0
  23. android/Teledrive-Expo/assets/icon.png +0 -0
  24. android/Teledrive-Expo/assets/splash.png +0 -0
  25. android/Teledrive-Expo/babel.config.js +6 -0
  26. android/Teledrive-Expo/eas.json +20 -0
  27. android/Teledrive-Expo/package.json +26 -0
  28. android/Teledrive-Expo/yarn.lock +0 -0
  29. android/todolist.txt +5 -0
  30. api/.env-example +12 -0
  31. api/.eslintignore +5 -0
  32. api/.eslintrc.js +95 -0
  33. api/.gitignore +4 -0
  34. api/package.json +90 -0
  35. api/prisma/migrations/20220420012853_init/migration.sql +107 -0
  36. api/prisma/migrations/20220525012308_add_password_files/migration.sql +2 -0
  37. api/prisma/migrations/migration_lock.toml +3 -0
  38. api/prisma/schema.prisma +87 -0
  39. api/src/Types.ts +11 -0
  40. api/src/api/base/Endpoint.ts +151 -0
  41. api/src/api/index.ts +5 -0
  42. api/src/api/middlewares/Auth.ts +119 -0
  43. api/src/api/middlewares/Key.ts +10 -0
  44. api/src/api/middlewares/TGClient.ts +15 -0
  45. api/src/api/middlewares/TGSessionAuth.ts +32 -0
  46. api/src/api/v1/Auth.ts +468 -0
  47. api/src/api/v1/Config.ts +93 -0
  48. api/src/api/v1/Dialogs.ts +92 -0
  49. api/src/api/v1/Files.ts +1360 -0
  50. api/src/api/v1/Messages.ts +324 -0
.gitattributes CHANGED
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ press/(EN)[[:space:]]Press[[:space:]]Release_[[:space:]]TeleDrive.pdf filter=lfs diff=lfs merge=lfs -text
37
+ press/(ID)[[:space:]]Press[[:space:]]Release_[[:space:]]TeleDrive.pdf filter=lfs diff=lfs merge=lfs -text
.github/FUNDING.yml ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # These are supported funding model platforms
2
+
3
+ github: mgilangjanuar
4
+ patreon: # Replace with a single Patreon username
5
+ open_collective: teledrive
6
+ ko_fi: # Replace with a single Ko-fi username
7
+ tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
8
+ community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
9
+ liberapay: # Replace with a single Liberapay username
10
+ issuehunt: # Replace with a single IssueHunt username
11
+ otechie: # Replace with a single Otechie username
12
+ custom: ['https://paypal.me/mgilangjanuar']
.github/ISSUE_TEMPLATE/bug_report.md ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: Bug report
3
+ about: Create a report to help us improve
4
+ title: ''
5
+ labels: bug
6
+ assignees: ''
7
+
8
+ ---
9
+
10
+ **Describe the bug**
11
+ A clear and concise description of what the bug is.
12
+
13
+ **To Reproduce**
14
+ Steps to reproduce the behavior:
15
+ 1. Go to '...'
16
+ 2. Click on '....'
17
+ 3. Scroll down to '....'
18
+ 4. See error
19
+
20
+ **Expected behavior**
21
+ A clear and concise description of what you expected to happen.
22
+
23
+ **Screenshots**
24
+ If applicable, add screenshots to help explain your problem.
25
+
26
+ **Desktop (please complete the following information):**
27
+ - OS: [e.g. iOS]
28
+ - Browser [e.g. chrome, safari]
29
+ - Version [e.g. 22]
30
+
31
+ **Smartphone (please complete the following information):**
32
+ - Device: [e.g. iPhone6]
33
+ - OS: [e.g. iOS8.1]
34
+ - Browser [e.g. stock browser, safari]
35
+ - Version [e.g. 22]
36
+
37
+ **Additional context**
38
+ Add any other context about the problem here.
.github/ISSUE_TEMPLATE/feature_request.md ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: Feature request
3
+ about: Suggest an idea for this project
4
+ title: ''
5
+ labels: enhancement
6
+ assignees: ''
7
+
8
+ ---
9
+
10
+ **Is your feature request related to a problem? Please describe.**
11
+ A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
12
+
13
+ **Describe the solution you'd like**
14
+ A clear and concise description of what you want to happen.
15
+
16
+ **Describe alternatives you've considered**
17
+ A clear and concise description of any alternative solutions or features you've considered.
18
+
19
+ **Additional context**
20
+ Add any other context or screenshots about the feature request here.
.github/workflows/build-prod.yml ADDED
@@ -0,0 +1,491 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ on:
2
+ push:
3
+ branches:
4
+ - main
5
+
6
+ name: Build Prod
7
+
8
+ env:
9
+ APP_DIR: /root/teledrive
10
+ DEV_USER: root
11
+ DEV_HOST_SG_1: 159.223.92.212
12
+ DEV_HOST_SG_2: 10.104.0.2
13
+ DEV_HOST_GE_1: 104.248.23.115
14
+ DEV_HOST_GE_2: 10.114.0.2
15
+ DEV_HOST_US_1: 159.223.111.175
16
+
17
+ jobs:
18
+ build:
19
+ name: Build
20
+ runs-on: ubuntu-latest
21
+
22
+ steps:
23
+ - uses: actions/checkout@v2
24
+ - name: Use Node.js
25
+ uses: actions/setup-node@v1
26
+ with:
27
+ node-version: '14.x'
28
+ - name: Add npmrc
29
+ run: echo -e "//npm.pkg.github.com/:_authToken=${NPM_AUTH_TOKEN}\n@mgilangjanuar:registry=https://npm.pkg.github.com/" > ~/.npmrc && cat ~/.npmrc
30
+ env:
31
+ NPM_AUTH_TOKEN: ${{ secrets.NPM_AUTH_TOKEN }}
32
+ - run: yarn install
33
+ - run: REACT_APP_TG_API_ID=${APP_ID} REACT_APP_TG_API_HASH=${APP_HASH} GENERATE_SOURCEMAP=false yarn workspaces run build
34
+ env:
35
+ APP_ID: ${{ secrets.TG_API_ID }}
36
+ APP_HASH: ${{ secrets.TG_API_HASH }}
37
+ - name: Compress node_modules root
38
+ if: ${{ github.event_name == 'push' }}
39
+ run: tar -czf build-root.tar.gz node_modules
40
+ - name: Archive build-root.tar.gz
41
+ uses: actions/upload-artifact@v2
42
+ with:
43
+ name: build-root
44
+ path: build-root.tar.gz
45
+ - name: Compress node_modules & dist server
46
+ if: ${{ github.event_name == 'push' }}
47
+ run: tar -czf build-server.tar.gz server/node_modules server/dist
48
+ - name: Archive build-server.tar.gz
49
+ uses: actions/upload-artifact@v2
50
+ with:
51
+ name: build-server
52
+ path: build-server.tar.gz
53
+ - name: Compress node_modules & build web
54
+ if: ${{ github.event_name == 'push' }}
55
+ run: tar -czf build-web.tar.gz web/node_modules web/build
56
+ - name: Archive build-web.tar.gz
57
+ uses: actions/upload-artifact@v2
58
+ with:
59
+ name: build-web
60
+ path: build-web.tar.gz
61
+
62
+ sg1:
63
+ name: Upload & Deploy to SG1
64
+ needs: build
65
+ runs-on: ubuntu-latest
66
+ steps:
67
+ - name: Download all workflow run artifacts
68
+ uses: actions/download-artifact@v2
69
+
70
+ - run: mv build-root/build-root.tar.gz . && mv build-server/build-server.tar.gz . && mv build-web/build-web.tar.gz .
71
+
72
+ # Upload to SG_1
73
+ - name: Upload build-root.tar.gz to sg_1
74
+ uses: appleboy/scp-action@master
75
+ with:
76
+ source: build-root.tar.gz
77
+ target: ${{ env.APP_DIR }}
78
+ host: ${{ env.DEV_HOST_SG_1 }}
79
+ username: ${{ env.DEV_USER }}
80
+ key: ${{ secrets.SSH_SECRET }}
81
+ debug: true
82
+ - name: Upload build-server.tar.gz to sg_1
83
+ uses: appleboy/scp-action@master
84
+ with:
85
+ source: build-server.tar.gz
86
+ target: ${{ env.APP_DIR }}
87
+ host: ${{ env.DEV_HOST_SG_1 }}
88
+ username: ${{ env.DEV_USER }}
89
+ key: ${{ secrets.SSH_SECRET }}
90
+ - name: Upload build-web.tar.gz to sg_1
91
+ uses: appleboy/scp-action@master
92
+ with:
93
+ source: build-web.tar.gz
94
+ target: ${{ env.APP_DIR }}
95
+ host: ${{ env.DEV_HOST_SG_1 }}
96
+ username: ${{ env.DEV_USER }}
97
+ key: ${{ secrets.SSH_SECRET }}
98
+
99
+ # Deployment SG_1
100
+ - name: Extract build-root.tar.gz to sg_1
101
+ uses: appleboy/ssh-action@master
102
+ with:
103
+ script: cd ${{ env.APP_DIR }} && rm -rf node_modules && tar -xzf build-root.tar.gz && rm -rf build-root.tar.gz
104
+ host: ${{ env.DEV_HOST_SG_1 }}
105
+ username: ${{ env.DEV_USER }}
106
+ key: ${{ secrets.SSH_SECRET }}
107
+ - name: Extract build-web.tar.gz to sg_1
108
+ if: ${{ github.event_name == 'push' }}
109
+ uses: appleboy/ssh-action@master
110
+ with:
111
+ script: cd ${{ env.APP_DIR }}/web && rm -rf node_modules && rm -rf build && cd .. && tar -xzf build-web.tar.gz && rm -rf build-web.tar.gz
112
+ host: ${{ env.DEV_HOST_SG_1 }}
113
+ username: ${{ env.DEV_USER }}
114
+ key: ${{ secrets.SSH_SECRET }}
115
+ - name: Extract build-server.tar.gz to sg_1
116
+ if: ${{ github.event_name == 'push' }}
117
+ uses: appleboy/ssh-action@master
118
+ with:
119
+ script: cd ${{ env.APP_DIR }}/server && rm -rf node_modules && rm -rf dist && cd .. && tar -xzf build-server.tar.gz && rm -rf build-server.tar.gz && git pull origin main --rebase && cd ${{ env.APP_DIR }} && /usr/local/bin/pm2 restart td
120
+ host: ${{ env.DEV_HOST_SG_1 }}
121
+ username: ${{ env.DEV_USER }}
122
+ key: ${{ secrets.SSH_SECRET }}
123
+
124
+ # Notification
125
+ - name: Success Notification
126
+ uses: appleboy/telegram-action@master
127
+ with:
128
+ to: -700697945
129
+ token: ${{ secrets.TG_BOT_TOKEN }}
130
+ message: 🎉 Deployed to SG_1
131
+ format: markdown
132
+ - name: Failed Notification
133
+ if: ${{ failure() }}
134
+ uses: appleboy/telegram-action@master
135
+ with:
136
+ to: -700697945
137
+ token: ${{ secrets.TG_BOT_TOKEN }}
138
+ message: 🔥 Deploy to SG_1 Failed!
139
+ format: markdown
140
+
141
+ sg2:
142
+ name: Upload & Deploy to SG2
143
+ needs: build
144
+ runs-on: ubuntu-latest
145
+ steps:
146
+ - name: Download all workflow run artifacts
147
+ uses: actions/download-artifact@v2
148
+
149
+ - run: mv build-root/build-root.tar.gz . && mv build-server/build-server.tar.gz . && mv build-web/build-web.tar.gz .
150
+
151
+ # Upload to SG_2
152
+ - name: Upload build-root.tar.gz to sg_2
153
+ uses: appleboy/scp-action@master
154
+ with:
155
+ source: build-root.tar.gz
156
+ target: ${{ env.APP_DIR }}
157
+ host: ${{ env.DEV_HOST_SG_2 }}
158
+ username: ${{ env.DEV_USER }}
159
+ key: ${{ secrets.SSH_SECRET }}
160
+ proxy_host: ${{ env.DEV_HOST_SG_1 }}
161
+ proxy_username: ${{ env.DEV_USER }}
162
+ proxy_key: ${{ secrets.SSH_SECRET }}
163
+ debug: true
164
+ - name: Upload build-server.tar.gz to sg_2
165
+ uses: appleboy/scp-action@master
166
+ with:
167
+ source: build-server.tar.gz
168
+ target: ${{ env.APP_DIR }}
169
+ host: ${{ env.DEV_HOST_SG_2 }}
170
+ username: ${{ env.DEV_USER }}
171
+ key: ${{ secrets.SSH_SECRET }}
172
+ proxy_host: ${{ env.DEV_HOST_SG_1 }}
173
+ proxy_username: ${{ env.DEV_USER }}
174
+ proxy_key: ${{ secrets.SSH_SECRET }}
175
+ - name: Upload build-web.tar.gz to sg_2
176
+ uses: appleboy/scp-action@master
177
+ with:
178
+ source: build-web.tar.gz
179
+ target: ${{ env.APP_DIR }}
180
+ host: ${{ env.DEV_HOST_SG_2 }}
181
+ username: ${{ env.DEV_USER }}
182
+ key: ${{ secrets.SSH_SECRET }}
183
+ proxy_host: ${{ env.DEV_HOST_SG_1 }}
184
+ proxy_username: ${{ env.DEV_USER }}
185
+ proxy_key: ${{ secrets.SSH_SECRET }}
186
+
187
+ # Deployment SG_2
188
+ - name: Extract build-root.tar.gz to sg_2
189
+ uses: appleboy/ssh-action@master
190
+ with:
191
+ script: cd ${{ env.APP_DIR }} && rm -rf node_modules && tar -xzf build-root.tar.gz && rm -rf build-root.tar.gz
192
+ host: ${{ env.DEV_HOST_SG_2 }}
193
+ username: ${{ env.DEV_USER }}
194
+ key: ${{ secrets.SSH_SECRET }}
195
+ proxy_host: ${{ env.DEV_HOST_SG_1 }}
196
+ proxy_username: ${{ env.DEV_USER }}
197
+ proxy_key: ${{ secrets.SSH_SECRET }}
198
+ - name: Extract build-web.tar.gz to sg_2
199
+ if: ${{ github.event_name == 'push' }}
200
+ uses: appleboy/ssh-action@master
201
+ with:
202
+ script: cd ${{ env.APP_DIR }}/web && rm -rf node_modules && rm -rf build && cd .. && tar -xzf build-web.tar.gz && rm -rf build-web.tar.gz
203
+ host: ${{ env.DEV_HOST_SG_2 }}
204
+ username: ${{ env.DEV_USER }}
205
+ key: ${{ secrets.SSH_SECRET }}
206
+ proxy_host: ${{ env.DEV_HOST_SG_1 }}
207
+ proxy_username: ${{ env.DEV_USER }}
208
+ proxy_key: ${{ secrets.SSH_SECRET }}
209
+ - name: Extract build-server.tar.gz to sg_2
210
+ if: ${{ github.event_name == 'push' }}
211
+ uses: appleboy/ssh-action@master
212
+ with:
213
+ script: cd ${{ env.APP_DIR }}/server && rm -rf node_modules && rm -rf dist && cd .. && tar -xzf build-server.tar.gz && rm -rf build-server.tar.gz && git pull origin main --rebase && cd ${{ env.APP_DIR }} && /usr/local/bin/pm2 restart td
214
+ host: ${{ env.DEV_HOST_SG_2 }}
215
+ username: ${{ env.DEV_USER }}
216
+ key: ${{ secrets.SSH_SECRET }}
217
+ proxy_host: ${{ env.DEV_HOST_SG_1 }}
218
+ proxy_username: ${{ env.DEV_USER }}
219
+ proxy_key: ${{ secrets.SSH_SECRET }}
220
+
221
+ # Notification
222
+ - name: Success Notification
223
+ uses: appleboy/telegram-action@master
224
+ with:
225
+ to: -700697945
226
+ token: ${{ secrets.TG_BOT_TOKEN }}
227
+ message: 🎉 Deployed to SG_2
228
+ format: markdown
229
+ - name: Failed Notification
230
+ if: ${{ failure() }}
231
+ uses: appleboy/telegram-action@master
232
+ with:
233
+ to: -700697945
234
+ token: ${{ secrets.TG_BOT_TOKEN }}
235
+ message: 🔥 Deploy to SG_2 Failed!
236
+ format: markdown
237
+
238
+ ge1:
239
+ name: Upload & Deploy to GE1
240
+ needs: build
241
+ runs-on: ubuntu-latest
242
+ steps:
243
+ - name: Download all workflow run artifacts
244
+ uses: actions/download-artifact@v2
245
+
246
+ - run: mv build-root/build-root.tar.gz . && mv build-server/build-server.tar.gz . && mv build-web/build-web.tar.gz .
247
+
248
+ # Upload to GE_1
249
+ - name: Upload build-root.tar.gz to ge_1
250
+ uses: appleboy/scp-action@master
251
+ with:
252
+ source: build-root.tar.gz
253
+ target: ${{ env.APP_DIR }}
254
+ host: ${{ env.DEV_HOST_GE_1 }}
255
+ username: ${{ env.DEV_USER }}
256
+ key: ${{ secrets.SSH_SECRET }}
257
+ debug: true
258
+ - name: Upload build-server.tar.gz to ge_1
259
+ uses: appleboy/scp-action@master
260
+ with:
261
+ source: build-server.tar.gz
262
+ target: ${{ env.APP_DIR }}
263
+ host: ${{ env.DEV_HOST_GE_1 }}
264
+ username: ${{ env.DEV_USER }}
265
+ key: ${{ secrets.SSH_SECRET }}
266
+ - name: Upload build-web.tar.gz to ge_1
267
+ uses: appleboy/scp-action@master
268
+ with:
269
+ source: build-web.tar.gz
270
+ target: ${{ env.APP_DIR }}
271
+ host: ${{ env.DEV_HOST_GE_1 }}
272
+ username: ${{ env.DEV_USER }}
273
+ key: ${{ secrets.SSH_SECRET }}
274
+
275
+ # Deployment GE_1
276
+ - name: Extract build-root.tar.gz to ge_1
277
+ uses: appleboy/ssh-action@master
278
+ with:
279
+ script: cd ${{ env.APP_DIR }} && rm -rf node_modules && tar -xzf build-root.tar.gz && rm -rf build-root.tar.gz
280
+ host: ${{ env.DEV_HOST_GE_1 }}
281
+ username: ${{ env.DEV_USER }}
282
+ key: ${{ secrets.SSH_SECRET }}
283
+ - name: Extract build-web.tar.gz to ge_1
284
+ if: ${{ github.event_name == 'push' }}
285
+ uses: appleboy/ssh-action@master
286
+ with:
287
+ script: cd ${{ env.APP_DIR }}/web && rm -rf node_modules && rm -rf build && cd .. && tar -xzf build-web.tar.gz && rm -rf build-web.tar.gz
288
+ host: ${{ env.DEV_HOST_GE_1 }}
289
+ username: ${{ env.DEV_USER }}
290
+ key: ${{ secrets.SSH_SECRET }}
291
+ - name: Extract build-server.tar.gz to ge_1
292
+ if: ${{ github.event_name == 'push' }}
293
+ uses: appleboy/ssh-action@master
294
+ with:
295
+ script: cd ${{ env.APP_DIR }}/server && rm -rf node_modules && rm -rf dist && cd .. && tar -xzf build-server.tar.gz && rm -rf build-server.tar.gz && git pull origin main --rebase && cd ${{ env.APP_DIR }} && /usr/local/bin/pm2 restart td
296
+ host: ${{ env.DEV_HOST_GE_1 }}
297
+ username: ${{ env.DEV_USER }}
298
+ key: ${{ secrets.SSH_SECRET }}
299
+
300
+ # Notification
301
+ - name: Success Notification
302
+ uses: appleboy/telegram-action@master
303
+ with:
304
+ to: -700697945
305
+ token: ${{ secrets.TG_BOT_TOKEN }}
306
+ message: 🎉 Deployed to GE_1
307
+ format: markdown
308
+ - name: Failed Notification
309
+ if: ${{ failure() }}
310
+ uses: appleboy/telegram-action@master
311
+ with:
312
+ to: -700697945
313
+ token: ${{ secrets.TG_BOT_TOKEN }}
314
+ message: 🔥 Deploy to GE_1 Failed!
315
+ format: markdown
316
+
317
+ ge2:
318
+ name: Upload & Deploy to GE2
319
+ needs: build
320
+ runs-on: ubuntu-latest
321
+ steps:
322
+ - name: Download all workflow run artifacts
323
+ uses: actions/download-artifact@v2
324
+
325
+ - run: mv build-root/build-root.tar.gz . && mv build-server/build-server.tar.gz . && mv build-web/build-web.tar.gz .
326
+
327
+ # Upload to GE_2
328
+ - name: Upload build-root.tar.gz to ge_2
329
+ uses: appleboy/scp-action@master
330
+ with:
331
+ source: build-root.tar.gz
332
+ target: ${{ env.APP_DIR }}
333
+ host: ${{ env.DEV_HOST_GE_2 }}
334
+ username: ${{ env.DEV_USER }}
335
+ key: ${{ secrets.SSH_SECRET }}
336
+ proxy_host: ${{ env.DEV_HOST_GE_1 }}
337
+ proxy_username: ${{ env.DEV_USER }}
338
+ proxy_key: ${{ secrets.SSH_SECRET }}
339
+ debug: true
340
+ - name: Upload build-server.tar.gz to ge_2
341
+ uses: appleboy/scp-action@master
342
+ with:
343
+ source: build-server.tar.gz
344
+ target: ${{ env.APP_DIR }}
345
+ host: ${{ env.DEV_HOST_GE_2 }}
346
+ username: ${{ env.DEV_USER }}
347
+ key: ${{ secrets.SSH_SECRET }}
348
+ proxy_host: ${{ env.DEV_HOST_GE_1 }}
349
+ proxy_username: ${{ env.DEV_USER }}
350
+ proxy_key: ${{ secrets.SSH_SECRET }}
351
+ - name: Upload build-web.tar.gz to ge_2
352
+ uses: appleboy/scp-action@master
353
+ with:
354
+ source: build-web.tar.gz
355
+ target: ${{ env.APP_DIR }}
356
+ host: ${{ env.DEV_HOST_GE_2 }}
357
+ username: ${{ env.DEV_USER }}
358
+ key: ${{ secrets.SSH_SECRET }}
359
+ proxy_host: ${{ env.DEV_HOST_GE_1 }}
360
+ proxy_username: ${{ env.DEV_USER }}
361
+ proxy_key: ${{ secrets.SSH_SECRET }}
362
+
363
+ # Deployment GE_2
364
+ - name: Extract build-root.tar.gz to ge_2
365
+ uses: appleboy/ssh-action@master
366
+ with:
367
+ script: cd ${{ env.APP_DIR }} && rm -rf node_modules && tar -xzf build-root.tar.gz && rm -rf build-root.tar.gz
368
+ host: ${{ env.DEV_HOST_GE_2 }}
369
+ username: ${{ env.DEV_USER }}
370
+ key: ${{ secrets.SSH_SECRET }}
371
+ proxy_host: ${{ env.DEV_HOST_GE_1 }}
372
+ proxy_username: ${{ env.DEV_USER }}
373
+ proxy_key: ${{ secrets.SSH_SECRET }}
374
+ - name: Extract build-web.tar.gz to ge_2
375
+ if: ${{ github.event_name == 'push' }}
376
+ uses: appleboy/ssh-action@master
377
+ with:
378
+ script: cd ${{ env.APP_DIR }}/web && rm -rf node_modules && rm -rf build && cd .. && tar -xzf build-web.tar.gz && rm -rf build-web.tar.gz
379
+ host: ${{ env.DEV_HOST_GE_2 }}
380
+ username: ${{ env.DEV_USER }}
381
+ key: ${{ secrets.SSH_SECRET }}
382
+ proxy_host: ${{ env.DEV_HOST_GE_1 }}
383
+ proxy_username: ${{ env.DEV_USER }}
384
+ proxy_key: ${{ secrets.SSH_SECRET }}
385
+ - name: Extract build-server.tar.gz to ge_2
386
+ if: ${{ github.event_name == 'push' }}
387
+ uses: appleboy/ssh-action@master
388
+ with:
389
+ script: cd ${{ env.APP_DIR }}/server && rm -rf node_modules && rm -rf dist && cd .. && tar -xzf build-server.tar.gz && rm -rf build-server.tar.gz && git pull origin main --rebase && cd ${{ env.APP_DIR }} && /usr/local/bin/pm2 restart td
390
+ host: ${{ env.DEV_HOST_GE_2 }}
391
+ username: ${{ env.DEV_USER }}
392
+ key: ${{ secrets.SSH_SECRET }}
393
+ proxy_host: ${{ env.DEV_HOST_GE_1 }}
394
+ proxy_username: ${{ env.DEV_USER }}
395
+ proxy_key: ${{ secrets.SSH_SECRET }}
396
+
397
+ # Notification
398
+ - name: Success Notification
399
+ uses: appleboy/telegram-action@master
400
+ with:
401
+ to: -700697945
402
+ token: ${{ secrets.TG_BOT_TOKEN }}
403
+ message: 🎉 Deployed to GE_2
404
+ format: markdown
405
+ - name: Failed Notification
406
+ if: ${{ failure() }}
407
+ uses: appleboy/telegram-action@master
408
+ with:
409
+ to: -700697945
410
+ token: ${{ secrets.TG_BOT_TOKEN }}
411
+ message: 🔥 Deploy to GE_2 Failed!
412
+ format: markdown
413
+
414
+ us1:
415
+ name: Upload & Deploy to US1
416
+ needs: build
417
+ runs-on: ubuntu-latest
418
+ steps:
419
+ - name: Download all workflow run artifacts
420
+ uses: actions/download-artifact@v2
421
+
422
+ - run: mv build-root/build-root.tar.gz . && mv build-server/build-server.tar.gz . && mv build-web/build-web.tar.gz .
423
+
424
+ # Upload to US_1
425
+ - name: Upload build-root.tar.gz to us_1
426
+ uses: appleboy/scp-action@master
427
+ with:
428
+ source: build-root.tar.gz
429
+ target: ${{ env.APP_DIR }}
430
+ host: ${{ env.DEV_HOST_US_1 }}
431
+ username: ${{ env.DEV_USER }}
432
+ key: ${{ secrets.SSH_SECRET }}
433
+ debug: true
434
+ - name: Upload build-server.tar.gz to us_1
435
+ uses: appleboy/scp-action@master
436
+ with:
437
+ source: build-server.tar.gz
438
+ target: ${{ env.APP_DIR }}
439
+ host: ${{ env.DEV_HOST_US_1 }}
440
+ username: ${{ env.DEV_USER }}
441
+ key: ${{ secrets.SSH_SECRET }}
442
+ - name: Upload build-web.tar.gz to us_1
443
+ uses: appleboy/scp-action@master
444
+ with:
445
+ source: build-web.tar.gz
446
+ target: ${{ env.APP_DIR }}
447
+ host: ${{ env.DEV_HOST_US_1 }}
448
+ username: ${{ env.DEV_USER }}
449
+ key: ${{ secrets.SSH_SECRET }}
450
+
451
+ # Deployment US_1
452
+ - name: Extract build-root.tar.gz to us_1
453
+ uses: appleboy/ssh-action@master
454
+ with:
455
+ script: cd ${{ env.APP_DIR }} && rm -rf node_modules && tar -xzf build-root.tar.gz && rm -rf build-root.tar.gz
456
+ host: ${{ env.DEV_HOST_US_1 }}
457
+ username: ${{ env.DEV_USER }}
458
+ key: ${{ secrets.SSH_SECRET }}
459
+ - name: Extract build-web.tar.gz to us_1
460
+ if: ${{ github.event_name == 'push' }}
461
+ uses: appleboy/ssh-action@master
462
+ with:
463
+ script: cd ${{ env.APP_DIR }}/web && rm -rf node_modules && rm -rf build && cd .. && tar -xzf build-web.tar.gz && rm -rf build-web.tar.gz
464
+ host: ${{ env.DEV_HOST_US_1 }}
465
+ username: ${{ env.DEV_USER }}
466
+ key: ${{ secrets.SSH_SECRET }}
467
+ - name: Extract build-server.tar.gz to us_1
468
+ if: ${{ github.event_name == 'push' }}
469
+ uses: appleboy/ssh-action@master
470
+ with:
471
+ script: cd ${{ env.APP_DIR }}/server && rm -rf node_modules && rm -rf dist && cd .. && tar -xzf build-server.tar.gz && rm -rf build-server.tar.gz && git pull origin main --rebase && cd ${{ env.APP_DIR }} && /usr/local/bin/pm2 restart td
472
+ host: ${{ env.DEV_HOST_US_1 }}
473
+ username: ${{ env.DEV_USER }}
474
+ key: ${{ secrets.SSH_SECRET }}
475
+
476
+ # Notification
477
+ - name: Success Notification
478
+ uses: appleboy/telegram-action@master
479
+ with:
480
+ to: -700697945
481
+ token: ${{ secrets.TG_BOT_TOKEN }}
482
+ message: 🎉 Deployed to US_1
483
+ format: markdown
484
+ - name: Failed Notification
485
+ if: ${{ failure() }}
486
+ uses: appleboy/telegram-action@master
487
+ with:
488
+ to: -700697945
489
+ token: ${{ secrets.TG_BOT_TOKEN }}
490
+ message: 🔥 Deploy to US_1 Failed!
491
+ format: markdown
.github/workflows/build-staging.yml ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ on:
2
+ push:
3
+ branches:
4
+ - staging
5
+
6
+ name: Build Staging
7
+
8
+ jobs:
9
+ build:
10
+ name: Build
11
+ runs-on: ubuntu-latest
12
+
13
+ steps:
14
+ - uses: actions/checkout@v2
15
+ - name: Use Node.js
16
+ uses: actions/setup-node@v1
17
+ with:
18
+ node-version: '14.x'
19
+ - name: Add npmrc
20
+ run: echo -e "//npm.pkg.github.com/:_authToken=${NPM_AUTH_TOKEN}\n@mgilangjanuar:registry=https://npm.pkg.github.com/" > ~/.npmrc && cat ~/.npmrc
21
+ env:
22
+ NPM_AUTH_TOKEN: ${{ secrets.NPM_AUTH_TOKEN }}
23
+ - run: yarn install
24
+ - run: REACT_APP_TG_API_ID=${APP_ID} REACT_APP_TG_API_HASH=${APP_HASH} yarn workspaces run build
25
+ env:
26
+ APP_ID: ${{ secrets.TG_API_ID }}
27
+ APP_HASH: ${{ secrets.TG_API_HASH }}
28
+ - run: npm i vercel -g
29
+ - name: "Deploy to Vercel"
30
+ run: npx vercel --token ${VERCEL_TOKEN} --prod
31
+ env:
32
+ VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
33
+ VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }}
34
+ VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}
35
+ - name: Success Notification
36
+ uses: appleboy/telegram-action@master
37
+ with:
38
+ to: -700697945
39
+ token: ${{ secrets.TG_BOT_TOKEN }}
40
+ message: |
41
+ 🎉 *Deployed to Staging*
42
+
43
+ Please take a look -> https://teledrive.vercel.app
44
+ format: markdown
45
+ - name: Failed Notification
46
+ if: ${{ failure() }}
47
+ uses: appleboy/telegram-action@master
48
+ with:
49
+ to: -700697945
50
+ token: ${{ secrets.TG_BOT_TOKEN }}
51
+ message: |
52
+ 🔥 *Deploy to Staging Failed!*
53
+
54
+ Please take a look -> https://github.com/mgilangjanuar/teledrive/actions
55
+ format: markdown
.gitignore ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ node_modules/
2
+ .DS_Store
3
+ .vscode/
4
+ dist/
5
+ build/
6
+ keys
7
+ .env
8
+ *.env
9
+ .vercel
10
+ lab/
11
+ sessions/
12
+ *.crt
13
+ dump\.rdb
14
+ *.log
15
+ .cached/
Dockerfile ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM node:18.16.0 as build
2
+ ARG REACT_APP_TG_API_ID
3
+ ARG REACT_APP_TG_API_HASH
4
+
5
+ WORKDIR /apps
6
+
7
+ COPY yarn.lock .
8
+ COPY package.json .
9
+ COPY api/package.json api/package.json
10
+ COPY web/package.json web/package.json
11
+ COPY docker/.env .
12
+ RUN yarn cache clean
13
+ RUN yarn install
14
+ RUN yarn global add prisma
15
+ RUN npx browserslist@latest --update-db
16
+ COPY . .
17
+ RUN export NODE_OPTIONS="--openssl-legacy-provider --no-experimental-fetch"
18
+ RUN yarn workspaces run build
LICENSE.md ADDED
@@ -0,0 +1,674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU General Public License is a free, copyleft license for
11
+ software and other kinds of works.
12
+
13
+ The licenses for most software and other practical works are designed
14
+ to take away your freedom to share and change the works. By contrast,
15
+ the GNU General Public License is intended to guarantee your freedom to
16
+ share and change all versions of a program--to make sure it remains free
17
+ software for all its users. We, the Free Software Foundation, use the
18
+ GNU General Public License for most of our software; it applies also to
19
+ any other work released this way by its authors. You can apply it to
20
+ your programs, too.
21
+
22
+ When we speak of free software, we are referring to freedom, not
23
+ price. Our General Public Licenses are designed to make sure that you
24
+ have the freedom to distribute copies of free software (and charge for
25
+ them if you wish), that you receive source code or can get it if you
26
+ want it, that you can change the software or use pieces of it in new
27
+ free programs, and that you know you can do these things.
28
+
29
+ To protect your rights, we need to prevent others from denying you
30
+ these rights or asking you to surrender the rights. Therefore, you have
31
+ certain responsibilities if you distribute copies of the software, or if
32
+ you modify it: responsibilities to respect the freedom of others.
33
+
34
+ For example, if you distribute copies of such a program, whether
35
+ gratis or for a fee, you must pass on to the recipients the same
36
+ freedoms that you received. You must make sure that they, too, receive
37
+ or can get the source code. And you must show them these terms so they
38
+ know their rights.
39
+
40
+ Developers that use the GNU GPL protect your rights with two steps:
41
+ (1) assert copyright on the software, and (2) offer you this License
42
+ giving you legal permission to copy, distribute and/or modify it.
43
+
44
+ For the developers' and authors' protection, the GPL clearly explains
45
+ that there is no warranty for this free software. For both users' and
46
+ authors' sake, the GPL requires that modified versions be marked as
47
+ changed, so that their problems will not be attributed erroneously to
48
+ authors of previous versions.
49
+
50
+ Some devices are designed to deny users access to install or run
51
+ modified versions of the software inside them, although the manufacturer
52
+ can do so. This is fundamentally incompatible with the aim of
53
+ protecting users' freedom to change the software. The systematic
54
+ pattern of such abuse occurs in the area of products for individuals to
55
+ use, which is precisely where it is most unacceptable. Therefore, we
56
+ have designed this version of the GPL to prohibit the practice for those
57
+ products. If such problems arise substantially in other domains, we
58
+ stand ready to extend this provision to those domains in future versions
59
+ of the GPL, as needed to protect the freedom of users.
60
+
61
+ Finally, every program is threatened constantly by software patents.
62
+ States should not allow patents to restrict development and use of
63
+ software on general-purpose computers, but in those that do, we wish to
64
+ avoid the special danger that patents applied to a free program could
65
+ make it effectively proprietary. To prevent this, the GPL assures that
66
+ patents cannot be used to render the program non-free.
67
+
68
+ The precise terms and conditions for copying, distribution and
69
+ modification follow.
70
+
71
+ TERMS AND CONDITIONS
72
+
73
+ 0. Definitions.
74
+
75
+ "This License" refers to version 3 of the GNU General Public License.
76
+
77
+ "Copyright" also means copyright-like laws that apply to other kinds of
78
+ works, such as semiconductor masks.
79
+
80
+ "The Program" refers to any copyrightable work licensed under this
81
+ License. Each licensee is addressed as "you". "Licensees" and
82
+ "recipients" may be individuals or organizations.
83
+
84
+ To "modify" a work means to copy from or adapt all or part of the work
85
+ in a fashion requiring copyright permission, other than the making of an
86
+ exact copy. The resulting work is called a "modified version" of the
87
+ earlier work or a work "based on" the earlier work.
88
+
89
+ A "covered work" means either the unmodified Program or a work based
90
+ on the Program.
91
+
92
+ To "propagate" a work means to do anything with it that, without
93
+ permission, would make you directly or secondarily liable for
94
+ infringement under applicable copyright law, except executing it on a
95
+ computer or modifying a private copy. Propagation includes copying,
96
+ distribution (with or without modification), making available to the
97
+ public, and in some countries other activities as well.
98
+
99
+ To "convey" a work means any kind of propagation that enables other
100
+ parties to make or receive copies. Mere interaction with a user through
101
+ a computer network, with no transfer of a copy, is not conveying.
102
+
103
+ An interactive user interface displays "Appropriate Legal Notices"
104
+ to the extent that it includes a convenient and prominently visible
105
+ feature that (1) displays an appropriate copyright notice, and (2)
106
+ tells the user that there is no warranty for the work (except to the
107
+ extent that warranties are provided), that licensees may convey the
108
+ work under this License, and how to view a copy of this License. If
109
+ the interface presents a list of user commands or options, such as a
110
+ menu, a prominent item in the list meets this criterion.
111
+
112
+ 1. Source Code.
113
+
114
+ The "source code" for a work means the preferred form of the work
115
+ for making modifications to it. "Object code" means any non-source
116
+ form of a work.
117
+
118
+ A "Standard Interface" means an interface that either is an official
119
+ standard defined by a recognized standards body, or, in the case of
120
+ interfaces specified for a particular programming language, one that
121
+ is widely used among developers working in that language.
122
+
123
+ The "System Libraries" of an executable work include anything, other
124
+ than the work as a whole, that (a) is included in the normal form of
125
+ packaging a Major Component, but which is not part of that Major
126
+ Component, and (b) serves only to enable use of the work with that
127
+ Major Component, or to implement a Standard Interface for which an
128
+ implementation is available to the public in source code form. A
129
+ "Major Component", in this context, means a major essential component
130
+ (kernel, window system, and so on) of the specific operating system
131
+ (if any) on which the executable work runs, or a compiler used to
132
+ produce the work, or an object code interpreter used to run it.
133
+
134
+ The "Corresponding Source" for a work in object code form means all
135
+ the source code needed to generate, install, and (for an executable
136
+ work) run the object code and to modify the work, including scripts to
137
+ control those activities. However, it does not include the work's
138
+ System Libraries, or general-purpose tools or generally available free
139
+ programs which are used unmodified in performing those activities but
140
+ which are not part of the work. For example, Corresponding Source
141
+ includes interface definition files associated with source files for
142
+ the work, and the source code for shared libraries and dynamically
143
+ linked subprograms that the work is specifically designed to require,
144
+ such as by intimate data communication or control flow between those
145
+ subprograms and other parts of the work.
146
+
147
+ The Corresponding Source need not include anything that users
148
+ can regenerate automatically from other parts of the Corresponding
149
+ Source.
150
+
151
+ The Corresponding Source for a work in source code form is that
152
+ same work.
153
+
154
+ 2. Basic Permissions.
155
+
156
+ All rights granted under this License are granted for the term of
157
+ copyright on the Program, and are irrevocable provided the stated
158
+ conditions are met. This License explicitly affirms your unlimited
159
+ permission to run the unmodified Program. The output from running a
160
+ covered work is covered by this License only if the output, given its
161
+ content, constitutes a covered work. This License acknowledges your
162
+ rights of fair use or other equivalent, as provided by copyright law.
163
+
164
+ You may make, run and propagate covered works that you do not
165
+ convey, without conditions so long as your license otherwise remains
166
+ in force. You may convey covered works to others for the sole purpose
167
+ of having them make modifications exclusively for you, or provide you
168
+ with facilities for running those works, provided that you comply with
169
+ the terms of this License in conveying all material for which you do
170
+ not control copyright. Those thus making or running the covered works
171
+ for you must do so exclusively on your behalf, under your direction
172
+ and control, on terms that prohibit them from making any copies of
173
+ your copyrighted material outside their relationship with you.
174
+
175
+ Conveying under any other circumstances is permitted solely under
176
+ the conditions stated below. Sublicensing is not allowed; section 10
177
+ makes it unnecessary.
178
+
179
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180
+
181
+ No covered work shall be deemed part of an effective technological
182
+ measure under any applicable law fulfilling obligations under article
183
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184
+ similar laws prohibiting or restricting circumvention of such
185
+ measures.
186
+
187
+ When you convey a covered work, you waive any legal power to forbid
188
+ circumvention of technological measures to the extent such circumvention
189
+ is effected by exercising rights under this License with respect to
190
+ the covered work, and you disclaim any intention to limit operation or
191
+ modification of the work as a means of enforcing, against the work's
192
+ users, your or third parties' legal rights to forbid circumvention of
193
+ technological measures.
194
+
195
+ 4. Conveying Verbatim Copies.
196
+
197
+ You may convey verbatim copies of the Program's source code as you
198
+ receive it, in any medium, provided that you conspicuously and
199
+ appropriately publish on each copy an appropriate copyright notice;
200
+ keep intact all notices stating that this License and any
201
+ non-permissive terms added in accord with section 7 apply to the code;
202
+ keep intact all notices of the absence of any warranty; and give all
203
+ recipients a copy of this License along with the Program.
204
+
205
+ You may charge any price or no price for each copy that you convey,
206
+ and you may offer support or warranty protection for a fee.
207
+
208
+ 5. Conveying Modified Source Versions.
209
+
210
+ You may convey a work based on the Program, or the modifications to
211
+ produce it from the Program, in the form of source code under the
212
+ terms of section 4, provided that you also meet all of these conditions:
213
+
214
+ a) The work must carry prominent notices stating that you modified
215
+ it, and giving a relevant date.
216
+
217
+ b) The work must carry prominent notices stating that it is
218
+ released under this License and any conditions added under section
219
+ 7. This requirement modifies the requirement in section 4 to
220
+ "keep intact all notices".
221
+
222
+ c) You must license the entire work, as a whole, under this
223
+ License to anyone who comes into possession of a copy. This
224
+ License will therefore apply, along with any applicable section 7
225
+ additional terms, to the whole of the work, and all its parts,
226
+ regardless of how they are packaged. This License gives no
227
+ permission to license the work in any other way, but it does not
228
+ invalidate such permission if you have separately received it.
229
+
230
+ d) If the work has interactive user interfaces, each must display
231
+ Appropriate Legal Notices; however, if the Program has interactive
232
+ interfaces that do not display Appropriate Legal Notices, your
233
+ work need not make them do so.
234
+
235
+ A compilation of a covered work with other separate and independent
236
+ works, which are not by their nature extensions of the covered work,
237
+ and which are not combined with it such as to form a larger program,
238
+ in or on a volume of a storage or distribution medium, is called an
239
+ "aggregate" if the compilation and its resulting copyright are not
240
+ used to limit the access or legal rights of the compilation's users
241
+ beyond what the individual works permit. Inclusion of a covered work
242
+ in an aggregate does not cause this License to apply to the other
243
+ parts of the aggregate.
244
+
245
+ 6. Conveying Non-Source Forms.
246
+
247
+ You may convey a covered work in object code form under the terms
248
+ of sections 4 and 5, provided that you also convey the
249
+ machine-readable Corresponding Source under the terms of this License,
250
+ in one of these ways:
251
+
252
+ a) Convey the object code in, or embodied in, a physical product
253
+ (including a physical distribution medium), accompanied by the
254
+ Corresponding Source fixed on a durable physical medium
255
+ customarily used for software interchange.
256
+
257
+ b) Convey the object code in, or embodied in, a physical product
258
+ (including a physical distribution medium), accompanied by a
259
+ written offer, valid for at least three years and valid for as
260
+ long as you offer spare parts or customer support for that product
261
+ model, to give anyone who possesses the object code either (1) a
262
+ copy of the Corresponding Source for all the software in the
263
+ product that is covered by this License, on a durable physical
264
+ medium customarily used for software interchange, for a price no
265
+ more than your reasonable cost of physically performing this
266
+ conveying of source, or (2) access to copy the
267
+ Corresponding Source from a network server at no charge.
268
+
269
+ c) Convey individual copies of the object code with a copy of the
270
+ written offer to provide the Corresponding Source. This
271
+ alternative is allowed only occasionally and noncommercially, and
272
+ only if you received the object code with such an offer, in accord
273
+ with subsection 6b.
274
+
275
+ d) Convey the object code by offering access from a designated
276
+ place (gratis or for a charge), and offer equivalent access to the
277
+ Corresponding Source in the same way through the same place at no
278
+ further charge. You need not require recipients to copy the
279
+ Corresponding Source along with the object code. If the place to
280
+ copy the object code is a network server, the Corresponding Source
281
+ may be on a different server (operated by you or a third party)
282
+ that supports equivalent copying facilities, provided you maintain
283
+ clear directions next to the object code saying where to find the
284
+ Corresponding Source. Regardless of what server hosts the
285
+ Corresponding Source, you remain obligated to ensure that it is
286
+ available for as long as needed to satisfy these requirements.
287
+
288
+ e) Convey the object code using peer-to-peer transmission, provided
289
+ you inform other peers where the object code and Corresponding
290
+ Source of the work are being offered to the general public at no
291
+ charge under subsection 6d.
292
+
293
+ A separable portion of the object code, whose source code is excluded
294
+ from the Corresponding Source as a System Library, need not be
295
+ included in conveying the object code work.
296
+
297
+ A "User Product" is either (1) a "consumer product", which means any
298
+ tangible personal property which is normally used for personal, family,
299
+ or household purposes, or (2) anything designed or sold for incorporation
300
+ into a dwelling. In determining whether a product is a consumer product,
301
+ doubtful cases shall be resolved in favor of coverage. For a particular
302
+ product received by a particular user, "normally used" refers to a
303
+ typical or common use of that class of product, regardless of the status
304
+ of the particular user or of the way in which the particular user
305
+ actually uses, or expects or is expected to use, the product. A product
306
+ is a consumer product regardless of whether the product has substantial
307
+ commercial, industrial or non-consumer uses, unless such uses represent
308
+ the only significant mode of use of the product.
309
+
310
+ "Installation Information" for a User Product means any methods,
311
+ procedures, authorization keys, or other information required to install
312
+ and execute modified versions of a covered work in that User Product from
313
+ a modified version of its Corresponding Source. The information must
314
+ suffice to ensure that the continued functioning of the modified object
315
+ code is in no case prevented or interfered with solely because
316
+ modification has been made.
317
+
318
+ If you convey an object code work under this section in, or with, or
319
+ specifically for use in, a User Product, and the conveying occurs as
320
+ part of a transaction in which the right of possession and use of the
321
+ User Product is transferred to the recipient in perpetuity or for a
322
+ fixed term (regardless of how the transaction is characterized), the
323
+ Corresponding Source conveyed under this section must be accompanied
324
+ by the Installation Information. But this requirement does not apply
325
+ if neither you nor any third party retains the ability to install
326
+ modified object code on the User Product (for example, the work has
327
+ been installed in ROM).
328
+
329
+ The requirement to provide Installation Information does not include a
330
+ requirement to continue to provide support service, warranty, or updates
331
+ for a work that has been modified or installed by the recipient, or for
332
+ the User Product in which it has been modified or installed. Access to a
333
+ network may be denied when the modification itself materially and
334
+ adversely affects the operation of the network or violates the rules and
335
+ protocols for communication across the network.
336
+
337
+ Corresponding Source conveyed, and Installation Information provided,
338
+ in accord with this section must be in a format that is publicly
339
+ documented (and with an implementation available to the public in
340
+ source code form), and must require no special password or key for
341
+ unpacking, reading or copying.
342
+
343
+ 7. Additional Terms.
344
+
345
+ "Additional permissions" are terms that supplement the terms of this
346
+ License by making exceptions from one or more of its conditions.
347
+ Additional permissions that are applicable to the entire Program shall
348
+ be treated as though they were included in this License, to the extent
349
+ that they are valid under applicable law. If additional permissions
350
+ apply only to part of the Program, that part may be used separately
351
+ under those permissions, but the entire Program remains governed by
352
+ this License without regard to the additional permissions.
353
+
354
+ When you convey a copy of a covered work, you may at your option
355
+ remove any additional permissions from that copy, or from any part of
356
+ it. (Additional permissions may be written to require their own
357
+ removal in certain cases when you modify the work.) You may place
358
+ additional permissions on material, added by you to a covered work,
359
+ for which you have or can give appropriate copyright permission.
360
+
361
+ Notwithstanding any other provision of this License, for material you
362
+ add to a covered work, you may (if authorized by the copyright holders of
363
+ that material) supplement the terms of this License with terms:
364
+
365
+ a) Disclaiming warranty or limiting liability differently from the
366
+ terms of sections 15 and 16 of this License; or
367
+
368
+ b) Requiring preservation of specified reasonable legal notices or
369
+ author attributions in that material or in the Appropriate Legal
370
+ Notices displayed by works containing it; or
371
+
372
+ c) Prohibiting misrepresentation of the origin of that material, or
373
+ requiring that modified versions of such material be marked in
374
+ reasonable ways as different from the original version; or
375
+
376
+ d) Limiting the use for publicity purposes of names of licensors or
377
+ authors of the material; or
378
+
379
+ e) Declining to grant rights under trademark law for use of some
380
+ trade names, trademarks, or service marks; or
381
+
382
+ f) Requiring indemnification of licensors and authors of that
383
+ material by anyone who conveys the material (or modified versions of
384
+ it) with contractual assumptions of liability to the recipient, for
385
+ any liability that these contractual assumptions directly impose on
386
+ those licensors and authors.
387
+
388
+ All other non-permissive additional terms are considered "further
389
+ restrictions" within the meaning of section 10. If the Program as you
390
+ received it, or any part of it, contains a notice stating that it is
391
+ governed by this License along with a term that is a further
392
+ restriction, you may remove that term. If a license document contains
393
+ a further restriction but permits relicensing or conveying under this
394
+ License, you may add to a covered work material governed by the terms
395
+ of that license document, provided that the further restriction does
396
+ not survive such relicensing or conveying.
397
+
398
+ If you add terms to a covered work in accord with this section, you
399
+ must place, in the relevant source files, a statement of the
400
+ additional terms that apply to those files, or a notice indicating
401
+ where to find the applicable terms.
402
+
403
+ Additional terms, permissive or non-permissive, may be stated in the
404
+ form of a separately written license, or stated as exceptions;
405
+ the above requirements apply either way.
406
+
407
+ 8. Termination.
408
+
409
+ You may not propagate or modify a covered work except as expressly
410
+ provided under this License. Any attempt otherwise to propagate or
411
+ modify it is void, and will automatically terminate your rights under
412
+ this License (including any patent licenses granted under the third
413
+ paragraph of section 11).
414
+
415
+ However, if you cease all violation of this License, then your
416
+ license from a particular copyright holder is reinstated (a)
417
+ provisionally, unless and until the copyright holder explicitly and
418
+ finally terminates your license, and (b) permanently, if the copyright
419
+ holder fails to notify you of the violation by some reasonable means
420
+ prior to 60 days after the cessation.
421
+
422
+ Moreover, your license from a particular copyright holder is
423
+ reinstated permanently if the copyright holder notifies you of the
424
+ violation by some reasonable means, this is the first time you have
425
+ received notice of violation of this License (for any work) from that
426
+ copyright holder, and you cure the violation prior to 30 days after
427
+ your receipt of the notice.
428
+
429
+ Termination of your rights under this section does not terminate the
430
+ licenses of parties who have received copies or rights from you under
431
+ this License. If your rights have been terminated and not permanently
432
+ reinstated, you do not qualify to receive new licenses for the same
433
+ material under section 10.
434
+
435
+ 9. Acceptance Not Required for Having Copies.
436
+
437
+ You are not required to accept this License in order to receive or
438
+ run a copy of the Program. Ancillary propagation of a covered work
439
+ occurring solely as a consequence of using peer-to-peer transmission
440
+ to receive a copy likewise does not require acceptance. However,
441
+ nothing other than this License grants you permission to propagate or
442
+ modify any covered work. These actions infringe copyright if you do
443
+ not accept this License. Therefore, by modifying or propagating a
444
+ covered work, you indicate your acceptance of this License to do so.
445
+
446
+ 10. Automatic Licensing of Downstream Recipients.
447
+
448
+ Each time you convey a covered work, the recipient automatically
449
+ receives a license from the original licensors, to run, modify and
450
+ propagate that work, subject to this License. You are not responsible
451
+ for enforcing compliance by third parties with this License.
452
+
453
+ An "entity transaction" is a transaction transferring control of an
454
+ organization, or substantially all assets of one, or subdividing an
455
+ organization, or merging organizations. If propagation of a covered
456
+ work results from an entity transaction, each party to that
457
+ transaction who receives a copy of the work also receives whatever
458
+ licenses to the work the party's predecessor in interest had or could
459
+ give under the previous paragraph, plus a right to possession of the
460
+ Corresponding Source of the work from the predecessor in interest, if
461
+ the predecessor has it or can get it with reasonable efforts.
462
+
463
+ You may not impose any further restrictions on the exercise of the
464
+ rights granted or affirmed under this License. For example, you may
465
+ not impose a license fee, royalty, or other charge for exercise of
466
+ rights granted under this License, and you may not initiate litigation
467
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
468
+ any patent claim is infringed by making, using, selling, offering for
469
+ sale, or importing the Program or any portion of it.
470
+
471
+ 11. Patents.
472
+
473
+ A "contributor" is a copyright holder who authorizes use under this
474
+ License of the Program or a work on which the Program is based. The
475
+ work thus licensed is called the contributor's "contributor version".
476
+
477
+ A contributor's "essential patent claims" are all patent claims
478
+ owned or controlled by the contributor, whether already acquired or
479
+ hereafter acquired, that would be infringed by some manner, permitted
480
+ by this License, of making, using, or selling its contributor version,
481
+ but do not include claims that would be infringed only as a
482
+ consequence of further modification of the contributor version. For
483
+ purposes of this definition, "control" includes the right to grant
484
+ patent sublicenses in a manner consistent with the requirements of
485
+ this License.
486
+
487
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
488
+ patent license under the contributor's essential patent claims, to
489
+ make, use, sell, offer for sale, import and otherwise run, modify and
490
+ propagate the contents of its contributor version.
491
+
492
+ In the following three paragraphs, a "patent license" is any express
493
+ agreement or commitment, however denominated, not to enforce a patent
494
+ (such as an express permission to practice a patent or covenant not to
495
+ sue for patent infringement). To "grant" such a patent license to a
496
+ party means to make such an agreement or commitment not to enforce a
497
+ patent against the party.
498
+
499
+ If you convey a covered work, knowingly relying on a patent license,
500
+ and the Corresponding Source of the work is not available for anyone
501
+ to copy, free of charge and under the terms of this License, through a
502
+ publicly available network server or other readily accessible means,
503
+ then you must either (1) cause the Corresponding Source to be so
504
+ available, or (2) arrange to deprive yourself of the benefit of the
505
+ patent license for this particular work, or (3) arrange, in a manner
506
+ consistent with the requirements of this License, to extend the patent
507
+ license to downstream recipients. "Knowingly relying" means you have
508
+ actual knowledge that, but for the patent license, your conveying the
509
+ covered work in a country, or your recipient's use of the covered work
510
+ in a country, would infringe one or more identifiable patents in that
511
+ country that you have reason to believe are valid.
512
+
513
+ If, pursuant to or in connection with a single transaction or
514
+ arrangement, you convey, or propagate by procuring conveyance of, a
515
+ covered work, and grant a patent license to some of the parties
516
+ receiving the covered work authorizing them to use, propagate, modify
517
+ or convey a specific copy of the covered work, then the patent license
518
+ you grant is automatically extended to all recipients of the covered
519
+ work and works based on it.
520
+
521
+ A patent license is "discriminatory" if it does not include within
522
+ the scope of its coverage, prohibits the exercise of, or is
523
+ conditioned on the non-exercise of one or more of the rights that are
524
+ specifically granted under this License. You may not convey a covered
525
+ work if you are a party to an arrangement with a third party that is
526
+ in the business of distributing software, under which you make payment
527
+ to the third party based on the extent of your activity of conveying
528
+ the work, and under which the third party grants, to any of the
529
+ parties who would receive the covered work from you, a discriminatory
530
+ patent license (a) in connection with copies of the covered work
531
+ conveyed by you (or copies made from those copies), or (b) primarily
532
+ for and in connection with specific products or compilations that
533
+ contain the covered work, unless you entered into that arrangement,
534
+ or that patent license was granted, prior to 28 March 2007.
535
+
536
+ Nothing in this License shall be construed as excluding or limiting
537
+ any implied license or other defenses to infringement that may
538
+ otherwise be available to you under applicable patent law.
539
+
540
+ 12. No Surrender of Others' Freedom.
541
+
542
+ If conditions are imposed on you (whether by court order, agreement or
543
+ otherwise) that contradict the conditions of this License, they do not
544
+ excuse you from the conditions of this License. If you cannot convey a
545
+ covered work so as to satisfy simultaneously your obligations under this
546
+ License and any other pertinent obligations, then as a consequence you may
547
+ not convey it at all. For example, if you agree to terms that obligate you
548
+ to collect a royalty for further conveying from those to whom you convey
549
+ the Program, the only way you could satisfy both those terms and this
550
+ License would be to refrain entirely from conveying the Program.
551
+
552
+ 13. Use with the GNU Affero General Public License.
553
+
554
+ Notwithstanding any other provision of this License, you have
555
+ permission to link or combine any covered work with a work licensed
556
+ under version 3 of the GNU Affero General Public License into a single
557
+ combined work, and to convey the resulting work. The terms of this
558
+ License will continue to apply to the part which is the covered work,
559
+ but the special requirements of the GNU Affero General Public License,
560
+ section 13, concerning interaction through a network will apply to the
561
+ combination as such.
562
+
563
+ 14. Revised Versions of this License.
564
+
565
+ The Free Software Foundation may publish revised and/or new versions of
566
+ the GNU General Public License from time to time. Such new versions will
567
+ be similar in spirit to the present version, but may differ in detail to
568
+ address new problems or concerns.
569
+
570
+ Each version is given a distinguishing version number. If the
571
+ Program specifies that a certain numbered version of the GNU General
572
+ Public License "or any later version" applies to it, you have the
573
+ option of following the terms and conditions either of that numbered
574
+ version or of any later version published by the Free Software
575
+ Foundation. If the Program does not specify a version number of the
576
+ GNU General Public License, you may choose any version ever published
577
+ by the Free Software Foundation.
578
+
579
+ If the Program specifies that a proxy can decide which future
580
+ versions of the GNU General Public License can be used, that proxy's
581
+ public statement of acceptance of a version permanently authorizes you
582
+ to choose that version for the Program.
583
+
584
+ Later license versions may give you additional or different
585
+ permissions. However, no additional obligations are imposed on any
586
+ author or copyright holder as a result of your choosing to follow a
587
+ later version.
588
+
589
+ 15. Disclaimer of Warranty.
590
+
591
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599
+
600
+ 16. Limitation of Liability.
601
+
602
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610
+ SUCH DAMAGES.
611
+
612
+ 17. Interpretation of Sections 15 and 16.
613
+
614
+ If the disclaimer of warranty and limitation of liability provided
615
+ above cannot be given local legal effect according to their terms,
616
+ reviewing courts shall apply local law that most closely approximates
617
+ an absolute waiver of all civil liability in connection with the
618
+ Program, unless a warranty or assumption of liability accompanies a
619
+ copy of the Program in return for a fee.
620
+
621
+ END OF TERMS AND CONDITIONS
622
+
623
+ How to Apply These Terms to Your New Programs
624
+
625
+ If you develop a new program, and you want it to be of the greatest
626
+ possible use to the public, the best way to achieve this is to make it
627
+ free software which everyone can redistribute and change under these terms.
628
+
629
+ To do so, attach the following notices to the program. It is safest
630
+ to attach them to the start of each source file to most effectively
631
+ state the exclusion of warranty; and each file should have at least
632
+ the "copyright" line and a pointer to where the full notice is found.
633
+
634
+ <one line to give the program's name and a brief idea of what it does.>
635
+ Copyright (C) <year> <name of author>
636
+
637
+ This program is free software: you can redistribute it and/or modify
638
+ it under the terms of the GNU General Public License as published by
639
+ the Free Software Foundation, either version 3 of the License, or
640
+ (at your option) any later version.
641
+
642
+ This program is distributed in the hope that it will be useful,
643
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
644
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645
+ GNU General Public License for more details.
646
+
647
+ You should have received a copy of the GNU General Public License
648
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
649
+
650
+ Also add information on how to contact you by electronic and paper mail.
651
+
652
+ If the program does terminal interaction, make it output a short
653
+ notice like this when it starts in an interactive mode:
654
+
655
+ <program> Copyright (C) <year> <name of author>
656
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657
+ This is free software, and you are welcome to redistribute it
658
+ under certain conditions; type `show c' for details.
659
+
660
+ The hypothetical commands `show w' and `show c' should show the appropriate
661
+ parts of the General Public License. Of course, your program's commands
662
+ might be different; for a GUI interface, you would use an "about box".
663
+
664
+ You should also get your employer (if you work as a programmer) or school,
665
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
666
+ For more information on this, and how to apply and follow the GNU GPL, see
667
+ <https://www.gnu.org/licenses/>.
668
+
669
+ The GNU General Public License does not permit incorporating your program
670
+ into proprietary programs. If your program is a subroutine library, you
671
+ may consider it more useful to permit linking proprietary applications with
672
+ the library. If this is what you want to do, use the GNU Lesser General
673
+ Public License instead of this License. But first, please read
674
+ <https://www.gnu.org/licenses/why-not-lgpl.html>.
Procfile ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ web: yarn start
2
+
3
+ release: yarn api prisma migrate deploy || yarn api prisma migrate resolve --applied 20220420012853_init
README.md CHANGED
@@ -1,10 +1,66 @@
1
- ---
2
- title: Teledrive2
3
- emoji: 🌍
4
- colorFrom: gray
5
- colorTo: yellow
6
- sdk: docker
7
- pinned: false
8
- ---
9
-
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ![img](./logoteledrive-white.png)
2
+
3
+ This is the open source project of Google Drive/OneDrive/iCloud/Dropbox alternative using Telegram API for the free unlimited cloud storage.
4
+
5
+ [![img](https://drive.google.com/uc?id=1o2HnKglEF0-cvtNmQqWZicJnSCSmnoEr)](https://twitter.com/telegram/status/1428703364737507332)
6
+
7
+ ## Motivation
8
+
9
+ - [Google Photos ends the free storage service](https://www.techradar.com/news/google-photos-price)
10
+ - We deserve the free cloud storage service! Pricing: [Google Drive](https://one.google.com/about/plans), [OneDrive](https://one.google.com/about/plans), [Dropbox](https://www.dropbox.com/individual/plans-comparison), [iCloud](https://support.apple.com/en-us/HT201238)
11
+
12
+
13
+ ## Getting Started
14
+
15
+ Read here for full instructions: [teledriveapp.com](https://teledriveapp.com)
16
+
17
+ ## API Documentation
18
+
19
+ [![Run in Postman](https://run.pstmn.io/button.svg)](https://www.postman.com/restfireteam/workspace/mgilangjanuar/collection/1778529-3e4b0f8d-f721-4055-8d30-33cacaea93e6?ctx=documentation)
20
+
21
+ ## How to Contribute
22
+
23
+ - Fork and clone this repository
24
+ - Commit your changes
25
+ - Create a pull request to the `staging` branch
26
+
27
+ Or, just send us an [issue](https://github.com/mgilangjanuar/teledrive/issues) for reporting bugs and/or ask the questions, share your ideas, etc in [discussions](https://github.com/mgilangjanuar/teledrive/discussions).
28
+
29
+ ## Deploy to Heroku
30
+ [![Deploy](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy?template=https://github.com/mgilangjanuar/teledrive)
31
+
32
+ If you're experiencing issues check this https://github.com/mgilangjanuar/teledrive/issues/373
33
+
34
+ # Deploy to Railway
35
+ [![Deploy](https://railway.app/button.svg)](https://railway.app/new/template/m4m_XE?referralCode=BvMMSE)
36
+
37
+ (DrakeTDL's forked Teledrive repo powers the railway template.)
38
+
39
+ ## Folder Structure
40
+
41
+ We using the monorepo structure with [yarn workspaces](https://classic.yarnpkg.com/en/docs/workspaces/).
42
+
43
+ ```
44
+ .
45
+ ├── README.md
46
+ ├── package.json
47
+ ├── server
48
+ │   ├── package.json
49
+ │   ├── src
50
+ │   │   └── index.ts
51
+ │   └── tsconfig.json
52
+ ├── web
53
+ │   ├── package.json
54
+ │   ├── public
55
+ │   ├── src
56
+ │   │   ├── pages
57
+ │   │   └── App.tsx
58
+ │   ├── tsconfig.json
59
+ │   └── yarn.lock
60
+ └── yarn.lock
61
+ ```
62
+
63
+ ## Community
64
+ [![img](https://user-images.githubusercontent.com/34012548/172031316-60d858c7-8401-42f3-9c73-0b75e80c8292.png)](https://discord.gg/PKNVJwAZnR)
65
+
66
+ [![img](https://media.discordapp.net/attachments/978783095463501834/984317776544014416/ytbutton.png)](https://youtube.com/channel/UCg9WsNAHdOpo8SyM8JHGuZQ)
android/Icons/logoteledriveblack-onblue.png ADDED
android/Icons/logoteledriveblack-ongradientblack.png ADDED
android/Icons/logoteledriveblue-onblack.png ADDED
android/Icons/logoteledrivewhite-onblack.png ADDED
android/Icons/logoteledrivewhite-onblue.png.png ADDED
android/Icons/logoteledrivewhite-ongradientblueblack.png ADDED
android/Teledrive-Expo/.gitignore ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ node_modules/
2
+ .expo/
3
+ dist/
4
+ npm-debug.*
5
+ *.jks
6
+ *.p8
7
+ *.p12
8
+ *.key
9
+ *.mobileprovision
10
+ *.orig.*
11
+ web-build/
12
+
13
+ # macOS
14
+ .DS_Store
android/Teledrive-Expo/App.js ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import * as React from 'react';
2
+ import { WebView } from 'react-native-webview';
3
+ import { StyleSheet } from 'react-native';
4
+ import Constants from 'expo-constants';
5
+
6
+ export default function App() {
7
+ return (
8
+ <WebView
9
+ style={styles.container}
10
+ source={{ uri: 'https://teledrive-web.vercel.app/startup'}}
11
+ />
12
+ );
13
+ }
14
+
15
+ const styles = StyleSheet.create({
16
+ container: {
17
+
18
+ flex: 1,
19
+ marginTop: Constants.statusBarHeight,
20
+ },
21
+ });
android/Teledrive-Expo/app.json ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "expo": {
3
+ "name": "Teledrive",
4
+ "slug": "snack-6b33518d-2b5e-46c5-beb5-d37aa4f26f80",
5
+ "version": "1.0.2",
6
+ "orientation": "portrait",
7
+ "icon": "./assets/icon.png",
8
+ "splash": {
9
+ "image": "./assets/splash.png",
10
+ "resizeMode": "contain",
11
+ "backgroundColor": "#ffffff"
12
+ },
13
+ "updates": {
14
+ "fallbackToCacheTimeout": 0
15
+ },
16
+ "assetBundlePatterns": [
17
+ "**/*"
18
+ ],
19
+ "ios": {
20
+ "supportsTablet": true
21
+ },
22
+ "android": {
23
+ "versionCode": 3,
24
+ "adaptiveIcon": {
25
+ "foregroundImage": "./assets/adaptive-icon.png",
26
+ "backgroundColor": "#FFFFFF"
27
+ },
28
+ "package": "com.mgilangjanuar.teledrive"
29
+ },
30
+ "web": {
31
+ "favicon": "./assets/favicon.png"
32
+ }
33
+ }
34
+ }
android/Teledrive-Expo/assets/adaptive-icon.png ADDED
android/Teledrive-Expo/assets/favicon.png ADDED
android/Teledrive-Expo/assets/icon.png ADDED
android/Teledrive-Expo/assets/splash.png ADDED
android/Teledrive-Expo/babel.config.js ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ module.exports = function(api) {
2
+ api.cache(true);
3
+ return {
4
+ presets: ['babel-preset-expo'],
5
+ };
6
+ };
android/Teledrive-Expo/eas.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cli": {
3
+ "version": ">= 0.52.0"
4
+ },
5
+ "build": {
6
+ "development": {
7
+ "developmentClient": true,
8
+ "distribution": "internal"
9
+ },
10
+ "preview": {
11
+ "android": {
12
+ "buildType": "apk"
13
+ }
14
+ },
15
+ "production": {}
16
+ },
17
+ "submit": {
18
+ "production": {}
19
+ }
20
+ }
android/Teledrive-Expo/package.json ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "main": "node_modules/expo/AppEntry.js",
3
+ "scripts": {
4
+ "start": "expo start",
5
+ "android": "expo start --android",
6
+ "ios": "expo start --ios",
7
+ "web": "expo start --web",
8
+ "eject": "expo eject"
9
+ },
10
+ "dependencies": {
11
+ "expo": "~44.0.0",
12
+ "expo-cli": "^5.4.6",
13
+ "expo-constants": "~13.0.2",
14
+ "expo-status-bar": "~1.2.0",
15
+ "expo-updates": "~0.11.7",
16
+ "react": "17.0.1",
17
+ "react-dom": "17.0.1",
18
+ "react-native": "0.64.3",
19
+ "react-native-web": "0.17.1",
20
+ "react-native-webview": "11.15.0"
21
+ },
22
+ "devDependencies": {
23
+ "@babel/core": "^7.12.9"
24
+ },
25
+ "private": true
26
+ }
android/Teledrive-Expo/yarn.lock ADDED
The diff for this file is too large to render. See raw diff
 
android/todolist.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Todo list created by greengeckowizard
2
+ ##Start##
3
+ 1.Config File Upload from web app
4
+ ##End##
5
+
api/.env-example ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ENV=production
2
+ PORT=4000
3
+
4
+ TG_API_ID=
5
+ TG_API_HASH=
6
+ ADMIN_USERNAME=
7
+
8
+ DATABASE_URL=postgresql://postgres@localhost:5432/teledrive
9
+
10
+ IS_MAINTENANCE=
11
+
12
+ CACHE_FILES_LIMIT=20GB
api/.eslintignore ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ .vscode
2
+ node_modules
3
+ dist
4
+ cert
5
+ get_env.js
api/.eslintrc.js ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ module.exports = {
2
+ root: true,
3
+ env: {
4
+ node: true
5
+ },
6
+ parser: '@typescript-eslint/parser',
7
+ plugins: [
8
+ '@typescript-eslint',
9
+ ],
10
+ extends: [
11
+ 'eslint:recommended',
12
+ // 'plugin:@typescript-eslint/eslint-recommended',
13
+ 'plugin:@typescript-eslint/recommended',
14
+ ],
15
+ rules: {
16
+ '@typescript-eslint/naming-convention': [
17
+ 'error',
18
+ {
19
+ 'selector': 'variable',
20
+ 'format': ['camelCase', 'UPPER_CASE', 'PascalCase'],
21
+ 'leadingUnderscore': 'allow'
22
+ },
23
+ {
24
+ 'selector': 'typeLike',
25
+ 'format': ['PascalCase']
26
+ }
27
+ ],
28
+ '@typescript-eslint/indent': [
29
+ 'error',
30
+ 2
31
+ ],
32
+ '@typescript-eslint/prefer-namespace-keyword': 'error',
33
+ '@typescript-eslint/quotes': [
34
+ 'error',
35
+ 'single',
36
+ {
37
+ 'avoidEscape': true
38
+ }
39
+ ],
40
+ '@typescript-eslint/semi': [
41
+ 'error',
42
+ 'never'
43
+ ],
44
+ '@typescript-eslint/type-annotation-spacing': 'error',
45
+ '@typescript-eslint/member-delimiter-style': [
46
+ 'error',
47
+ {
48
+ 'multiline': {
49
+ 'delimiter': 'comma',
50
+ 'requireLast': false
51
+ },
52
+ 'singleline': {
53
+ 'delimiter': 'comma',
54
+ 'requireLast': false
55
+ }
56
+ }
57
+ ],
58
+ '@typescript-eslint/no-unused-vars': [
59
+ 'warn',
60
+ {
61
+ 'vars': 'all',
62
+ 'args': 'all',
63
+ 'varsIgnorePattern': '^\_.*$',
64
+ 'argsIgnorePattern': '^\_.*$',
65
+ }
66
+ ],
67
+ '@typescript-eslint/no-extra-parens': 'error',
68
+ '@typescript-eslint/brace-style': 'error',
69
+ '@typescript-eslint/no-use-before-define': 'off',
70
+ '@typescript-eslint/no-explicit-any': 'off',
71
+ '@typescript-eslint/explicit-function-return-type': 'off',
72
+ '@typescript-eslint/no-namespace': 'off',
73
+ '@typescript-eslint/no-inferrable-types': 'off',
74
+ '@typescript-eslint/no-empty-function': 'off',
75
+ '@typescript-eslint/no-empty-interface': 'off',
76
+ 'no-null/no-null': 'off',
77
+ 'no-useless-escape': 'off',
78
+ 'no-trailing-spaces': 'error',
79
+ 'no-var': 'error',
80
+ 'prefer-const': 'error',
81
+ 'spaced-comment': 'error',
82
+ 'object-curly-spacing': ['error', 'always'],
83
+ 'space-in-parens': ['error', 'never'],
84
+ 'array-bracket-spacing': ['error', 'never'],
85
+ 'space-before-function-paren': [
86
+ 'error',
87
+ {
88
+ 'named': 'never',
89
+ 'anonymous': 'always',
90
+ 'asyncArrow': 'always'
91
+ }
92
+ ],
93
+ '@typescript-eslint/no-var-requires': 'off'
94
+ }
95
+ }
api/.gitignore ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ node_modules
2
+ # Keep environment variables out of version control
3
+ .env
4
+ .vercel
api/package.json ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "api",
3
+ "version": "2.5.5",
4
+ "main": "dist/index.js",
5
+ "license": "MIT",
6
+ "private": true,
7
+ "scripts": {
8
+ "start": "nodemon dist/index.js --watch",
9
+ "prebuild": "prisma generate",
10
+ "build": "rimraf dist && eslint -c .eslintrc.js --ext .ts . && tsc",
11
+ "postbuild": "test -f keys || (node -e \"console.log(require('crypto').randomBytes(48).toString('base64'));\" > keys && node -e \"console.log(require('crypto').randomBytes(48).toString('base64'));\" >> keys)"
12
+ },
13
+ "dependencies": {
14
+ "@prisma/client": "^4.12.0",
15
+ "@types/moment": "^2.13.0",
16
+ "axios": "^0.21.4",
17
+ "bcryptjs": "^2.4.3",
18
+ "big-integer": "^1.6.48",
19
+ "check-disk-space": "^3.3.0",
20
+ "compression": "^1.7.4",
21
+ "content-disposition": "^0.5.3",
22
+ "cookie-parser": "^1.4.5",
23
+ "cors": "^2.8.5",
24
+ "crypto": "^1.0.1",
25
+ "crypto-js": "^4.1.1",
26
+ "curly-express": "^1.3.6",
27
+ "dotenv": "^10.0.0",
28
+ "express": "^4.17.1",
29
+ "express-ipinfo": "^1.0.0",
30
+ "express-list-endpoints": "^6.0.0",
31
+ "express-rate-limit": "^5.3.0",
32
+ "flatted": "^3.2.2",
33
+ "geoip-lite": "^1.4.2",
34
+ "human-format": "^1.0.0",
35
+ "input": "^1.0.1",
36
+ "ioredis": "^4.28.2",
37
+ "is-uuid": "^1.0.2",
38
+ "json-bigint": "^1.0.0",
39
+ "jsonwebtoken": "^8.5.1",
40
+ "moment": "^2.29.1",
41
+ "morgan": "^1.10.0",
42
+ "multer": "^1.4.3",
43
+ "nanoid": "^3.1.25",
44
+ "pg": "^8.7.1",
45
+ "pg-connection-string": "^2.5.0",
46
+ "prisma": "^4.12.0",
47
+ "redis": "^4.0.1",
48
+ "serialize-error": "^8.1.0",
49
+ "serverless-http": "^3.0.1",
50
+ "source-map-support": "^0.5.19",
51
+ "telegram": "^2.15.5",
52
+ "uuid-random": "^1.3.2",
53
+ "util": "0.12.5",
54
+ "path":"0.12.7"
55
+ },
56
+ "devDependencies": {
57
+ "@types/axios": "^0.14.0",
58
+ "@types/bcryptjs": "^2.4.2",
59
+ "@types/big-integer": "^0.0.31",
60
+ "@types/compression": "^1.7.2",
61
+ "@types/content-disposition": "^0.5.4",
62
+ "@types/cookie-parser": "^1.4.2",
63
+ "@types/cors": "^2.8.12",
64
+ "@types/crypto-js": "^4.0.2",
65
+ "@types/dotenv": "^8.2.0",
66
+ "@types/express": "^4.17.13",
67
+ "@types/express-list-endpoints": "^6.0.0",
68
+ "@types/express-rate-limit": "^5.1.3",
69
+ "@types/geoip-lite": "^1.4.1",
70
+ "@types/ioredis": "^4.28.7",
71
+ "@types/is-uuid": "^1.0.0",
72
+ "@types/jsonwebtoken": "^8.5.5",
73
+ "@types/morgan": "^1.9.3",
74
+ "@types/multer": "^1.4.7",
75
+ "@types/nanoid": "^3.0.0",
76
+ "@types/node": "^16.7.2",
77
+ "@types/pg": "^8.6.1",
78
+ "@types/pg-connection-string": "^2.0.0",
79
+ "@types/redis": "^4.0.11",
80
+ "@types/serialize-error": "^4.0.1",
81
+ "@types/source-map-support": "^0.5.4",
82
+ "@typescript-eslint/eslint-plugin": "^4.29.3",
83
+ "@typescript-eslint/parser": "^4.29.3",
84
+ "eslint": "^7.32.0",
85
+ "nodemon": "^2.0.12",
86
+ "reflect-metadata": "^0.1.13",
87
+ "rimraf": "^3.0.2",
88
+ "typescript": "^4.4.2"
89
+ }
90
+ }
api/prisma/migrations/20220420012853_init/migration.sql ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
2
+
3
+ -- CreateTable
4
+ CREATE TABLE "config" (
5
+ "created_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
6
+ "updated_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
7
+ "id" UUID NOT NULL DEFAULT uuid_generate_v4(),
8
+ "invitation_code" VARCHAR,
9
+ "disable_signup" BOOLEAN NOT NULL DEFAULT false,
10
+ "allow_server_storage_use" BOOLEAN NOT NULL DEFAULT false,
11
+
12
+ CONSTRAINT "pk_af2ddc24176f1572cbdd4b45992" PRIMARY KEY ("id")
13
+ );
14
+
15
+ -- CreateTable
16
+ CREATE TABLE "files" (
17
+ "created_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
18
+ "updated_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
19
+ "id" UUID NOT NULL DEFAULT uuid_generate_v4(),
20
+ "name" VARCHAR NOT NULL,
21
+ "type" VARCHAR,
22
+ "message_id" VARCHAR,
23
+ "mime_type" VARCHAR,
24
+ "size" BIGINT,
25
+ "uploaded_at" TIMESTAMPTZ(6),
26
+ "upload_progress" DOUBLE PRECISION,
27
+ "user_id" UUID NOT NULL,
28
+ "parent_id" UUID,
29
+ "deleted_at" TIMESTAMPTZ(6),
30
+ "sharing_options" VARCHAR[],
31
+ "signed_key" VARCHAR,
32
+ "file_id" VARCHAR,
33
+ "link_id" UUID,
34
+ "forward_info" VARCHAR,
35
+
36
+ CONSTRAINT "PK_6c16b9093a142e0e7613b04a3d9" PRIMARY KEY ("id")
37
+ );
38
+
39
+ -- CreateTable
40
+ CREATE TABLE "rate_limits" (
41
+ "key" VARCHAR(255) NOT NULL,
42
+ "points" INTEGER NOT NULL DEFAULT 0,
43
+ "expire" BIGINT,
44
+
45
+ CONSTRAINT "rate_limits_pkey" PRIMARY KEY ("key")
46
+ );
47
+
48
+ -- CreateTable
49
+ CREATE TABLE "usages" (
50
+ "created_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
51
+ "updated_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
52
+ "key" VARCHAR NOT NULL,
53
+ "usage" BIGINT NOT NULL,
54
+ "expire" TIMESTAMPTZ(6) NOT NULL,
55
+
56
+ CONSTRAINT "PK_7d8e95b6dd4c0e87cad4972da13" PRIMARY KEY ("key")
57
+ );
58
+
59
+ -- CreateTable
60
+ CREATE TABLE "users" (
61
+ "created_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
62
+ "updated_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
63
+ "id" UUID NOT NULL DEFAULT uuid_generate_v4(),
64
+ "username" VARCHAR NOT NULL,
65
+ "name" VARCHAR,
66
+ "email" VARCHAR,
67
+ "tg_id" VARCHAR,
68
+ "plan" VARCHAR,
69
+ "settings" JSONB,
70
+ "role" VARCHAR,
71
+
72
+ CONSTRAINT "PK_a3ffb1c0c8416b9fc6f907b7433" PRIMARY KEY ("id")
73
+ );
74
+
75
+ -- CreateTable
76
+ CREATE TABLE "waitings" (
77
+ "created_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
78
+ "updated_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
79
+ "id" UUID NOT NULL DEFAULT uuid_generate_v4(),
80
+ "email" VARCHAR NOT NULL,
81
+
82
+ CONSTRAINT "PK_f0cfe98441cf0fb92db66ae71c4" PRIMARY KEY ("id")
83
+ );
84
+
85
+ -- CreateIndex
86
+ CREATE INDEX "files_link_id_idx" ON "files"("link_id");
87
+
88
+ -- CreateIndex
89
+ CREATE INDEX "files_message_id_idx" ON "files"("message_id");
90
+
91
+ -- CreateIndex
92
+ CREATE INDEX "files_parent_id_idx" ON "files"("parent_id");
93
+
94
+ -- CreateIndex
95
+ CREATE INDEX "files_user_id_idx" ON "files"("user_id");
96
+
97
+ -- CreateIndex
98
+ CREATE INDEX "tg_id" ON "users"("tg_id");
99
+
100
+ -- AddForeignKey
101
+ ALTER TABLE "files" ADD CONSTRAINT "files_links_fkey" FOREIGN KEY ("link_id") REFERENCES "files"("id") ON DELETE CASCADE ON UPDATE CASCADE;
102
+
103
+ -- AddForeignKey
104
+ ALTER TABLE "files" ADD CONSTRAINT "files_files_fkey" FOREIGN KEY ("parent_id") REFERENCES "files"("id") ON DELETE CASCADE ON UPDATE CASCADE;
105
+
106
+ -- AddForeignKey
107
+ ALTER TABLE "files" ADD CONSTRAINT "files_users_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
api/prisma/migrations/20220525012308_add_password_files/migration.sql ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ -- AlterTable
2
+ ALTER TABLE "files" ADD COLUMN "password" VARCHAR;
api/prisma/migrations/migration_lock.toml ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Please do not edit this file manually
2
+ # It should be added in your version-control system (i.e. Git)
3
+ provider = "postgresql"
api/prisma/schema.prisma ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ generator client {
2
+ provider = "prisma-client-js"
3
+ }
4
+
5
+ datasource db {
6
+ provider = "postgresql"
7
+ url = env("DATABASE_URL")
8
+ }
9
+
10
+ /// The underlying table does not contain a valid unique identifier and can therefore currently not be handled by the Prisma Client.
11
+ model config {
12
+ created_at DateTime @default(now()) @db.Timestamptz(6)
13
+ updated_at DateTime @default(now()) @db.Timestamptz(6)
14
+ id String @id(map: "pk_af2ddc24176f1572cbdd4b45992") @default(dbgenerated("uuid_generate_v4()")) @db.Uuid
15
+ invitation_code String? @db.VarChar
16
+ disable_signup Boolean @default(false)
17
+ allow_server_storage_use Boolean @default(false)
18
+ }
19
+
20
+ model files {
21
+ created_at DateTime @default(now()) @db.Timestamptz(6)
22
+ updated_at DateTime @default(now()) @db.Timestamptz(6)
23
+ id String @id(map: "PK_6c16b9093a142e0e7613b04a3d9") @default(dbgenerated("uuid_generate_v4()")) @db.Uuid
24
+ name String @db.VarChar
25
+ type String? @db.VarChar
26
+ message_id String? @db.VarChar
27
+ mime_type String? @db.VarChar
28
+ size BigInt?
29
+ uploaded_at DateTime? @db.Timestamptz(6)
30
+ upload_progress Float?
31
+ user_id String @db.Uuid
32
+ parent_id String? @db.Uuid
33
+ deleted_at DateTime? @db.Timestamptz(6)
34
+ sharing_options String[] @db.VarChar
35
+ signed_key String? @db.VarChar
36
+ file_id String? @db.VarChar
37
+ link_id String? @db.Uuid
38
+ forward_info String? @db.VarChar
39
+ link files? @relation("filesTofiles_link_id", fields: [link_id], references: [id], onDelete: Cascade, map: "files_links_fkey")
40
+ parent files? @relation("filesTofiles_parent_id", fields: [parent_id], references: [id], onDelete: Cascade, map: "files_files_fkey")
41
+ users users @relation(fields: [user_id], references: [id], onDelete: Cascade, map: "files_users_fkey")
42
+ links files[] @relation("filesTofiles_link_id")
43
+ parents files[] @relation("filesTofiles_parent_id")
44
+ password String? @db.VarChar
45
+
46
+ @@index([link_id])
47
+ @@index([message_id])
48
+ @@index([parent_id])
49
+ @@index([user_id])
50
+ }
51
+
52
+ model rate_limits {
53
+ key String @id @db.VarChar(255)
54
+ points Int @default(0)
55
+ expire BigInt?
56
+ }
57
+
58
+ model usages {
59
+ created_at DateTime @default(now()) @db.Timestamptz(6)
60
+ updated_at DateTime @default(now()) @db.Timestamptz(6)
61
+ key String @id(map: "PK_7d8e95b6dd4c0e87cad4972da13") @db.VarChar
62
+ usage BigInt
63
+ expire DateTime @db.Timestamptz(6)
64
+ }
65
+
66
+ model users {
67
+ created_at DateTime @default(now()) @db.Timestamptz(6)
68
+ updated_at DateTime @default(now()) @db.Timestamptz(6)
69
+ id String @id(map: "PK_a3ffb1c0c8416b9fc6f907b7433") @default(dbgenerated("uuid_generate_v4()")) @db.Uuid
70
+ username String @db.VarChar
71
+ name String? @db.VarChar
72
+ email String? @db.VarChar
73
+ tg_id String? @db.VarChar
74
+ plan String? @db.VarChar
75
+ settings Json?
76
+ role String? @db.VarChar
77
+ files files[]
78
+
79
+ @@index([tg_id], map: "tg_id")
80
+ }
81
+
82
+ model waitings {
83
+ created_at DateTime @default(now()) @db.Timestamptz(6)
84
+ updated_at DateTime @default(now()) @db.Timestamptz(6)
85
+ id String @id(map: "PK_f0cfe98441cf0fb92db66ae71c4") @default(dbgenerated("uuid_generate_v4()")) @db.Uuid
86
+ email String @db.VarChar
87
+ }
api/src/Types.ts ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { users } from '@prisma/client'
2
+ import { TelegramClient } from 'telegram'
3
+
4
+ declare module 'http' {
5
+ interface IncomingMessage {
6
+ tg?: TelegramClient,
7
+ user?: users,
8
+ userAuth?: any,
9
+ authKey?: string
10
+ }
11
+ }
api/src/api/base/Endpoint.ts ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NextFunction, Request, RequestHandler, Response, Router } from 'express'
2
+ import { serializeError } from 'serialize-error'
3
+
4
+ interface RouteOptions {
5
+ path?: string,
6
+ middlewares?: RequestHandler[]
7
+ }
8
+
9
+ interface Route {
10
+ method: string,
11
+ basepath: string,
12
+ middlewares?: RequestHandler[],
13
+ path: string,
14
+ handler: RequestHandler
15
+ }
16
+
17
+ export const Endpoint = {
18
+ _handlers: [],
19
+ register: function (..._classes: any[]): Router {
20
+ const router = Router()
21
+ for (const route of this._handlers?.filter((handler: Route) => !!handler.basepath)) {
22
+ router[route.method](`${route.basepath}${route.path}`,
23
+ ...(route.middlewares || []).map((middleware: RequestHandler) => this.RequestWrapper(middleware)), route.handler)
24
+ }
25
+ return router
26
+ },
27
+ API: function (basepath?: string): any {
28
+ return (cls: new () => any): void => {
29
+ this._handlers = this._handlers.map((handler: Route) => ({
30
+ ...handler,
31
+ basepath: handler.basepath || basepath || `/${cls.name[0].toLowerCase()}${cls.name.slice(1)}`
32
+ }))
33
+ }
34
+ },
35
+ USE: function (...args: [(string | RouteOptions)?, RouteOptions?]): any {
36
+ return (_: any, method: string, descriptor: PropertyDescriptor): void => {
37
+ this._handlers.push(this._buildRouteHandler('use', method, descriptor, ...args))
38
+ }
39
+ },
40
+ GET: function (...args: [(string | RouteOptions)?, RouteOptions?]): any {
41
+ return (_: any, method: string, descriptor: PropertyDescriptor): void => {
42
+ this._handlers.push(this._buildRouteHandler('get', method, descriptor, ...args))
43
+ }
44
+ },
45
+ HEAD: function (...args: [(string | RouteOptions)?, RouteOptions?]): any {
46
+ return (_: any, method: string, descriptor: PropertyDescriptor): void => {
47
+ this._handlers.push(this._buildRouteHandler('head', method, descriptor, ...args))
48
+ }
49
+ },
50
+ POST: function (...args: [(string | RouteOptions)?, RouteOptions?]): any {
51
+ return (_: any, method: string, descriptor: PropertyDescriptor): void => {
52
+ this._handlers.push(this._buildRouteHandler('post', method, descriptor, ...args))
53
+ }
54
+ },
55
+ PATCH: function (...args: [(string | RouteOptions)?, RouteOptions?]): any {
56
+ return (_: any, method: string, descriptor: PropertyDescriptor): void => {
57
+ this._handlers.push(this._buildRouteHandler('patch', method, descriptor, ...args))
58
+ }
59
+ },
60
+ PUT: function (...args: [(string | RouteOptions)?, RouteOptions?]): any {
61
+ return (_: any, method: string, descriptor: PropertyDescriptor): void => {
62
+ this._handlers.push(this._buildRouteHandler('put', method, descriptor, ...args))
63
+ }
64
+ },
65
+ DELETE: function (...args: [(string | RouteOptions)?, RouteOptions?]): any {
66
+ return (_: any, method: string, descriptor: PropertyDescriptor): void => {
67
+ this._handlers.push(this._buildRouteHandler('delete', method, descriptor, ...args))
68
+ }
69
+ },
70
+ RequestWrapper: (target: RequestHandler): RequestHandler => {
71
+ return async function (req: Request, res: Response, next: NextFunction) {
72
+ let trial = 0
73
+ const execute = async () => {
74
+ try {
75
+ return await target(req, res, next)
76
+ } catch (error) {
77
+ if (/.*You need to call \.connect\(\)/gi.test(error.message) && trial < 5) {
78
+ await new Promise(res => setTimeout(res, ++trial * 1000))
79
+ req.tg?.connect()
80
+ return await execute()
81
+ }
82
+ if (process.env.ENV !== 'production') {
83
+ console.error('RequestWrapper', error)
84
+ }
85
+ req.tg?.disconnect()
86
+ const isValidCode = error.code && Number(error.code) > 99 && Number(error.code) < 599
87
+ return next(error.code ? {
88
+ status: isValidCode ? error.code : 500, body: {
89
+ error: error.message, details: serializeError(error)
90
+ }
91
+ } : error)
92
+ }
93
+ }
94
+ return await execute()
95
+ }
96
+ },
97
+ _buildRouteHandler: function (method: string, route: string, descriptor: PropertyDescriptor, ...args: [(string | RouteOptions)?, RouteOptions?]): Route {
98
+ // get path
99
+ let path = `/${route[0].toLowerCase()}${route.slice(1)}`
100
+ if (args[0]) {
101
+ if (typeof args[0] === 'string') {
102
+ path = args[0]
103
+ } else if (args[0]?.path) {
104
+ path = args[0].path
105
+ }
106
+ } else if (args[1]?.path) {
107
+ path = args[1].path
108
+ }
109
+
110
+ // build opts
111
+ let opts: RouteOptions = {}
112
+ if (args[0] && typeof args[0] === 'object') {
113
+ opts = args[0] as RouteOptions
114
+ } else if (args[1]) {
115
+ opts = args[1] as RouteOptions
116
+ }
117
+
118
+ return {
119
+ ...opts,
120
+ method,
121
+ basepath: null,
122
+ path,
123
+ handler: async function (req: Request, res: Response, next: NextFunction) {
124
+ let trial = 0
125
+ const execute = async () => {
126
+ try {
127
+ await descriptor.value(req, res, next)
128
+ req.tg?.disconnect()
129
+ } catch (error) {
130
+ if (/.*You need to call \.connect\(\)/gi.test(error.message) && trial < 5) {
131
+ await new Promise(res => setTimeout(res, ++trial * 1000))
132
+ req.tg?.connect()
133
+ return await execute()
134
+ }
135
+ if (process.env.ENV !== 'production') {
136
+ console.error('handler', error.message)
137
+ }
138
+ req.tg?.disconnect()
139
+ const isValidCode = error.code && Number(error.code) > 99 && Number(error.code) < 599
140
+ return next(error.code ? {
141
+ status: isValidCode ? error.code : 500, body: {
142
+ error: error.message, details: serializeError(error)
143
+ }
144
+ } : error)
145
+ }
146
+ }
147
+ return await execute()
148
+ }
149
+ }
150
+ }
151
+ }
api/src/api/index.ts ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ import { Router } from 'express'
2
+ import { V1 } from './v1'
3
+
4
+ export const API = Router()
5
+ .use('/v1', V1)
api/src/api/middlewares/Auth.ts ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NextFunction, Request, Response } from 'express'
2
+ import { verify } from 'jsonwebtoken'
3
+ import { Logger, TelegramClient } from 'telegram'
4
+ import { LogLevel } from 'telegram/extensions/Logger'
5
+ import { StringSession } from 'telegram/sessions'
6
+ import { prisma } from '../../model'
7
+ import { Redis } from '../../service/Cache'
8
+ import { API_JWT_SECRET, CONNECTION_RETRIES, TG_CREDS } from '../../utils/Constant'
9
+
10
+ export async function Auth(req: Request, _: Response, next: NextFunction): Promise<any> {
11
+ const authkey = (req.headers.authorization || req.cookies.authorization)?.replace(/^Bearer\ /gi, '')
12
+ if (!authkey) {
13
+ throw { status: 401, body: { error: 'Auth key is required' } }
14
+ }
15
+
16
+ let data: { session: string }
17
+ try {
18
+ data = verify(authkey, API_JWT_SECRET) as { session: string }
19
+ } catch (error) {
20
+ throw { status: 401, body: { error: 'Access token is invalid' } }
21
+ }
22
+
23
+ try {
24
+ const session = new StringSession(data.session)
25
+ req.tg = new TelegramClient(session, TG_CREDS.apiId, TG_CREDS.apiHash, {
26
+ connectionRetries: CONNECTION_RETRIES,
27
+ useWSS: false,
28
+ ...process.env.ENV === 'production' ? { baseLogger: new Logger(LogLevel.NONE) } : {}
29
+ })
30
+ } catch (error) {
31
+ throw { status: 401, body: { error: 'Invalid key' } }
32
+ }
33
+ await req.tg.connect()
34
+ req.authKey = authkey
35
+
36
+ const [userAuth, user] = await Redis.connect().getFromCacheFirst(`auth:${authkey}`, async () => {
37
+ let userAuth: any
38
+ try {
39
+ userAuth = await req.tg.getMe()
40
+ } catch (error) {
41
+ try {
42
+ await new Promise((resolve) => setTimeout(resolve, 2000))
43
+ await req.tg.connect()
44
+ userAuth = await req.tg.getMe()
45
+ } catch (error) {
46
+ await new Promise((resolve) => setTimeout(resolve, 2000))
47
+ await req.tg.connect()
48
+ userAuth = await req.tg.getMe()
49
+ }
50
+ }
51
+
52
+ const user = await prisma.users.findFirst({ where: { tg_id: userAuth['id'].toString() } })
53
+ if (!user) {
54
+ throw { status: 401, body: { error: 'User not found' } }
55
+ }
56
+ return [userAuth, user]
57
+ }, 54000)
58
+
59
+ req.user = user
60
+ req.userAuth = userAuth
61
+
62
+ return next()
63
+ }
64
+
65
+ export async function AuthMaybe(req: Request, _: Response, next: NextFunction): Promise<any> {
66
+ const authkey = (req.headers.authorization || req.cookies.authorization)?.replace(/^Bearer\ /gi, '')
67
+ if (authkey) {
68
+ let data: { session: string }
69
+ try {
70
+ data = verify(authkey, API_JWT_SECRET) as { session: string }
71
+ } catch (error) {
72
+ // throw { status: 401, body: { error: 'Access token is invalid' } }
73
+ return next()
74
+ }
75
+
76
+ try {
77
+ const session = new StringSession(data.session)
78
+ req.tg = new TelegramClient(session, TG_CREDS.apiId, TG_CREDS.apiHash, {
79
+ connectionRetries: CONNECTION_RETRIES,
80
+ useWSS: false,
81
+ ...process.env.ENV === 'production' ? { baseLogger: new Logger(LogLevel.NONE) } : {}
82
+ })
83
+ } catch (error) {
84
+ // throw { status: 401, body: { error: 'Invalid key' } }
85
+ return next()
86
+ }
87
+ await req.tg.connect()
88
+ req.authKey = authkey
89
+
90
+ const [userAuth, user] = await Redis.connect().getFromCacheFirst(`auth:${authkey}`, async () => {
91
+ let userAuth: any = null
92
+ try {
93
+ userAuth = await req.tg.getMe()
94
+ } catch (error) {
95
+ try {
96
+ await new Promise((resolve) => setTimeout(resolve, 2000))
97
+ await req.tg.connect()
98
+ userAuth = await req.tg.getMe()
99
+ } catch (error) {
100
+ await new Promise((resolve) => setTimeout(resolve, 2000))
101
+ await req.tg.connect()
102
+ userAuth = await req.tg.getMe()
103
+ }
104
+ }
105
+
106
+ const user = await prisma.users.findFirst({ where: { tg_id: userAuth['id'].toString() } })
107
+ if (!user) {
108
+ // throw { status: 401, body: { error: 'User not found' } }
109
+ return [userAuth, null]
110
+ }
111
+ return [userAuth, user]
112
+ }, 54000)
113
+
114
+ req.user = user
115
+ req.userAuth = userAuth
116
+ }
117
+
118
+ return next()
119
+ }
api/src/api/middlewares/Key.ts ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NextFunction, Request, Response } from 'express'
2
+
3
+ export async function AuthKey(req: Request, _: Response, next: NextFunction): Promise<any> {
4
+ const authkey = req.headers['token'] || req.query['token']
5
+ if (authkey !== process.env.UTILS_API_KEY) {
6
+ throw { status: 401, body: { error: 'Invalid key' } }
7
+ }
8
+
9
+ return next()
10
+ }
api/src/api/middlewares/TGClient.ts ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Logger, TelegramClient } from 'telegram'
2
+ import { LogLevel } from 'telegram/extensions/Logger'
3
+ import { StringSession } from 'telegram/sessions'
4
+ import { NextFunction, Request, Response } from 'express'
5
+ import { CONNECTION_RETRIES, TG_CREDS } from '../../utils/Constant'
6
+
7
+ export async function TGClient(req: Request, _: Response, next: NextFunction): Promise<any> {
8
+ const session = new StringSession('')
9
+ req.tg = new TelegramClient(session, TG_CREDS.apiId, TG_CREDS.apiHash, {
10
+ connectionRetries: CONNECTION_RETRIES,
11
+ useWSS: false,
12
+ ...process.env.ENV === 'production' ? { baseLogger: new Logger(LogLevel.NONE) } : {}
13
+ })
14
+ return next()
15
+ }
api/src/api/middlewares/TGSessionAuth.ts ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NextFunction, Request, Response } from 'express'
2
+ import { verify } from 'jsonwebtoken'
3
+ import { Logger, TelegramClient } from 'telegram'
4
+ import { LogLevel } from 'telegram/extensions/Logger'
5
+ import { StringSession } from 'telegram/sessions'
6
+ import { API_JWT_SECRET, CONNECTION_RETRIES, TG_CREDS } from '../../utils/Constant'
7
+
8
+ export async function TGSessionAuth(req: Request, _: Response, next: NextFunction): Promise<any> {
9
+ const authkey = (req.headers.authorization || req.cookies.authorization)?.replace(/^Bearer\ /gi, '')
10
+ if (!authkey) {
11
+ throw { status: 401, body: { error: 'Auth key is required' } }
12
+ }
13
+
14
+ let data: { session: string }
15
+ try {
16
+ data = verify(authkey, API_JWT_SECRET) as { session: string }
17
+ } catch (error) {
18
+ throw { status: 401, body: { error: 'Access token is invalid' } }
19
+ }
20
+
21
+ try {
22
+ const session = new StringSession(data.session)
23
+ req.tg = new TelegramClient(session, TG_CREDS.apiId, TG_CREDS.apiHash, {
24
+ connectionRetries: CONNECTION_RETRIES,
25
+ useWSS: false,
26
+ ...process.env.ENV === 'production' ? { baseLogger: new Logger(LogLevel.NONE) } : {}
27
+ })
28
+ } catch (error) {
29
+ throw { status: 401, body: { error: 'Invalid key' } }
30
+ }
31
+ return next()
32
+ }
api/src/api/v1/Auth.ts ADDED
@@ -0,0 +1,468 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { AES } from 'crypto-js'
2
+ import { Request, Response } from 'express'
3
+ import { sign, verify } from 'jsonwebtoken'
4
+ import { serializeError } from 'serialize-error'
5
+ import { Api, Logger, TelegramClient } from 'telegram'
6
+ import { LogLevel } from 'telegram/extensions/Logger'
7
+ import { generateRandomBytes } from 'telegram/Helpers'
8
+ import { computeCheck } from 'telegram/Password'
9
+ import { StringSession } from 'telegram/sessions'
10
+ import { prisma } from '../../model'
11
+ import { Redis } from '../../service/Cache'
12
+ import { API_JWT_SECRET, CONNECTION_RETRIES, COOKIE_AGE, FILES_JWT_SECRET, TG_CREDS } from '../../utils/Constant'
13
+ import { Endpoint } from '../base/Endpoint'
14
+ import { TGClient } from '../middlewares/TGClient'
15
+ import { TGSessionAuth } from '../middlewares/TGSessionAuth'
16
+
17
+ @Endpoint.API()
18
+ export class Auth {
19
+
20
+ @Endpoint.POST({ middlewares: [TGClient] })
21
+ public async sendCode(req: Request, res: Response): Promise<any> {
22
+ const { phoneNumber } = req.body
23
+ if (!phoneNumber) {
24
+ throw { status: 400, body: { error: 'Phone number is required' } }
25
+ }
26
+
27
+ await req.tg.connect()
28
+ const { phoneCodeHash, timeout } = await req.tg.invoke(new Api.auth.SendCode({
29
+ ...TG_CREDS,
30
+ phoneNumber,
31
+ settings: new Api.CodeSettings({
32
+ allowFlashcall: true,
33
+ currentNumber: true,
34
+ allowAppHash: true,
35
+ })
36
+ }))
37
+ const session = req.tg.session.save()
38
+ const accessToken = sign({ session }, API_JWT_SECRET, { expiresIn: '3h' })
39
+ return res.cookie('authorization', `Bearer ${accessToken}`)
40
+ .send({ phoneCodeHash, timeout, accessToken })
41
+ }
42
+
43
+ @Endpoint.POST({ middlewares: [TGSessionAuth] })
44
+ public async reSendCode(req: Request, res: Response): Promise<any> {
45
+ const { phoneNumber, phoneCodeHash } = req.body
46
+ if (!phoneNumber || !phoneCodeHash) {
47
+ throw { status: 400, body: { error: 'Phone number and phone code hash are required' } }
48
+ }
49
+
50
+ await req.tg.connect()
51
+ const { phoneCodeHash: newPhoneCodeHash, timeout } = await req.tg.invoke(new Api.auth.ResendCode({
52
+ phoneNumber, phoneCodeHash }))
53
+ const session = req.tg.session.save()
54
+ const accessToken = sign({ session }, API_JWT_SECRET, { expiresIn: '3h' })
55
+ return res.cookie('authorization', `Bearer ${accessToken}`)
56
+ .send({ phoneCodeHash: newPhoneCodeHash, timeout, accessToken })
57
+ }
58
+
59
+ @Endpoint.POST({ middlewares: [TGSessionAuth] })
60
+ public async login(req: Request, res: Response): Promise<any> {
61
+ const { phoneNumber, phoneCode, phoneCodeHash, password, invitationCode } = req.body
62
+ if ((!phoneNumber || !phoneCode || !phoneCodeHash) && !password) {
63
+ if (!password) {
64
+ throw { status: 400, body: { error: 'Password is required' } }
65
+ }
66
+ throw { status: 400, body: { error: 'Phone number, phone code, and phone code hash are required' } }
67
+ }
68
+
69
+ await req.tg.connect()
70
+ let signIn: any
71
+ if (password) {
72
+ const data = await req.tg.invoke(new Api.account.GetPassword())
73
+ data.newAlgo['salt1'] = Buffer.concat([data.newAlgo['salt1'], generateRandomBytes(32)])
74
+ signIn = await req.tg.invoke(new Api.auth.CheckPassword({ password: await computeCheck(data, password) }))
75
+ } else {
76
+ signIn = await req.tg.invoke(new Api.auth.SignIn({ phoneNumber, phoneCode, phoneCodeHash }))
77
+ }
78
+ const userAuth = signIn['user']
79
+ if (!userAuth) {
80
+ throw { status: 400, body: { error: 'User not found/authorized' } }
81
+ }
82
+
83
+ let user = await prisma.users.findFirst({ where: { tg_id: userAuth.id.toString() } })
84
+ const config = await prisma.config.findFirst()
85
+ const username = userAuth.username || userAuth.phone || phoneNumber
86
+ if (!user) {
87
+ if (config?.disable_signup) {
88
+ throw { status: 403, body: { error: 'Signup is disabled' } }
89
+ }
90
+
91
+ if (config?.invitation_code && config?.invitation_code !== invitationCode) {
92
+ throw { status: 403, body: { error: 'Invalid invitation code' } }
93
+ }
94
+
95
+ user = await prisma.users.create({
96
+ data: {
97
+ username,
98
+ plan: 'premium',
99
+ name: `${userAuth.firstName || ''} ${userAuth.lastName || ''}`.trim() || username,
100
+ tg_id: userAuth.id.toString()
101
+ }
102
+ })
103
+ }
104
+ await prisma.users.update({
105
+ data: {
106
+ username,
107
+ plan: 'premium'
108
+ },
109
+ where: { id: user.id }
110
+ })
111
+
112
+ const session = req.tg.session.save()
113
+ const auth = {
114
+ session,
115
+ accessToken: sign({ session }, API_JWT_SECRET, { expiresIn: '15h' }),
116
+ refreshToken: sign({ session }, API_JWT_SECRET, { expiresIn: '1y' }),
117
+ expiredAfter: Date.now() + COOKIE_AGE
118
+ }
119
+
120
+ res
121
+ .cookie('authorization', `Bearer ${auth.accessToken}`, { maxAge: COOKIE_AGE, expires: new Date(auth.expiredAfter) })
122
+ .cookie('refreshToken', auth.refreshToken, { maxAge: 3.154e+10, expires: new Date(Date.now() + 3.154e+10) })
123
+ .send({ user, ...auth })
124
+
125
+ // sync all shared files in background, if any
126
+ prisma.files.findMany({
127
+ where: {
128
+ AND: [
129
+ { user_id: user.id },
130
+ {
131
+ NOT: { signed_key: null }
132
+ }
133
+ ]
134
+ }
135
+ }).then(files => files?.map(file => {
136
+ const signedKey = AES.encrypt(JSON.stringify({ file: { id: file.id }, session: req.tg.session.save() }), FILES_JWT_SECRET).toString()
137
+ prisma.files.update({
138
+ data: { signed_key: signedKey },
139
+ where: { id: file.id }
140
+ })
141
+ }))
142
+ }
143
+
144
+ @Endpoint.POST()
145
+ public async refreshToken(req: Request, res: Response): Promise<any> {
146
+ const refreshToken = req.body?.refreshToken || req.cookies?.refreshToken
147
+ if (!refreshToken) {
148
+ throw { status: 400, body: { error: 'Refresh token is required' } }
149
+ }
150
+
151
+ let data: { session: string }
152
+ try {
153
+ data = verify(refreshToken, API_JWT_SECRET) as { session: string }
154
+ } catch (error) {
155
+ throw { status: 400, body: { error: 'Refresh token is invalid' } }
156
+ }
157
+
158
+ try {
159
+ const session = new StringSession(data.session)
160
+ req.tg = new TelegramClient(session, TG_CREDS.apiId, TG_CREDS.apiHash, {
161
+ connectionRetries: CONNECTION_RETRIES,
162
+ useWSS: false,
163
+ ...process.env.ENV === 'production' ? { baseLogger: new Logger(LogLevel.NONE) } : {}
164
+ })
165
+ } catch (error) {
166
+ throw { status: 400, body: { error: 'Invalid key' } }
167
+ }
168
+
169
+ try {
170
+ await req.tg.connect()
171
+ const userAuth = await req.tg.getMe()
172
+ const user = await prisma.users.findFirst({ where: { tg_id: userAuth['id'].toString() } })
173
+ if (!user) {
174
+ throw { status: 404, body: { error: 'User not found' } }
175
+ }
176
+ await prisma.users.update({
177
+ data: {
178
+ username: req.userAuth?.username || req.userAuth?.phone || user.username,
179
+ plan: 'premium'
180
+ },
181
+ where: { id: user.id }
182
+ })
183
+
184
+ const session = req.tg.session.save()
185
+ const auth = {
186
+ session,
187
+ accessToken: sign({ session }, API_JWT_SECRET, { expiresIn: '15h' }),
188
+ refreshToken: sign({ session }, API_JWT_SECRET, { expiresIn: '100y' }),
189
+ expiredAfter: Date.now() + COOKIE_AGE
190
+ }
191
+ return res
192
+ .cookie('authorization', `Bearer ${auth.accessToken}`, { maxAge: COOKIE_AGE, expires: new Date(auth.expiredAfter) })
193
+ .cookie('refreshToken', auth.refreshToken, { maxAge: 3.154e+10, expires: new Date(Date.now() + 3.154e+10) })
194
+ .send({ user, ...auth })
195
+ } catch (error) {
196
+ throw { status: 400, body: { error: error.message || 'Something error', details: serializeError(error) } }
197
+ }
198
+ }
199
+
200
+ /**
201
+ * Initialize export login token to be a param for URL tg://login?token={{token}}
202
+ * @param req
203
+ * @param res
204
+ * @returns
205
+ */
206
+ @Endpoint.GET({ middlewares: [TGClient] })
207
+ public async qrCode(req: Request, res: Response): Promise<any> {
208
+ await req.tg.connect()
209
+ const data = await req.tg.invoke(new Api.auth.ExportLoginToken({
210
+ ...TG_CREDS,
211
+ exceptIds: []
212
+ }))
213
+
214
+ const session = req.tg.session.save()
215
+ const auth = {
216
+ session,
217
+ accessToken: sign({ session }, API_JWT_SECRET, { expiresIn: '15h' }),
218
+ refreshToken: sign({ session }, API_JWT_SECRET, { expiresIn: '100y' }),
219
+ expiredAfter: Date.now() + COOKIE_AGE
220
+ }
221
+ return res
222
+ .cookie('authorization', `Bearer ${auth.accessToken}`, { maxAge: COOKIE_AGE, expires: new Date(auth.expiredAfter) })
223
+ .cookie('refreshToken', auth.refreshToken, { maxAge: 3.154e+10, expires: new Date(Date.now() + 3.154e+10) })
224
+ .send({ loginToken: Buffer.from(data['token'], 'utf8').toString('base64url'), accessToken: auth.accessToken })
225
+ }
226
+
227
+ /**
228
+ * Sign in process with QR Code https://core.telegram.org/api/qr-login
229
+ * @param req
230
+ * @param res
231
+ * @returns
232
+ */
233
+ @Endpoint.POST({ middlewares: [TGSessionAuth] })
234
+ public async qrCodeSignIn(req: Request, res: Response): Promise<any> {
235
+ const { password, session: sessionString, invitationCode } = req.body
236
+
237
+ // handle the 2fa password in the second call
238
+ if (password && sessionString) {
239
+ req.tg = new TelegramClient(new StringSession(sessionString), TG_CREDS.apiId, TG_CREDS.apiHash, {
240
+ connectionRetries: CONNECTION_RETRIES,
241
+ useWSS: false,
242
+ ...process.env.ENV === 'production' ? { baseLogger: new Logger(LogLevel.NONE) } : {}
243
+ })
244
+ await req.tg.connect()
245
+
246
+ const passwordData = await req.tg.invoke(new Api.account.GetPassword())
247
+
248
+ passwordData.newAlgo['salt1'] = Buffer.concat([passwordData.newAlgo['salt1'], generateRandomBytes(32)])
249
+ const signIn = await req.tg.invoke(new Api.auth.CheckPassword({
250
+ password: await computeCheck(passwordData, password)
251
+ }))
252
+ const userAuth = signIn['user']
253
+ if (!userAuth) {
254
+ throw { status: 400, body: { error: 'User not found/authorized' } }
255
+ }
256
+
257
+ let user = await prisma.users.findFirst({ where: { tg_id: userAuth.id.toString() } })
258
+ const config = await prisma.config.findFirst()
259
+ if (!user) {
260
+ if (config?.disable_signup) {
261
+ throw { status: 403, body: { error: 'Signup is disabled' } }
262
+ }
263
+
264
+ if (config?.invitation_code && config?.invitation_code !== invitationCode) {
265
+ throw { status: 403, body: { error: 'Invalid invitation code' } }
266
+ }
267
+
268
+ const username = userAuth.username || userAuth.phone
269
+ user = await prisma.users.create({
270
+ data: {
271
+ username,
272
+ plan: 'premium',
273
+ name: `${userAuth.firstName || ''} ${userAuth.lastName || ''}`.trim() || username,
274
+ tg_id: userAuth.id.toString()
275
+ }
276
+ })
277
+ }
278
+
279
+ await prisma.users.update({
280
+ data: {
281
+ username: userAuth.username || userAuth.phone,
282
+ plan: 'premium'
283
+ },
284
+ where: { id: user.id }
285
+ })
286
+
287
+
288
+ const session = req.tg.session.save()
289
+ const auth = {
290
+ session,
291
+ accessToken: sign({ session }, API_JWT_SECRET, { expiresIn: '15h' }),
292
+ refreshToken: sign({ session }, API_JWT_SECRET, { expiresIn: '1y' }),
293
+ expiredAfter: Date.now() + COOKIE_AGE
294
+ }
295
+
296
+ res
297
+ .cookie('authorization', `Bearer ${auth.accessToken}`, { maxAge: COOKIE_AGE, expires: new Date(auth.expiredAfter) })
298
+ .cookie('refreshToken', auth.refreshToken, { maxAge: 3.154e+10, expires: new Date(Date.now() + 3.154e+10) })
299
+ .send({ user, ...auth })
300
+
301
+ // sync all shared files in background, if any
302
+ prisma.files.findMany({
303
+ where: {
304
+ AND: [
305
+ { user_id: user.id },
306
+ {
307
+ NOT: { signed_key: null }
308
+ }
309
+ ]
310
+ }
311
+ }).then(files => files?.map(file => {
312
+ const signedKey = AES.encrypt(JSON.stringify({ file: { id: file.id }, session: req.tg.session.save() }), FILES_JWT_SECRET).toString()
313
+ prisma.files.update({
314
+ data: { signed_key: signedKey },
315
+ where: { id: file.id }
316
+ })
317
+ }))
318
+ return
319
+ }
320
+
321
+ // handle the second call for export login token, result case: success, need to migrate to other dc, or 2fa
322
+ await req.tg.connect()
323
+ try {
324
+ const data = await req.tg.invoke(new Api.auth.ExportLoginToken({
325
+ ...TG_CREDS,
326
+ exceptIds: []
327
+ }))
328
+
329
+ // build response with user data and auth data
330
+ const buildResponse = (data: Record<string, any> & { user?: { id: string } })=> {
331
+ const session = req.tg.session.save()
332
+ const auth = {
333
+ session,
334
+ accessToken: sign({ session }, API_JWT_SECRET, { expiresIn: '15h' }),
335
+ refreshToken: sign({ session }, API_JWT_SECRET, { expiresIn: '1y' }),
336
+ expiredAfter: Date.now() + COOKIE_AGE
337
+ }
338
+ res
339
+ .cookie('authorization', `Bearer ${auth.accessToken}`, { maxAge: COOKIE_AGE, expires: new Date(auth.expiredAfter) })
340
+ .cookie('refreshToken', auth.refreshToken, { maxAge: 3.154e+10, expires: new Date(Date.now() + 3.154e+10) })
341
+ .send({ ...data, ...auth })
342
+
343
+ if (data.user?.id) {
344
+ // sync all shared files in background, if any
345
+ prisma.files.findMany({
346
+ where: {
347
+ AND: [
348
+ { user_id: data.user.id },
349
+ {
350
+ NOT: { signed_key: null }
351
+ }
352
+ ]
353
+ }
354
+ }).then(files => files?.map(file => {
355
+ const signedKey = AES.encrypt(JSON.stringify({ file: { id: file.id }, session: req.tg.session.save() }), FILES_JWT_SECRET).toString()
356
+ prisma.files.update({
357
+ data: { signed_key: signedKey },
358
+ where: { id: file.id }
359
+ })
360
+ }))
361
+ }
362
+ return
363
+ }
364
+
365
+ // handle to switch dc
366
+ if (data instanceof Api.auth.LoginTokenMigrateTo) {
367
+ await req.tg._switchDC(data.dcId)
368
+ const result = await req.tg.invoke(new Api.auth.ImportLoginToken({
369
+ token: data.token
370
+ }))
371
+
372
+ // result import login token success
373
+ if (result instanceof Api.auth.LoginTokenSuccess && result.authorization instanceof Api.auth.Authorization) {
374
+ const userAuth = result.authorization.user
375
+ let user = await prisma.users.findFirst({ where: { tg_id: userAuth.id.toString() } })
376
+ const config = await prisma.config.findFirst()
377
+ if (!user) {
378
+ if (config?.disable_signup) {
379
+ throw { status: 403, body: { error: 'Signup is disabled' } }
380
+ }
381
+
382
+ if (config?.invitation_code && config?.invitation_code !== invitationCode) {
383
+ throw { status: 403, body: { error: 'Invalid invitation code' } }
384
+ }
385
+
386
+ const username = userAuth['username'] || userAuth['phone']
387
+ user = await prisma.users.create({
388
+ data: {
389
+ username,
390
+ plan: 'premium',
391
+ name: `${userAuth['firstName'] || ''} ${userAuth['lastName'] || ''}`.trim() || username,
392
+ tg_id: userAuth.id.toString()
393
+ }
394
+ })
395
+ }
396
+ await prisma.users.update({
397
+ data: {
398
+ username: userAuth['username'] || userAuth['phone'],
399
+ plan: 'premium'
400
+ },
401
+ where: { id: user.id }
402
+ })
403
+ return buildResponse({ user })
404
+ }
405
+ return buildResponse({ data, result })
406
+
407
+ // handle if success
408
+ } else if (data instanceof Api.auth.LoginTokenSuccess && data.authorization instanceof Api.auth.Authorization) {
409
+ const userAuth = data.authorization.user
410
+ let user = await prisma.users.findFirst({ where: { tg_id: userAuth.id.toString() } })
411
+ const config = await prisma.config.findFirst()
412
+ if (!user) {
413
+ if (config?.disable_signup) {
414
+ throw { status: 403, body: { error: 'Signup is disabled' } }
415
+ }
416
+
417
+ if (config?.invitation_code && config?.invitation_code !== invitationCode) {
418
+ throw { status: 403, body: { error: 'Invalid invitation code' } }
419
+ }
420
+
421
+ const username = userAuth['username'] || userAuth['phone']
422
+ user = await prisma.users.create({
423
+ data: {
424
+ username,
425
+ plan: 'premium',
426
+ name: `${userAuth['firstName'] || ''} ${userAuth['lastName'] || ''}`.trim() || username,
427
+ tg_id: userAuth.id.toString()
428
+ }
429
+ })
430
+ }
431
+ await prisma.users.update({
432
+ data: {
433
+ username: userAuth['username'] || userAuth['phone'],
434
+ plan: 'premium'
435
+ },
436
+ where: { id: user.id }
437
+ })
438
+ return buildResponse({ user })
439
+ }
440
+
441
+ // data instanceof auth.LoginToken
442
+ return buildResponse({
443
+ loginToken: Buffer.from(data['token'], 'utf8').toString('base64url')
444
+ })
445
+ } catch (error) {
446
+ // handle if need 2fa password
447
+ if (error.errorMessage === 'SESSION_PASSWORD_NEEDED') {
448
+ error.session = req.tg.session.save()
449
+ }
450
+ throw error
451
+ }
452
+ }
453
+
454
+ @Endpoint.GET({ middlewares: [TGSessionAuth] })
455
+ public async me(req: Request, res: Response): Promise<any> {
456
+ await req.tg.connect()
457
+ const data = await req.tg.getMe()
458
+ return res.send({ user: data })
459
+ }
460
+
461
+ @Endpoint.POST({ middlewares: [TGSessionAuth] })
462
+ public async logout(req: Request, res: Response): Promise<any> {
463
+ await req.tg.connect()
464
+ const success = req.query.destroySession === '1' ? await req.tg.invoke(new Api.auth.LogOut()) : true
465
+ await Redis.connect().del(`auth:${req.authKey}`)
466
+ return res.clearCookie('authorization').clearCookie('refreshToken').send({ success })
467
+ }
468
+ }
api/src/api/v1/Config.ts ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import crypto from 'crypto'
2
+ import { Request, Response } from 'express'
3
+ import { prisma } from '../../model'
4
+ import { Redis } from '../../service/Cache'
5
+ import { Endpoint } from '../base/Endpoint'
6
+ import { Auth, AuthMaybe } from '../middlewares/Auth'
7
+
8
+ @Endpoint.API()
9
+ export class Config {
10
+
11
+ @Endpoint.GET('/', { middlewares: [AuthMaybe] })
12
+ public async retrieve(req: Request, res: Response): Promise<any> {
13
+ // admin creation
14
+ let admin = await prisma.users.findFirst({ where: { role: 'admin' } })
15
+ if (!admin && process.env.ADMIN_USERNAME) {
16
+ admin = await prisma.users.findFirst({ where: { username: process.env.ADMIN_USERNAME } })
17
+ if (!admin) {
18
+ throw { status: 404, body: { error: 'Admin user not found' } }
19
+ }
20
+ await prisma.users.update({
21
+ data: {
22
+ role: 'admin'
23
+ },
24
+ where: { id: admin.id }
25
+ })
26
+ await Redis.connect().del(`auth:${req.authKey}`)
27
+ }
28
+
29
+ // get or create base config
30
+ let config = await prisma.config.findFirst()
31
+ if (!config) {
32
+ config = await prisma.config.create({
33
+ data: {
34
+ disable_signup: false,
35
+ invitation_code: null
36
+ }
37
+ })
38
+ }
39
+ return res.send({ config: {
40
+ ...config,
41
+ invitation_code: req.user?.role === 'admin' ? config.invitation_code : undefined
42
+ } })
43
+ }
44
+
45
+ @Endpoint.PATCH('/', { middlewares: [Auth] })
46
+ public async update(req: Request, res: Response): Promise<any> {
47
+ if (req.user.role !== 'admin') {
48
+ throw { status: 403, body: { error: 'Forbidden' } }
49
+ }
50
+ const { config } = req.body
51
+ if (!config) {
52
+ throw { status: 400, body: { error: 'Invalid request' } }
53
+ }
54
+ const model = await prisma.config.findFirst()
55
+ await prisma.config.update({
56
+ data: {
57
+ disable_signup: config.disable_signup,
58
+ ...config.clear_invitation_code ? { invitation_code: null } : {}
59
+ },
60
+ where: { id: model.id }
61
+ })
62
+ return res.send({ config: model })
63
+ }
64
+
65
+ @Endpoint.POST('/resetInvitationCode', { middlewares: [Auth] })
66
+ public async resetInvitationCode(req: Request, res: Response): Promise<any> {
67
+ if (req.user.role !== 'admin') {
68
+ throw { status: 403, body: { error: 'Forbidden' } }
69
+ }
70
+
71
+ const code = crypto.randomBytes(9).toString('base64url')
72
+ const model = await prisma.config.findFirst()
73
+ await prisma.config.update({
74
+ data: {
75
+ invitation_code: code
76
+ },
77
+ where: { id: model.id }
78
+ })
79
+ return res.send({ config: model })
80
+ }
81
+
82
+ @Endpoint.POST('/validateInvitationCode')
83
+ public async validateInvitationCode(req: Request, res: Response): Promise<any> {
84
+ const model = await prisma.config.findFirst()
85
+ if (!model.invitation_code) {
86
+ return res.send({ valid: true })
87
+ }
88
+ const { code } = req.query
89
+ return res.send({
90
+ valid: model.invitation_code === code
91
+ })
92
+ }
93
+ }
api/src/api/v1/Dialogs.ts ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Api } from 'telegram'
2
+ import bigInt from 'big-integer'
3
+ import { Request, Response } from 'express'
4
+ import { Redis } from '../../service/Cache'
5
+ import { objectParser } from '../../utils/ObjectParser'
6
+ import { Endpoint } from '../base/Endpoint'
7
+ import { Auth } from '../middlewares/Auth'
8
+
9
+ @Endpoint.API()
10
+ export class Dialogs {
11
+
12
+ @Endpoint.GET('/', { middlewares: [Auth] })
13
+ public async find(req: Request, res: Response): Promise<any> {
14
+ const { offset, limit } = req.query
15
+ const dialogs = await Redis.connect().getFromCacheFirst(`dialogs:${req.user.id}:${JSON.stringify(req.query)}`, async () => {
16
+ return objectParser(await req.tg.getDialogs({
17
+ limit: Number(limit) || 0,
18
+ offsetDate: Number(offset) || undefined,
19
+ ignorePinned: false
20
+ }))
21
+ }, 2)
22
+ return res.send({ dialogs })
23
+ }
24
+
25
+ @Endpoint.GET('/:type/:id', { middlewares: [Auth] })
26
+ public async retrieve(req: Request, res: Response): Promise<any> {
27
+ const { type, id } = req.params
28
+ let peer: Api.InputPeerChannel | Api.InputPeerUser | Api.InputPeerChat
29
+ if (type === 'channel') {
30
+ peer = new Api.InputPeerChannel({
31
+ channelId: bigInt(id),
32
+ accessHash: bigInt(req.query.accessHash as string) })
33
+ } else if (type === 'chat') {
34
+ peer = new Api.InputPeerChat({
35
+ chatId: bigInt(id)
36
+ })
37
+ } else if (type === 'user') {
38
+ peer = new Api.InputPeerUser({
39
+ userId: bigInt(id),
40
+ accessHash: bigInt(req.query.accessHash as string) })
41
+ }
42
+
43
+ const dialogs = await req.tg.invoke(new Api.messages.GetPeerDialogs({
44
+ peers: [new Api.InputDialogPeer({ peer })]
45
+ }))
46
+
47
+ const result = objectParser(dialogs) as any
48
+ return res.send({ dialog: {
49
+ ...result,
50
+ dialog: result.dialogs[0],
51
+ message: result.messages[0],
52
+ chat: result.chats[0],
53
+ user: result.users[0],
54
+ dialogs: undefined,
55
+ messages: undefined,
56
+ chats: undefined,
57
+ users: undefined
58
+ } })
59
+ }
60
+
61
+ @Endpoint.GET('/:type/:id/avatar.jpg', { middlewares: [Auth] })
62
+ public async avatar(req: Request, res: Response): Promise<any> {
63
+ const { type, id } = req.params
64
+ let peer: Api.InputPeerChannel | Api.InputPeerUser | Api.InputPeerChat
65
+ if (type === 'channel') {
66
+ peer = new Api.InputPeerChannel({
67
+ channelId: bigInt(id),
68
+ accessHash: bigInt(req.query.accessHash as string) })
69
+ } else if (type === 'chat') {
70
+ peer = new Api.InputPeerChat({
71
+ chatId: bigInt(id)
72
+ })
73
+ } else if (type === 'user') {
74
+ peer = new Api.InputPeerUser({
75
+ userId: bigInt(id),
76
+ accessHash: bigInt(req.query.accessHash as string) })
77
+ }
78
+ try {
79
+ const file = await req.tg.downloadProfilePhoto(peer)
80
+ if (!file?.length) {
81
+ return res.redirect('https://upload.wikimedia.org/wikipedia/commons/7/7c/Profile_avatar_placeholder_large.png')
82
+ }
83
+ res.setHeader('Content-Disposition', `inline; filename=avatar-${id}.jpg`)
84
+ res.setHeader('Content-Type', 'image/jpeg')
85
+ res.setHeader('Content-Length', file.length)
86
+ res.write(file)
87
+ return res.end()
88
+ } catch (error) {
89
+ return res.redirect('https://upload.wikimedia.org/wikipedia/commons/7/7c/Profile_avatar_placeholder_large.png')
90
+ }
91
+ }
92
+ }
api/src/api/v1/Files.ts ADDED
@@ -0,0 +1,1360 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { files, Prisma } from '@prisma/client'
2
+ import bigInt from 'big-integer'
3
+ import { compareSync, hashSync } from 'bcryptjs'
4
+ import checkDiskSpace from 'check-disk-space'
5
+ import contentDisposition from 'content-disposition'
6
+ import { AES, enc } from 'crypto-js'
7
+ import { Request, Response } from 'express'
8
+ import { appendFileSync, createReadStream, existsSync, mkdirSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'fs'
9
+ import moment from 'moment'
10
+ import multer from 'multer'
11
+ import { Api, Logger, TelegramClient } from 'telegram'
12
+ import { LogLevel } from 'telegram/extensions/Logger'
13
+ import { StringSession } from 'telegram/sessions'
14
+ import { prisma } from '../../model'
15
+ import { Redis } from '../../service/Cache'
16
+ import { CACHE_FILES_LIMIT, CONNECTION_RETRIES, FILES_JWT_SECRET, TG_CREDS } from '../../utils/Constant'
17
+ import { buildSort } from '../../utils/FilterQuery'
18
+ import { Endpoint } from '../base/Endpoint'
19
+ import { Auth, AuthMaybe } from '../middlewares/Auth'
20
+
21
+ const CACHE_DIR = `${__dirname}/../../../../.cached`
22
+
23
+ @Endpoint.API()
24
+ export class Files {
25
+
26
+ @Endpoint.GET('/', { middlewares: [AuthMaybe] })
27
+ public async find(req: Request, res: Response): Promise<any> {
28
+ const { sort, offset, limit, shared, exclude_parts: excludeParts, full_properties: fullProperties, no_cache: noCache, t: _t, ...filters } = req.query
29
+ const parent = filters?.parent_id && filters.parent_id !== 'null' ? await prisma.files.findFirst({ where: { id: filters.parent_id as string } }) : null
30
+ if (filters?.parent_id && filters.parent_id !== 'null' && !parent) {
31
+ throw { status: 404, body: { error: 'Parent not found' } }
32
+ }
33
+ if (!req.user && !parent?.sharing_options?.includes('*')) {
34
+ throw { status: 404, body: { error: 'Parent not found' } }
35
+ }
36
+
37
+ const getFiles = async (): Promise<[files[], number]> => {
38
+ let where: Record<string, any> = { user_id: req.user?.id } // 'files.user_id = :user'
39
+ if (shared) {
40
+ if (parent?.sharing_options?.includes(req.user?.username) || parent?.sharing_options?.includes('*')) {
41
+ where = {}
42
+ } else {
43
+ // :user = any(files.sharing_options) and (files.parent_id is null or parent.sharing_options is null or cardinality(parent.sharing_options) = 0 or not :user = any(parent.sharing_options))
44
+ where = {
45
+ AND: [
46
+ {
47
+ sharing_options: {
48
+ has: req.user?.username
49
+ }
50
+ },
51
+ {
52
+ OR: [
53
+ { parent_id: null },
54
+ { parent: {
55
+ sharing_options: undefined }
56
+ },
57
+ {
58
+ parent: {
59
+ sharing_options: {
60
+ isEmpty: true
61
+ }
62
+ }
63
+ },
64
+ {
65
+ NOT: {
66
+ parent: {
67
+ sharing_options: {
68
+ has: req.user?.username
69
+ }
70
+ }
71
+ }
72
+ }
73
+ ]
74
+ }
75
+ ]
76
+ }
77
+ }
78
+ }
79
+
80
+ let select = null
81
+ if (fullProperties !== 'true' && fullProperties !== '1') {
82
+ select = {
83
+ id: true,
84
+ name: true,
85
+ type: true,
86
+ size: true,
87
+ sharing_options: true,
88
+ upload_progress: true,
89
+ link_id: true,
90
+ user_id: true,
91
+ parent_id: true,
92
+ uploaded_at: true,
93
+ created_at: true,
94
+ password: true
95
+ }
96
+ }
97
+ if (shared && Object.keys(where).length) {
98
+ select['parent'] = true
99
+ }
100
+
101
+ const whereQuery: Prisma.filesWhereInput = {
102
+ AND: [
103
+ where,
104
+ ...Object.keys(filters).reduce((res, k) => {
105
+ let obj = { [k]: filters[k] }
106
+ if (filters[k] === 'null') {
107
+ obj = { [k]: null }
108
+ }
109
+ if (/\.in$/.test(k)) {
110
+ obj = { [k.replace(/\.in$/, '')]: {
111
+ in: (filters[k] as string)
112
+ .replace(/^\(/, '')
113
+ .replace(/\'/g, '')
114
+ .replace(/\)$/, '')
115
+ .split(',')
116
+ } }
117
+ }
118
+ if (/\.like$/.test(k)) {
119
+ obj = { [k.replace(/\.like$/, '')]: {
120
+ startsWith: filters[k].toString()
121
+ } }
122
+ }
123
+ return [...res, obj]
124
+ }, []),
125
+ ...excludeParts === 'true' || excludeParts === '1' ? [
126
+ {
127
+ OR: [ // (files.name ~ \'.part0*1$\' or files.name !~ \'.part[0-9]+$\')
128
+ {
129
+ AND: [
130
+ { name: { contains: '.part0' } },
131
+ { name: { endsWith: '1' } },
132
+ { NOT: { name: { endsWith: '11' } } },
133
+ { NOT: { name: { endsWith: '111' } } },
134
+ { NOT: { name: { endsWith: '1111' } } },
135
+ { NOT: { name: { endsWith: '21' } } },
136
+ { NOT: { name: { endsWith: '31' } } },
137
+ { NOT: { name: { endsWith: '41' } } },
138
+ { NOT: { name: { endsWith: '51' } } },
139
+ { NOT: { name: { endsWith: '61' } } },
140
+ { NOT: { name: { endsWith: '71' } } },
141
+ { NOT: { name: { endsWith: '81' } } },
142
+ { NOT: { name: { endsWith: '91' } } },
143
+ ]
144
+ },
145
+ {
146
+ NOT: { name: { contains: '.part' } }
147
+ }
148
+ ]
149
+ }
150
+ ] : []
151
+ ],
152
+ }
153
+ return [
154
+ await prisma.files.findMany({
155
+ ...select ? { select } : {},
156
+ where: whereQuery,
157
+ skip: Number(offset) || 0,
158
+ take: Number(limit) || 10,
159
+ orderBy: buildSort(sort as string)
160
+ }),
161
+ await prisma.files.count({ where: whereQuery })
162
+ ]
163
+ }
164
+
165
+ const [files, length] = noCache === 'true' || noCache === '1' ? await getFiles() : await Redis.connect().getFromCacheFirst(`files:${req.user?.id || 'null'}:${JSON.stringify(req.query)}`, getFiles, 2)
166
+ return res.send({ files: files.map(file => ({ ...file, password: file.password ? '[REDACTED]' : null })), length })
167
+ }
168
+
169
+ @Endpoint.GET('/stats', { middlewares: [Auth] })
170
+ public async stats(req: Request, res: Response): Promise<any> {
171
+ const totalFilesSize = await prisma.files.aggregate({
172
+ _sum: { size: true }
173
+ })
174
+ const totalUserFilesSize = await prisma.files.aggregate({
175
+ _sum: { size: true },
176
+ where: {
177
+ user_id: req.user.id
178
+ }
179
+ })
180
+
181
+ try {
182
+ mkdirSync(`${CACHE_DIR}`, { recursive: true })
183
+ } catch (error) {
184
+ // ignore
185
+ }
186
+ const cachedSize = readdirSync(`${CACHE_DIR}`)
187
+ .filter(filename => statSync(`${CACHE_DIR}/${filename}`).isFile())
188
+ .reduce((res, file) => res + statSync(`${CACHE_DIR}/${file}`).size, 0)
189
+ return res.send({
190
+ stats: {
191
+ system: await checkDiskSpace(__dirname),
192
+ totalFilesSize: totalFilesSize._sum.size,
193
+ totalUserFilesSize: totalUserFilesSize._sum.size,
194
+ cachedSize
195
+ }
196
+ })
197
+ }
198
+
199
+ @Endpoint.POST('/', { middlewares: [Auth] })
200
+ public async save(req: Request, res: Response): Promise<any> {
201
+ const { messageId } = req.query
202
+ const { file } = req.body
203
+ if (!file) {
204
+ throw { status: 400, body: { error: 'File is required in body.' } }
205
+ }
206
+
207
+ let message: any = {}
208
+ if (messageId) {
209
+ if (!file.forward_info) {
210
+ throw { status: 400, body: { error: 'Forward info is required in body.' } }
211
+ }
212
+
213
+ let chat: any
214
+ if (file.forward_info && file.forward_info.match(/^channel\//gi)) {
215
+ const [type, peerId, _id, accessHash] = file.forward_info.split('/')
216
+ let peer: Api.InputPeerChannel | Api.InputPeerUser | Api.InputPeerChat
217
+ if (type === 'channel') {
218
+ peer = new Api.InputPeerChannel({
219
+ channelId: bigInt(peerId),
220
+ accessHash: bigInt(accessHash as string) })
221
+ chat = await req.tg.invoke(new Api.channels.GetMessages({
222
+ channel: peer,
223
+ id: [new Api.InputMessageID({ id: Number(messageId) })]
224
+ }))
225
+ }
226
+ } else {
227
+ chat = await req.tg.invoke(new Api.messages.GetMessages({
228
+ id: [new Api.InputMessageID({ id: Number(messageId) })]
229
+ })) as any
230
+ }
231
+
232
+ if (!chat?.['messages']?.[0]) {
233
+ throw { status: 404, body: { error: 'Message not found' } }
234
+ }
235
+
236
+ const mimeType = chat['messages'][0].media.photo ? 'image/jpeg' : chat['messages'][0].media.document.mimeType || 'unknown'
237
+ const name = chat['messages'][0].media.photo ? `${chat['messages'][0].media.photo.id}.jpg` : chat['messages'][0].media.document.attributes?.find((atr: any) => atr.fileName)?.fileName || `${chat['messages'][0].media?.document.id}.${mimeType.split('/').pop()}`
238
+
239
+ const getSizes = ({ size, sizes }) => sizes ? sizes.pop() : size
240
+ const size = chat['messages'][0].media.photo ? getSizes(chat['messages'][0].media.photo.sizes.pop()) : chat['messages'][0].media.document?.size
241
+ let type = chat['messages'][0].media.photo || mimeType.match(/^image/gi) ? 'image' : null
242
+ if (chat['messages'][0].media.document?.mimeType.match(/^video/gi) || name.match(/\.mp4$/gi) || name.match(/\.mkv$/gi) || name.match(/\.mov$/gi)) {
243
+ type = 'video'
244
+ } else if (chat['messages'][0].media.document?.mimeType.match(/pdf$/gi) || name.match(/\.doc$/gi) || name.match(/\.docx$/gi) || name.match(/\.xls$/gi) || name.match(/\.xlsx$/gi)) {
245
+ type = 'document'
246
+ } else if (chat['messages'][0].media.document?.mimeType.match(/audio$/gi) || name.match(/\.mp3$/gi) || name.match(/\.ogg$/gi)) {
247
+ type = 'audio'
248
+ }
249
+
250
+ message = {
251
+ name,
252
+ message_id: chat['messages'][0].id.toString(),
253
+ mime_type: mimeType,
254
+ size,
255
+ user_id: req.user.id,
256
+ uploaded_at: new Date(chat['messages'][0].date * 1000),
257
+ type
258
+ }
259
+ }
260
+ return res.send({ file: await prisma.files.create({
261
+ data: {
262
+ ...file,
263
+ ...message
264
+ }
265
+ }) })
266
+ }
267
+
268
+ @Endpoint.POST({ middlewares: [Auth] })
269
+ public async addFolder(req: Request, res: Response): Promise<any> {
270
+ const { file: data } = req.body
271
+ const count = await prisma.files.count({
272
+ where: {
273
+ AND: [
274
+ { type: 'folder' },
275
+ { user_id: req.user.id },
276
+ { name: { startsWith: data?.name || 'New Folder' } },
277
+ { parent_id: data?.parent_id || null },
278
+ { link_id: data?.link_id || null }
279
+ ]
280
+ }
281
+ })
282
+ const parent = data?.parent_id ? await prisma.files.findUnique({
283
+ where: { id: data.parent_id }
284
+ }) : null
285
+
286
+ return res.send({ file: await prisma.files.create({
287
+ data: {
288
+ name: (data?.name || 'New Folder') + `${count ? ` (${count})` : ''}`,
289
+ mime_type: 'teledrive/folder',
290
+ user_id: req.user.id,
291
+ type: 'folder',
292
+ uploaded_at: new Date(),
293
+ link_id: data?.link_id,
294
+ ...parent ? {
295
+ parent_id: parent.id,
296
+ sharing_options: parent.sharing_options,
297
+ signed_key: parent.signed_key
298
+ } : {}
299
+ }
300
+ }) })
301
+ }
302
+
303
+ @Endpoint.POST({ middlewares: [Auth] })
304
+ public async cloneFile(req: Request, res: Response): Promise<any> {
305
+ const { file: body } = req.body
306
+ const source = await prisma.files.findUnique({ where: { id: body.key } })
307
+ const files = await prisma.files.findMany({
308
+ where: {
309
+ AND: [
310
+ { name: source.name.endsWith('.part001') ? { startsWith: source.name.replace(/\.part0*\d+$/, '.part') } : source.name },
311
+ { user_id: req.user?.id },
312
+ { parent_id: source.parent_id },
313
+ ]
314
+ }
315
+ })
316
+
317
+ const countExists = await prisma.files.count({
318
+ where: {
319
+ AND: [
320
+ { name: source.name.endsWith('.part001') ? { startsWith: source.name.replace(/\.part0*\d+$/, ''), endsWith: '.part001' } : { startsWith: source.name } },
321
+ { user_id: req.user?.id },
322
+ { parent_id: body.parent_id }
323
+ ]
324
+ }
325
+ })
326
+
327
+ delete body.key
328
+ let countFiles = 0
329
+ for (const file of files) {
330
+ const { forward_info: forwardInfo, message_id: messageId, mime_type: mimeType } = file
331
+ let peerFrom: Api.InputPeerChannel | Api.InputPeerUser | Api.InputPeerChat
332
+ let peerTo: Api.InputPeerChannel | Api.InputPeerUser | Api.InputPeerChat
333
+ if (forwardInfo && forwardInfo.match(/^channel\//gi)) {
334
+ const [type, peerId, _id, accessHash] = forwardInfo?.split('/') ?? []
335
+ if (type === 'channel') {
336
+ peerFrom = new Api.InputPeerChannel({
337
+ channelId: bigInt(peerId),
338
+ accessHash: accessHash ? bigInt(accessHash as string) : null })
339
+ } else if (type === 'user') {
340
+ peerFrom = new Api.InputPeerUser({
341
+ userId: bigInt(peerId),
342
+ accessHash: bigInt(accessHash as string) })
343
+ } else if (type === 'chat') {
344
+ peerFrom = new Api.InputPeerChat({
345
+ chatId: bigInt(peerId) })
346
+ }
347
+ }
348
+ const [type, peerId, _, accessHash] = ((req.user.settings as Prisma.JsonObject).saved_location as string).split('/')
349
+ if ((req.user.settings as Prisma.JsonObject)?.saved_location) {
350
+ if (type === 'channel') {
351
+ peerTo = new Api.InputPeerChannel({
352
+ channelId: bigInt(peerId),
353
+ accessHash: accessHash ? bigInt(accessHash as string) : null })
354
+ } else if (type === 'user') {
355
+ peerTo = new Api.InputPeerUser({
356
+ userId: bigInt(peerId),
357
+ accessHash: bigInt(accessHash as string) })
358
+ } else if (type === 'chat') {
359
+ peerTo = new Api.InputPeerChat({
360
+ chatId: bigInt(peerId) })
361
+ }
362
+ }
363
+
364
+ const chat = await req.tg.invoke(new Api.messages.ForwardMessages({
365
+ fromPeer: peerFrom || 'me',
366
+ id: [Number(messageId)],
367
+ toPeer: peerTo || 'me',
368
+ randomId: [bigInt.randBetween('-1e100', '1e100')],
369
+ silent: true,
370
+ dropAuthor: true
371
+ })) as any
372
+
373
+ const newForwardInfo = peerTo ? `${type}/${peerId}/${chat.updates[0].id.toString()}/${accessHash}` : null
374
+ const message = {
375
+ size: Number(file.size),
376
+ message_id: chat.updates[0].id.toString(),
377
+ mime_type: mimeType,
378
+ forward_info: newForwardInfo,
379
+ uploaded_at: new Date(chat.date * 1000)
380
+ }
381
+
382
+ const response = await prisma.files.create({
383
+ data: {
384
+ ...body,
385
+ name: files.length == 1 ? body.name + `${countExists ? ` (${countExists})` : ''}` : body.name.replace(/\.part0*\d+$/, '')+`${countExists ? ` (${countExists})` : ''}`+`.part${String(countFiles + 1).padStart(3, '0')}`,
386
+ ...message
387
+ }
388
+ })
389
+ if (countFiles++ == 0)
390
+ res.send({ file: response })
391
+ }
392
+ }
393
+
394
+ @Endpoint.GET('/:id', { middlewares: [AuthMaybe] })
395
+ public async retrieve(req: Request, res: Response): Promise<any> {
396
+ const { id } = req.params
397
+ const { password } = req.query
398
+ const file = await prisma.files.findUnique({
399
+ where: { id }
400
+ })
401
+
402
+ const parent = file?.parent_id ? await prisma.files.findUnique({
403
+ where: { id: file.parent_id }
404
+ }) : null
405
+ if (!file || file.user_id !== req.user?.id && !file.sharing_options?.includes('*') && !file.sharing_options?.includes(req.user?.username)) {
406
+ if (!parent?.sharing_options?.includes(req.user?.username) && !parent?.sharing_options?.includes('*')) {
407
+ throw { status: 404, body: { error: 'File not found' } }
408
+ }
409
+ }
410
+ file.signed_key = file.signed_key || parent?.signed_key
411
+
412
+ if (file.password && req.user?.id !== file.user_id) {
413
+ if (!password) {
414
+ throw { status: 400, body: { error: 'Unauthorized' } }
415
+ }
416
+ if (!compareSync(password as string, file.password)) {
417
+ throw { status: 400, body: { error: 'Wrong passphrase' } }
418
+ }
419
+ }
420
+
421
+ let files = [file]
422
+ if (/.*\.part0*1$/gi.test(file?.name)) {
423
+ // if (req.user?.plan !== 'premium') {
424
+ // throw { status: 402, body: { error: 'Please upgrade your plan for view this file' } }
425
+ // }
426
+ files = await prisma.files.findMany({
427
+ where: {
428
+ AND: [
429
+ {
430
+ OR: [
431
+ { id },
432
+ { name: { startsWith: file.name.replace(/\.part0*1$/gi, '') } }
433
+ ]
434
+ },
435
+ { user_id: file.user_id },
436
+ { parent_id: file.parent_id || null }
437
+ ]
438
+ }
439
+ })
440
+ files[0].signed_key = file.signed_key = file.signed_key || parent?.signed_key
441
+ }
442
+
443
+ if (!req.user || file.user_id !== req.user?.id) {
444
+ await Files.initiateSessionTG(req, files)
445
+ await req.tg.connect()
446
+ }
447
+
448
+ return await Files.download(req, res, files)
449
+ }
450
+
451
+ @Endpoint.DELETE('/:id', { middlewares: [Auth] })
452
+ public async remove(req: Request, res: Response): Promise<any> {
453
+ const { id } = req.params
454
+ const { deleteMessage } = req.query
455
+ const file = await prisma.files.findFirst({
456
+ where: {
457
+ AND: [{ id }, { user_id: req.user.id }]
458
+ },
459
+ })
460
+ if (!file) {
461
+ throw { status: 404, body: { error: 'File not found' } }
462
+ }
463
+ await prisma.files.delete({ where: { id } })
464
+
465
+ if (deleteMessage && ['true', '1'].includes(deleteMessage as string) && !file?.forward_info) {
466
+ try {
467
+ await req.tg.invoke(new Api.messages.DeleteMessages({ id: [Number(file.message_id)], revoke: true }))
468
+ } catch (error) {
469
+ try {
470
+ await req.tg.invoke(new Api.channels.DeleteMessages({ id: [Number(file.message_id)], channel: 'me' }))
471
+ } catch (error) {
472
+ // ignore
473
+ }
474
+ }
475
+ }
476
+
477
+ if (/.*\.part0*1$/gi.test(file?.name)) {
478
+ const files = await prisma.files.findMany({
479
+ where: {
480
+ AND: [
481
+ {
482
+ OR: [
483
+ { id },
484
+ { name: { startsWith: file.name.replace(/\.part0*1$/gi, '') } }
485
+ ],
486
+ },
487
+ { user_id: file.user_id },
488
+ { parent_id: file.parent_id || null }
489
+ ]
490
+ }
491
+ })
492
+ files.map(async (file: files) => {
493
+ await prisma.files.delete({ where: { id: file.id } })
494
+ if (deleteMessage && ['true', '1'].includes(deleteMessage as string) && !file?.forward_info) {
495
+ try {
496
+ await req.tg.invoke(new Api.messages.DeleteMessages({ id: [Number(file.message_id)], revoke: true }))
497
+ } catch (error) {
498
+ try {
499
+ await req.tg.invoke(new Api.channels.DeleteMessages({ id: [Number(file.message_id)], channel: 'me' }))
500
+ } catch (error) {
501
+ // ignore
502
+ }
503
+ }
504
+ }
505
+ })
506
+ }
507
+ return res.send({ file })
508
+ }
509
+
510
+ @Endpoint.PATCH('/:id', { middlewares: [Auth] })
511
+ public async update(req: Request, res: Response): Promise<any> {
512
+ const { id } = req.params
513
+ const { file } = req.body
514
+ if (!file) {
515
+ throw { status: 400, body: { error: 'File is required in body' } }
516
+ }
517
+
518
+ const currentFile = await prisma.files.findFirst({
519
+ where: {
520
+ AND: [{ id }, { user_id: req.user.id }]
521
+ }
522
+ })
523
+ if (!currentFile) {
524
+ throw { status: 404, body: { error: 'File not found' } }
525
+ }
526
+
527
+ const parent = file.parent_id ? await prisma.files.findUnique({
528
+ where: { id: file.parent_id }
529
+ }) : null
530
+
531
+ let key: string = currentFile.signed_key || parent?.signed_key
532
+ if (file.sharing_options?.length && !key) {
533
+ key = AES.encrypt(JSON.stringify({ file: { id: file.id }, session: req.tg.session.save() }), FILES_JWT_SECRET).toString()
534
+ }
535
+
536
+ if (!file.sharing_options?.length && !currentFile.sharing_options?.length && !parent?.sharing_options?.length) {
537
+ key = null
538
+ }
539
+
540
+ if (/.*\.part0*1$/gi.test(currentFile?.name)) {
541
+ const files = await prisma.files.findMany({
542
+ where: {
543
+ AND: [
544
+ {
545
+ OR: [
546
+ { id },
547
+ { name: { startsWith: currentFile.name.replace(/\.part0*1$/gi, '') } }
548
+ ]
549
+ },
550
+ { user_id: currentFile.user_id },
551
+ { parent_id: currentFile.parent_id || null }
552
+ ]
553
+ }
554
+ })
555
+ await Promise.all(files.map(async current => await prisma.files.update({
556
+ where: { id: current.id },
557
+ data: {
558
+ ...file.name ? { name: current.name.replace(current.name.replace(/\.part0*\d+$/gi, ''), file.name) } : {},
559
+ ...file.sharing_options !== undefined ? { sharing_options: file.sharing_options } : {},
560
+ ...file.parent_id !== undefined ? { parent_id: file.parent_id } : {},
561
+ ...parent && current.type === 'folder' ? {
562
+ sharing_options: parent.sharing_options
563
+ } : {},
564
+ signed_key: key,
565
+ ...file.password !== undefined ? {
566
+ password: file.password !== null ? hashSync(file.password, 10) : null
567
+ } : {}
568
+ }
569
+ })))
570
+ } else {
571
+ await prisma.files.updateMany({
572
+ where: {
573
+ AND: [
574
+ { id },
575
+ { user_id: req.user.id }
576
+ ],
577
+ },
578
+ data: {
579
+ ...file.name ? { name: currentFile.name.replace(currentFile.name.replace(/\.part0*1$/gi, ''), file.name) } : {},
580
+ ...file.sharing_options !== undefined ? { sharing_options: file.sharing_options } : {},
581
+ ...file.parent_id !== undefined ? { parent_id: file.parent_id } : {},
582
+ ...parent && currentFile.type === 'folder' ? {
583
+ sharing_options: parent.sharing_options
584
+ } : {},
585
+ signed_key: key,
586
+ ...file.password !== undefined ? {
587
+ password: file.password !== null ? hashSync(file.password, 10) : null
588
+ } : {}
589
+ }
590
+ })
591
+ }
592
+
593
+ if (file.sharing_options !== undefined && currentFile.type === 'folder') {
594
+ const updateSharingOptions = async (currentFile: files) => {
595
+ const children = await prisma.files.findMany({
596
+ where: {
597
+ AND: [
598
+ { parent_id: currentFile.id },
599
+ { type: 'folder' }
600
+ ]
601
+ }
602
+ })
603
+ for (const child of children) {
604
+ await prisma.files.updateMany({
605
+ where: {
606
+ AND: [
607
+ { id: child.id },
608
+ { user_id: req.user.id }
609
+ ]
610
+ },
611
+ data: {
612
+ sharing_options: file.sharing_options,
613
+ signed_key: key || child.signed_key,
614
+ ...file.password !== undefined ? {
615
+ password: file.password !== null ? hashSync(file.password, 10) : null
616
+ } : {}
617
+ }
618
+ })
619
+ await updateSharingOptions(child)
620
+ }
621
+ }
622
+ await updateSharingOptions(currentFile)
623
+ }
624
+
625
+ return res.send({ file: { id } })
626
+ }
627
+
628
+ @Endpoint.POST('/upload/:id?', { middlewares: [Auth, multer().single('upload')] })
629
+ public async upload(req: Request, res: Response): Promise<any> {
630
+ const { name, size, mime_type: mimetype, parent_id: parentId, relative_path: relativePath, total_part: totalPart, part } = req.query as Record<string, string>
631
+
632
+ if (!name || !size || !mimetype || !part || !totalPart) {
633
+ throw { status: 400, body: { error: 'Name, size, mimetype, part, and total part are required' } }
634
+ }
635
+ const file = req.file
636
+ if (!file) {
637
+ throw { status: 400, body: { error: 'File upload is required' } }
638
+ }
639
+
640
+ if (file.size > 512 * 1024) {
641
+ throw { status: 400, body: { error: 'Maximum file part size is 500kB' } }
642
+ }
643
+
644
+ // if ((!req.user?.plan || req.user?.plan === 'free') && /\.part\d+$/gi.test(name)) {
645
+ // throw { status: 402, body: { error: 'Payment required' } }
646
+ // }
647
+
648
+ let model: files
649
+
650
+ if (req.params?.id) {
651
+ model = await prisma.files.findUnique({
652
+ where: { id: req.params.id }
653
+ })
654
+ if (!model) {
655
+ throw { status: 404, body: { error: 'File not found' } }
656
+ }
657
+ } else {
658
+ let type = null
659
+ if (mimetype.match(/^image/gi)) {
660
+ type = 'image'
661
+ } else if (mimetype.match(/^video/gi) || name.match(/\.mp4$/gi) || name.match(/\.mkv$/gi) || name.match(/\.mov$/gi)) {
662
+ type = 'video'
663
+ } else if (mimetype.match(/pdf$/gi) || name.match(/\.doc$/gi) || name.match(/\.docx$/gi) || name.match(/\.xls$/gi) || name.match(/\.xlsx$/gi)) {
664
+ type = 'document'
665
+ } else if (mimetype.match(/audio$/gi) || name.match(/\.mp3$/gi) || name.match(/\.ogg$/gi)) {
666
+ type = 'audio'
667
+ } else {
668
+ type = 'unknown'
669
+ }
670
+
671
+ let currentParentId = parentId
672
+ if (relativePath) {
673
+ const paths = relativePath.split('/').slice(0, -1) || []
674
+ for (const i in paths) {
675
+ const path = paths[i]
676
+ const findFolder = await prisma.files.findFirst({
677
+ where: {
678
+ AND: [
679
+ { type: 'folder' },
680
+ { name: path },
681
+ { parent_id: currentParentId || null }
682
+ ]
683
+ }
684
+ })
685
+ if (findFolder) {
686
+ currentParentId = findFolder.id
687
+ } else {
688
+ const newFolder = await prisma.files.create({
689
+ data: {
690
+ name: path,
691
+ type: 'folder',
692
+ user_id: req.user.id,
693
+ mime_type: 'teledrive/folder',
694
+ uploaded_at: new Date(),
695
+ ...currentParentId ? { parent_id: currentParentId } : {}
696
+ }
697
+ })
698
+ currentParentId = newFolder.id
699
+ }
700
+ }
701
+ }
702
+
703
+ model = await prisma.files.findFirst({
704
+ where: {
705
+ name: name,
706
+ mime_type: mimetype,
707
+ size: Number(size),
708
+ user_id: req.user.id,
709
+ type: type,
710
+ parent_id: currentParentId || null,
711
+ }
712
+ })
713
+
714
+ if (model) {
715
+ await prisma.files.update({
716
+ data: {
717
+ message_id: null,
718
+ uploaded_at: null,
719
+ upload_progress: 0
720
+ },
721
+ where: { id: model.id }
722
+ })
723
+ } else {
724
+ model = await prisma.files.create({
725
+ data: {
726
+ name: name,
727
+ mime_type: mimetype,
728
+ size: Number(size),
729
+ user_id: req.user.id,
730
+ type: type,
731
+ parent_id: currentParentId || null,
732
+ upload_progress: 0,
733
+ file_id: bigInt.randBetween('-1e100', '1e100').toString(),
734
+ forward_info: (req.user.settings as Prisma.JsonObject)?.saved_location as string || null,
735
+ }
736
+ })
737
+ }
738
+ }
739
+
740
+ // upload per part
741
+ let uploadPartStatus: boolean
742
+ const uploadPart = async () => await req.tg.invoke(new Api.upload.SaveBigFilePart({
743
+ fileId: bigInt(model.file_id),
744
+ filePart: Number(part),
745
+ fileTotalParts: Number(totalPart),
746
+ bytes: file.buffer
747
+ }))
748
+
749
+ try {
750
+ uploadPartStatus = await uploadPart()
751
+ } catch (error) {
752
+ try {
753
+ await new Promise((resolve) => setTimeout(resolve, 1000))
754
+ await req.tg?.connect()
755
+ uploadPartStatus = await uploadPart()
756
+ } catch (error) {
757
+ await new Promise((resolve) => setTimeout(resolve, 1000))
758
+ await req.tg?.connect()
759
+ uploadPartStatus = await uploadPart()
760
+ }
761
+ }
762
+
763
+ // model.size = bigInt(model.size).add(file.buffer.length).toString()
764
+ await prisma.files.update({
765
+ where: { id: model.id },
766
+ data: {
767
+ upload_progress: (Number(part) + 1) / Number(totalPart)
768
+ }
769
+ })
770
+
771
+ if (Number(part) < Number(totalPart) - 1) {
772
+ return res.status(202).send({ accepted: true, file: { id: model.id }, uploadPartStatus })
773
+ }
774
+
775
+ // begin to send
776
+ const sendData = async (forceDocument: boolean) => {
777
+ let peer: Api.InputPeerChannel | Api.InputPeerUser | Api.InputPeerChat
778
+ if ((req.user.settings as Prisma.JsonObject)?.saved_location) {
779
+ const [type, peerId, _, accessHash] = ((req.user.settings as Prisma.JsonObject).saved_location as string).split('/')
780
+ if (type === 'channel') {
781
+ peer = new Api.InputPeerChannel({
782
+ channelId: bigInt(peerId),
783
+ accessHash: accessHash ? bigInt(accessHash as string) : null })
784
+ } else if (type === 'user') {
785
+ peer = new Api.InputPeerUser({
786
+ userId: bigInt(peerId),
787
+ accessHash: bigInt(accessHash as string) })
788
+ } else if (type === 'chat') {
789
+ peer = new Api.InputPeerChat({
790
+ chatId: bigInt(peerId) })
791
+ }
792
+ }
793
+ return await req.tg.sendFile(peer || 'me', {
794
+ file: new Api.InputFileBig({
795
+ id: bigInt(model.file_id),
796
+ parts: Number(totalPart),
797
+ name: model.name
798
+ }),
799
+ forceDocument,
800
+ caption: model.name,
801
+ fileSize: Number(model.size),
802
+ attributes: forceDocument ? [
803
+ new Api.DocumentAttributeFilename({ fileName: model.name })
804
+ ] : undefined,
805
+ workers: 1
806
+ })
807
+ }
808
+
809
+ let data: Api.Message
810
+ try {
811
+ data = await sendData(false)
812
+ } catch (error) {
813
+ data = await sendData(true)
814
+ }
815
+
816
+ let forwardInfo = null
817
+ if ((req.user.settings as Prisma.JsonObject)?.saved_location) {
818
+ const [type, peerId, _, accessHash] = ((req.user.settings as Prisma.JsonObject).saved_location as string).split('/')
819
+ forwardInfo = `${type}/${peerId}/${data.id?.toString()}/${accessHash}`
820
+ }
821
+
822
+ await prisma.files.update({
823
+ data: {
824
+ message_id: data.id?.toString(),
825
+ uploaded_at: data.date ? new Date(data.date * 1000) : null,
826
+ upload_progress: null,
827
+ ...forwardInfo ? { forward_info: forwardInfo } : {}
828
+ },
829
+ where: { id: model.id }
830
+ })
831
+
832
+ return res.status(202).send({ accepted: true, file: { id: model.id } })
833
+ }
834
+
835
+ @Endpoint.POST('/uploadBeta/:id?', { middlewares: [Auth] })
836
+ public async uploadBeta(req: Request, res: Response): Promise<any> {
837
+ const {
838
+ name,
839
+ size,
840
+ mime_type: mimetype,
841
+ parent_id: parentId,
842
+ relative_path: relativePath,
843
+ total_part: totalPart,
844
+ part,
845
+ message
846
+ } = req.body as Record<string, any>
847
+
848
+ let model: files
849
+ if (req.params?.id) {
850
+ model = await prisma.files.findUnique({
851
+ where: { id: req.params.id }
852
+ })
853
+ if (!model) {
854
+ throw { status: 404, body: { error: 'File not found' } }
855
+ }
856
+ }
857
+
858
+ if (!message) {
859
+ // if ((!req.user?.plan || req.user?.plan === 'free') && /\.part\d+$/gi.test(name)) {
860
+ // throw { status: 402, body: { error: 'Payment required' } }
861
+ // }
862
+
863
+ if (!model) {
864
+ let type = null
865
+ if (mimetype.match(/^image/gi)) {
866
+ type = 'image'
867
+ } else if (mimetype.match(/^video/gi) || name.match(/\.mp4$/gi) || name.match(/\.mkv$/gi) || name.match(/\.mov$/gi)) {
868
+ type = 'video'
869
+ } else if (mimetype.match(/pdf$/gi) || name.match(/\.doc$/gi) || name.match(/\.docx$/gi) || name.match(/\.xls$/gi) || name.match(/\.xlsx$/gi)) {
870
+ type = 'document'
871
+ } else if (mimetype.match(/audio$/gi) || name.match(/\.mp3$/gi) || name.match(/\.ogg$/gi)) {
872
+ type = 'audio'
873
+ } else {
874
+ type = 'unknown'
875
+ }
876
+
877
+ let currentParentId = parentId
878
+ if (relativePath) {
879
+ const paths = relativePath.split('/').slice(0, -1) || []
880
+ for (const i in paths) {
881
+ const path = paths[i]
882
+ const findFolder = await prisma.files.findFirst({
883
+ where: {
884
+ AND: [
885
+ { type: 'folder' },
886
+ { name: path },
887
+ { user_id: req.user.id },
888
+ { parent_id: currentParentId || null }
889
+ ]
890
+ }
891
+ })
892
+ if (findFolder) {
893
+ currentParentId = findFolder.id
894
+ } else {
895
+ const newFolder = await prisma.files.create({
896
+ data: {
897
+ name: path,
898
+ type: 'folder',
899
+ user_id: req.user.id,
900
+ mime_type: 'teledrive/folder',
901
+ ...currentParentId ? { parent_id: currentParentId } : {}
902
+ }
903
+ })
904
+ currentParentId = newFolder.id
905
+ }
906
+ }
907
+ }
908
+
909
+ model = await prisma.files.findFirst({
910
+ where: {
911
+ name: name,
912
+ mime_type: mimetype,
913
+ size: Number(size),
914
+ user_id: req.user.id,
915
+ type: type,
916
+ parent_id: currentParentId || null,
917
+ }
918
+ })
919
+
920
+ if (model) {
921
+ await prisma.files.update({
922
+ data: {
923
+ message_id: null,
924
+ uploaded_at: null,
925
+ upload_progress: 0
926
+ },
927
+ where: { id: model.id }
928
+ })
929
+ } else {
930
+ model = await prisma.files.create({
931
+ data: {
932
+ name: name,
933
+ mime_type: mimetype,
934
+ size: Number(size),
935
+ user_id: req.user.id,
936
+ type: type,
937
+ parent_id: currentParentId || null,
938
+ upload_progress: 0,
939
+ file_id: bigInt.randBetween('-1e100', '1e100').toString(),
940
+ forward_info: (req.user.settings as Prisma.JsonObject)?.saved_location as string || null,
941
+ }
942
+ })
943
+ }
944
+ }
945
+
946
+ // model.size = bigInt(model.size).add(file.buffer.length).toString()
947
+ await prisma.files.update({
948
+ data: {
949
+ upload_progress: (Number(part) + 1) / Number(totalPart)
950
+ },
951
+ where: { id: model.id }
952
+ })
953
+
954
+ // if (Number(part) < Number(totalPart) - 1) {
955
+ if (!message) {
956
+ return res.status(202).send({ accepted: true, file: { id: model.id, file_id: model.file_id, name: model.name, size: model.size, type: model.type } })
957
+ }
958
+ }
959
+
960
+ let forwardInfo: string
961
+ if ((req.user.settings as Prisma.JsonObject)?.saved_location) {
962
+ const [type, peerId, _, accessHash] = ((req.user.settings as Prisma.JsonObject).saved_location as string).split('/')
963
+ forwardInfo = `${type}/${peerId}/${message.id?.toString()}/${accessHash}`
964
+ }
965
+
966
+ await prisma.files.update({
967
+ data: {
968
+ message_id: message.id?.toString(),
969
+ uploaded_at: message.date ? new Date(message.date * 1000) : null,
970
+ upload_progress: null,
971
+ ...forwardInfo ? { forward_info: forwardInfo } : {}
972
+ },
973
+ where: { id: model.id }
974
+ })
975
+ return res.status(202).send({ accepted: true, file: { id: model.id, file_id: model.file_id, name: model.name, size: model.size, type: model.type } })
976
+ }
977
+
978
+ @Endpoint.GET('/breadcrumbs/:id', { middlewares: [AuthMaybe] })
979
+ public async breadcrumbs(req: Request, res: Response): Promise<any> {
980
+ const { id } = req.params
981
+ let folder = await prisma.files.findUnique({ where: { id } })
982
+ if (!folder) {
983
+ throw { status: 404, body: { error: 'File not found' } }
984
+ }
985
+ if (req.user?.id !== folder.user_id) {
986
+ if (!folder.sharing_options?.includes('*') && !folder.sharing_options?.includes(req.user?.username)) {
987
+ throw { status: 404, body: { error: 'File not found' } }
988
+ }
989
+ }
990
+
991
+ const breadcrumbs = [folder]
992
+ while (folder.parent_id) {
993
+ folder = await prisma.files.findUnique({ where: { id: folder.parent_id } })
994
+ if (!req.user && folder.sharing_options?.includes('*') || folder.sharing_options?.includes(req.user?.username) || folder.user_id === req.user?.id) {
995
+ breadcrumbs.push(folder)
996
+ }
997
+ }
998
+
999
+ return res.send({ breadcrumbs: breadcrumbs.reverse() })
1000
+ }
1001
+
1002
+ @Endpoint.POST('/sync', { middlewares: [Auth] })
1003
+ public async sync(req: Request, res: Response): Promise<any> {
1004
+ const { parent_id: parentId, limit } = req.query
1005
+
1006
+ // if (req.user.plan === 'free' || !req.user.plan) {
1007
+ // throw { status: 402, body: { error: 'Payment required' } }
1008
+ // }
1009
+
1010
+ let peer: Api.InputPeerChannel | Api.InputPeerUser | Api.InputPeerChat
1011
+ if ((req.user.settings as Prisma.JsonObject)?.saved_location) {
1012
+ const [type, peerId, _, accessHash] = ((req.user.settings as Prisma.JsonObject).saved_location as string).split('/')
1013
+ if (type === 'channel') {
1014
+ peer = new Api.InputPeerChannel({
1015
+ channelId: bigInt(peerId),
1016
+ accessHash: accessHash ? bigInt(accessHash as string) : null })
1017
+ } else if (type === 'user') {
1018
+ peer = new Api.InputPeerUser({
1019
+ userId: bigInt(peerId),
1020
+ accessHash: bigInt(accessHash as string) })
1021
+ } else if (type === 'chat') {
1022
+ peer = new Api.InputPeerChat({
1023
+ chatId: bigInt(peerId) })
1024
+ }
1025
+ }
1026
+
1027
+ let files = []
1028
+ let found = true
1029
+ let offsetId: number
1030
+ while (files.length < (Number(limit) || 10) && found) {
1031
+ const messages = await req.tg.invoke(new Api.messages.GetHistory({
1032
+ peer: peer || 'me',
1033
+ limit: Number(limit) || 10,
1034
+ offsetId: offsetId || 0,
1035
+ }))
1036
+
1037
+ if (messages['messages']?.length) {
1038
+ offsetId = messages['messages'][messages['messages'].length - 1].id
1039
+ files = [...files, ...messages['messages'].filter((msg: any) => msg?.media?.photo || msg?.media?.document)]
1040
+ } else {
1041
+ found = false
1042
+ }
1043
+ }
1044
+
1045
+ files = files.slice(0, Number(limit) || 10)
1046
+
1047
+ if (files?.length) {
1048
+ const existFiles = await prisma.files.findMany({
1049
+ where: {
1050
+ AND: [
1051
+ {
1052
+ message_id: {
1053
+ in: files.map(file => file.id.toString())
1054
+ }
1055
+ },
1056
+ { parent_id: parentId as string || null },
1057
+ { forward_info: null }
1058
+ ]
1059
+ }
1060
+ })
1061
+ const filesWantToSave = files.filter(file => !existFiles.find(e => e.message_id == file.id))
1062
+ if (filesWantToSave?.length) {
1063
+ await prisma.files.createMany({
1064
+ data: filesWantToSave.map(file => {
1065
+ const mimeType = file.media.photo ? 'image/jpeg' : file.media.document.mimeType || 'unknown'
1066
+ const name = file.media.photo ? `${file.media.photo.id}.jpg` : file.media.document.attributes?.find((atr: any) => atr.fileName)?.fileName || `${file.media?.document.id}.${mimeType.split('/').pop()}`
1067
+
1068
+ const getSizes = ({ size, sizes }) => sizes ? sizes.pop() : size
1069
+ const size = file.media.photo ? getSizes(file.media.photo.sizes.pop()) : file.media.document?.size
1070
+ let type = file.media.photo
1071
+ if (file.media.document?.mimeType.match(/^video/gi) || name.match(/\.mp4$/gi) || name.match(/\.mkv$/gi) || name.match(/\.mov$/gi)) {
1072
+ type = 'video'
1073
+ } else if (file.media.document?.mimeType.match(/pdf$/gi) || name.match(/\.doc$/gi) || name.match(/\.docx$/gi) || name.match(/\.xls$/gi) || name.match(/\.xlsx$/gi)) {
1074
+ type = 'document'
1075
+ } else if (file.media.document?.mimeType.match(/audio$/gi) || name.match(/\.mp3$/gi) || name.match(/\.ogg$/gi)) {
1076
+ type = 'audio'
1077
+ } else if (file.media.document?.mimeType.match(/^image/gi) || name.match(/\.jpg$/gi) || name.match(/\.jpeg$/gi) || name.match(/\.png$/gi) || name.match(/\.gif$/gi)) {
1078
+ type = 'image'
1079
+ }
1080
+ return {
1081
+ name,
1082
+ message_id: file.id.toString(),
1083
+ mime_type: mimeType,
1084
+ size: size.value,
1085
+ user_id: req.user.id,
1086
+ uploaded_at: new Date(file.date * 1000),
1087
+ type,
1088
+ parent_id: parentId ? parentId.toString() : null
1089
+ }
1090
+ })
1091
+ })
1092
+ }
1093
+ }
1094
+ return res.send({ files })
1095
+ }
1096
+
1097
+ @Endpoint.POST('/filesSync', { middlewares: [Auth] })
1098
+ public async filesSync(req: Request, res: Response): Promise<any> {
1099
+ const { files } = req.body
1100
+ for (const file of files) {
1101
+ const existFile = await prisma.files.findFirst({
1102
+ where: {
1103
+ AND: [
1104
+ { name: file.name },
1105
+ { type: file.type },
1106
+ { size: Number(file.size) || null },
1107
+ {
1108
+ parent_id: file.parent_id ? { not: null } : null
1109
+ }
1110
+ ]
1111
+ }
1112
+ })
1113
+ if (!existFile) {
1114
+ try {
1115
+ await prisma.files.create({
1116
+ data: {
1117
+ ...file,
1118
+ size: Number(file.size),
1119
+ user_id: req.user.id,
1120
+ }
1121
+ })
1122
+ } catch (error) {
1123
+ // ignore
1124
+ }
1125
+ }
1126
+ }
1127
+ return res.status(202).send({ accepted: true })
1128
+ }
1129
+
1130
+ public static async download(req: Request, res: Response, files: files[], onlyHeaders?: boolean): Promise<any> {
1131
+ const { raw, dl, thumb, as_array: asArray } = req.query
1132
+
1133
+ let usage = await prisma.usages.findFirst({
1134
+ where: {
1135
+ key: req.user ? `u:${req.user.id}` : `ip:${req.headers['cf-connecting-ip'] as string || req.ip}`
1136
+ }
1137
+ })
1138
+ if (!usage) {
1139
+ usage = await prisma.usages.create({
1140
+ data: {
1141
+ key: req.user ? `u:${req.user.id}` : `ip:${req.headers['cf-connecting-ip'] as string || req.ip}`,
1142
+ usage: 0,
1143
+ expire: moment().add(1, 'day').toDate()
1144
+ }
1145
+ })
1146
+ }
1147
+
1148
+ if (new Date().getTime() - new Date(usage.expire).getTime() > 0) { // is expired
1149
+ usage = await prisma.usages.update({
1150
+ data: {
1151
+ expire: moment().add(1, 'day').toDate(),
1152
+ usage: 0
1153
+ },
1154
+ where: { key: usage.key }
1155
+ })
1156
+ }
1157
+
1158
+ const totalFileSize = files.reduce((res, file) => res.add(file.size || 0), bigInt(0))
1159
+
1160
+ if (!raw || Number(raw) === 0) {
1161
+ const { signed_key: _, ...result } = files[0]
1162
+ return res.send({ file: { ...result, password: result.password ? '[REDACTED]' : null } })
1163
+ }
1164
+
1165
+ usage = await prisma.usages.update({
1166
+ data: {
1167
+ usage: bigInt(totalFileSize).add(bigInt(usage.usage)).toJSNumber()
1168
+ },
1169
+ where: { key: usage.key }
1170
+ })
1171
+ if (asArray === '1') {
1172
+ return res.send({ files })
1173
+ }
1174
+
1175
+ console.log(req.headers.range)
1176
+
1177
+ let cancel = false
1178
+ req.on('close', () => cancel = true)
1179
+
1180
+ const ranges = req.headers.range ? req.headers.range.replace(/bytes\=/gi, '').split('-').map(Number) : null
1181
+
1182
+ if (onlyHeaders) return res.status(200)
1183
+
1184
+ const filename = (prefix: string = '') => `${CACHE_DIR}/${prefix}${totalFileSize.toString()}_${files[0].name}`
1185
+ try {
1186
+ mkdirSync(`${CACHE_DIR}`, { recursive: true })
1187
+ } catch (error) {
1188
+ // ignore
1189
+ }
1190
+
1191
+ const cachedFiles = () => readdirSync(`${CACHE_DIR}`)
1192
+ .filter(filename =>
1193
+ statSync(`${CACHE_DIR}/${filename}`).isFile()
1194
+ ).sort((a, b) =>
1195
+ new Date(statSync(`${CACHE_DIR}/${a}`).birthtime).getTime()
1196
+ - new Date(statSync(`${CACHE_DIR}/${b}`).birthtime).getTime()
1197
+ )
1198
+ const getCachedFilesSize = () => cachedFiles().reduce((res, file) => res + statSync(`${CACHE_DIR}/${file}`).size, 0)
1199
+
1200
+ if (existsSync(filename())) {
1201
+ if (ranges) {
1202
+ const start = ranges[0]
1203
+ const end = ranges[1] ? ranges[1] : totalFileSize.toJSNumber() - 1
1204
+
1205
+ const readStream = createReadStream(filename(), { start, end })
1206
+ res.writeHead(200, {
1207
+ 'Cache-Control': 'public, max-age=604800',
1208
+ 'ETag': Buffer.from(`${files[0].id}:${files[0].message_id}`).toString('base64'),
1209
+ 'Content-Range': `bytes ${start}-${end}/${totalFileSize}`,
1210
+ 'Content-Disposition': contentDisposition(files[0].name.replace(/\.part\d+$/gi, ''), { type: Number(dl) === 1 ? 'attachment' : 'inline' }),
1211
+ 'Content-Type': files[0].mime_type,
1212
+ 'Content-Length': end - start + 1,
1213
+ 'Accept-Ranges': 'bytes',
1214
+ })
1215
+ readStream.pipe(res)
1216
+ } else {
1217
+ res.writeHead(200, {
1218
+ 'Cache-Control': 'public, max-age=604800',
1219
+ 'ETag': Buffer.from(`${files[0].id}:${files[0].message_id}`).toString('base64'),
1220
+ 'Content-Range': `bytes */${totalFileSize}`,
1221
+ 'Content-Disposition': contentDisposition(files[0].name.replace(/\.part\d+$/gi, ''), { type: Number(dl) === 1 ? 'attachment' : 'inline' }),
1222
+ 'Content-Type': files[0].mime_type,
1223
+ 'Content-Length': totalFileSize.toString(),
1224
+ 'Accept-Ranges': 'bytes',
1225
+ })
1226
+ const readStream = createReadStream(filename())
1227
+ readStream
1228
+ .on('open', () => readStream.pipe(res))
1229
+ .on('error', msg => res.end(msg))
1230
+ }
1231
+ return
1232
+ }
1233
+
1234
+ // res.setHeader('Cache-Control', 'public, max-age=604800')
1235
+ // res.setHeader('ETag', Buffer.from(`${files[0].id}:${files[0].message_id}`).toString('base64'))
1236
+ res.setHeader('Content-Range', `bytes */${totalFileSize}`)
1237
+ res.setHeader('Content-Disposition', contentDisposition(files[0].name.replace(/\.part\d+$/gi, ''), { type: Number(dl) === 1 ? 'attachment' : 'inline' }))
1238
+ res.setHeader('Content-Type', files[0].mime_type)
1239
+ res.setHeader('Content-Length', totalFileSize.toString())
1240
+ res.setHeader('Accept-Ranges', 'bytes')
1241
+
1242
+ let downloaded: number = 0
1243
+
1244
+ // Sort the files based on their ".part" number
1245
+ files.sort((a, b) => {
1246
+ const aPart = Number(a.name.match(/\.part(\d+)$/i)?.[1] || 0)
1247
+ const bPart = Number(b.name.match(/\.part(\d+)$/i)?.[1] || 0)
1248
+ return aPart - bPart
1249
+ })
1250
+ try {
1251
+ writeFileSync(filename('process-'), '')
1252
+ } catch (error) {
1253
+ // ignore
1254
+ }
1255
+
1256
+ let countFiles = 1
1257
+ for (const file of files) {
1258
+ let chat
1259
+ if (file.forward_info && file.forward_info.match(/^channel\//gi)) {
1260
+ const [type, peerId, id, accessHash] = file.forward_info.split('/')
1261
+ let peer
1262
+ if (type === 'channel') {
1263
+ peer = new Api.InputPeerChannel({
1264
+ channelId: bigInt(peerId),
1265
+ accessHash: bigInt(accessHash as string)
1266
+ })
1267
+ chat = await req.tg.invoke(new Api.channels.GetMessages({
1268
+ channel: peer,
1269
+ id: [new Api.InputMessageID({ id: Number(id) })]
1270
+ }))
1271
+ }
1272
+ } else {
1273
+ chat = await req.tg.invoke(new Api.messages.GetMessages({
1274
+ id: [new Api.InputMessageID({ id: Number(file.message_id) })]
1275
+ }))
1276
+ }
1277
+ const getData = async () => await req.tg.downloadMedia(chat['messages'][0].media, {
1278
+ ...thumb ? { thumb: 0 } : {},
1279
+ outputFile: {
1280
+ write: (buffer: Buffer) => {
1281
+ downloaded += buffer.length
1282
+ if (cancel) {
1283
+ throw { status: 422, body: { error: 'canceled' } }
1284
+ } else {
1285
+ console.log(`${chat['messages'][0].id} ${downloaded}/${chat['messages'][0].media.document.size.value} (${downloaded / Number(totalFileSize) * 100 + '%'})`)
1286
+ try {
1287
+ appendFileSync(filename('process-'), buffer)
1288
+ } catch (error) {
1289
+ // ignore
1290
+ }
1291
+ res.write(buffer)
1292
+ }
1293
+ },
1294
+ close: () => {
1295
+ console.log(`${chat['messages'][0].id} ${downloaded}/${chat['messages'][0].media.document.size.value} (${downloaded / Number(totalFileSize) * 100 + '%'})`, '-end-')
1296
+ if (countFiles++ >= files.length) {
1297
+ try {
1298
+ const { size } = statSync(filename('process-'))
1299
+ if (totalFileSize.gt(bigInt(size))) {
1300
+ rmSync(filename('process-'))
1301
+ } else {
1302
+ renameSync(filename('process-'), filename())
1303
+ }
1304
+ } catch (error) {
1305
+ // ignore
1306
+ }
1307
+ res.end()
1308
+ }
1309
+ }
1310
+ }
1311
+ })
1312
+ try {
1313
+ await getData()
1314
+ } catch (error) {
1315
+ console.log(error)
1316
+ }
1317
+ }
1318
+ usage = await prisma.usages.update({
1319
+ data: {
1320
+ usage: bigInt(totalFileSize).add(bigInt(usage.usage)).toJSNumber()
1321
+ },
1322
+ where: { key: usage.key }
1323
+ })
1324
+
1325
+ while (CACHE_FILES_LIMIT < getCachedFilesSize()) {
1326
+ try {
1327
+ rmSync(`${CACHE_DIR}/${cachedFiles()[0]}`)
1328
+ } catch {
1329
+ // ignore
1330
+ }
1331
+ }
1332
+
1333
+ // res.end()
1334
+ }
1335
+
1336
+ public static async initiateSessionTG(req: Request, files?: files[]): Promise<any[]> {
1337
+ if (!files?.length) {
1338
+ throw { status: 404, body: { error: 'File not found' } }
1339
+ }
1340
+
1341
+ let data: { file: { id: string }, session: string }
1342
+ try {
1343
+ data = JSON.parse(AES.decrypt(files[0].signed_key, FILES_JWT_SECRET).toString(enc.Utf8))
1344
+ } catch (error) {
1345
+ throw { status: 401, body: { error: 'Invalid token' } }
1346
+ }
1347
+
1348
+ try {
1349
+ const session = new StringSession(data.session)
1350
+ req.tg = new TelegramClient(session, TG_CREDS.apiId, TG_CREDS.apiHash, {
1351
+ connectionRetries: CONNECTION_RETRIES,
1352
+ useWSS: false,
1353
+ ...process.env.ENV === 'production' ? { baseLogger: new Logger(LogLevel.NONE) } : {}
1354
+ })
1355
+ } catch (error) {
1356
+ throw { status: 401, body: { error: 'Invalid key' } }
1357
+ }
1358
+ return files
1359
+ }
1360
+ }
api/src/api/v1/Messages.ts ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Api } from 'telegram'
2
+ import bigInt from 'big-integer'
3
+ import { Request, Response } from 'express'
4
+ import { Redis } from '../../service/Cache'
5
+ import { Endpoint } from '../base/Endpoint'
6
+ import { Auth } from '../middlewares/Auth'
7
+
8
+ @Endpoint.API()
9
+ export class Messages {
10
+
11
+ @Endpoint.GET('/history/:type/:id', { middlewares: [Auth] })
12
+ public async history(req: Request, res: Response): Promise<any> {
13
+ const { type, id } = req.params
14
+ const { offset, limit, accessHash } = req.query
15
+
16
+ let peer: Api.InputPeerChannel | Api.InputPeerUser | Api.InputPeerChat
17
+ if (type === 'channel') {
18
+ peer = new Api.InputPeerChannel({
19
+ channelId: bigInt(id),
20
+ accessHash: bigInt(accessHash as string) })
21
+ } else if (type === 'chat') {
22
+ peer = new Api.InputPeerChat({
23
+ chatId: bigInt(id)
24
+ })
25
+ } else if (type === 'user') {
26
+ peer = new Api.InputPeerUser({
27
+ userId: bigInt(id),
28
+ accessHash: bigInt(accessHash as string) })
29
+ }
30
+
31
+ const result = await Redis.connect().getFromCacheFirst(`history:${req.user.id}:${JSON.stringify(req.params)}:${JSON.stringify(req.query)}`, async () => {
32
+ const messages = await req.tg.invoke(new Api.messages.GetHistory({
33
+ peer: peer,
34
+ limit: Number(limit) || 0,
35
+ offsetId: Number(offset) || 0,
36
+ }))
37
+ const result = JSON.parse(JSON.stringify(messages))
38
+ result.messages = result.messages?.map((msg, i) => ({ ...msg, action: { ...msg.action, className: messages['messages'][i]?.action?.className } }))
39
+ return result
40
+ }, 2)
41
+ return res.send({ messages: result })
42
+ }
43
+
44
+ @Endpoint.GET('/sponsoredMessages/:type/:id', { middlewares: [Auth] })
45
+ public async sponsoredMessages(req: Request, res: Response): Promise<any> {
46
+ const { type, id } = req.params
47
+ const { accessHash } = req.query
48
+
49
+ let peer: Api.InputPeerChannel
50
+ if (type === 'channel') {
51
+ peer = new Api.InputPeerChannel({
52
+ channelId: bigInt(id),
53
+ accessHash: bigInt(accessHash as string) })
54
+ } else {
55
+ return res.send({ messages: {
56
+ messages: [],
57
+ chats: [],
58
+ users: []
59
+ } })
60
+ }
61
+ const messages = await req.tg.invoke(new Api.channels.GetSponsoredMessages({ channel: peer }))
62
+ return res.send({ messages })
63
+ }
64
+
65
+ @Endpoint.POST('/readSponsoredMessages/:type/:id', { middlewares: [Auth] })
66
+ public async readSponsoredMessages(req: Request, res: Response): Promise<any> {
67
+ const { type, id } = req.params
68
+ const { accessHash } = req.query
69
+ const { random_id: randomId } = req.body
70
+
71
+ let peer: Api.InputPeerChannel
72
+ if (type === 'channel') {
73
+ peer = new Api.InputPeerChannel({
74
+ channelId: bigInt(id),
75
+ accessHash: bigInt(accessHash as string) })
76
+ } else {
77
+ return res.status(202).send({ accepted: true })
78
+ }
79
+ const accepted = await req.tg.invoke(new Api.channels.ViewSponsoredMessage({
80
+ channel: peer, randomId: Buffer.from(randomId)
81
+ }))
82
+ return res.status(202).send({ accepted })
83
+ }
84
+
85
+ @Endpoint.POST('/read/:type/:id', { middlewares: [Auth] })
86
+ public async read(req: Request, res: Response): Promise<any> {
87
+ const { type, id } = req.params
88
+ const { accessHash } = req.query
89
+
90
+ let peer: Api.InputPeerChannel | Api.InputPeerUser | Api.InputPeerChat
91
+ if (type === 'channel') {
92
+ peer = new Api.InputPeerChannel({
93
+ channelId: bigInt(id),
94
+ accessHash: bigInt(accessHash as string) })
95
+ } else if (type === 'chat') {
96
+ peer = new Api.InputPeerChat({
97
+ chatId: bigInt(id)
98
+ })
99
+ } else if (type === 'user') {
100
+ peer = new Api.InputPeerUser({
101
+ userId: bigInt(id),
102
+ accessHash: bigInt(accessHash as string) })
103
+ }
104
+
105
+ try {
106
+ await req.tg.invoke(new Api.messages.ReadHistory({ peer }))
107
+ } catch (error) {
108
+ await req.tg.invoke(new Api.channels.ReadHistory({ channel: peer }))
109
+ }
110
+ return res.status(202).send({ accepted: true })
111
+ }
112
+
113
+ @Endpoint.POST('/send/:type/:id', { middlewares: [Auth] })
114
+ public async send(req: Request, res: Response): Promise<any> {
115
+ const { type, id } = req.params
116
+ const { accessHash } = req.query
117
+ const { message, replyToMsgId } = req.body
118
+
119
+ let peer: Api.InputPeerChannel | Api.InputPeerUser | Api.InputPeerChat
120
+ if (type === 'channel') {
121
+ peer = new Api.InputPeerChannel({
122
+ channelId: bigInt(id),
123
+ accessHash: bigInt(accessHash as string) })
124
+ } else if (type === 'chat') {
125
+ peer = new Api.InputPeerChat({
126
+ chatId: bigInt(id)
127
+ })
128
+ } else if (type === 'user') {
129
+ peer = new Api.InputPeerUser({
130
+ userId: bigInt(id),
131
+ accessHash: bigInt(accessHash as string) })
132
+ }
133
+
134
+ const result = await req.tg.invoke(new Api.messages.SendMessage({
135
+ peer,
136
+ message,
137
+ // ...replyToMsgId ? { replyToMsgId: new Api.InputMessageReplyTo({ id: bigInt(replyToMsgId) }) } : {}
138
+ ...replyToMsgId ? { replyToMsgId: replyToMsgId } : {}
139
+ }))
140
+ return res.send({ message: result })
141
+ }
142
+
143
+ @Endpoint.PATCH('/:type/:id/:msgId', { middlewares: [Auth] })
144
+ public async update(req: Request, res: Response): Promise<any> {
145
+ const { type, id, msgId } = req.params
146
+ const { accessHash } = req.query
147
+ const { message } = req.body
148
+
149
+ let peer: Api.InputPeerChannel | Api.InputPeerUser | Api.InputPeerChat
150
+ if (type === 'channel') {
151
+ peer = new Api.InputPeerChannel({
152
+ channelId: bigInt(id),
153
+ accessHash: bigInt(accessHash as string) })
154
+ } else if (type === 'chat') {
155
+ peer = new Api.InputPeerChat({
156
+ chatId: bigInt(id)
157
+ })
158
+ } else if (type === 'user') {
159
+ peer = new Api.InputPeerUser({
160
+ userId: bigInt(id),
161
+ accessHash: bigInt(accessHash as string) })
162
+ }
163
+
164
+ const result = await req.tg.invoke(new Api.messages.EditMessage({
165
+ id: Number(msgId),
166
+ peer,
167
+ message
168
+ }))
169
+ return res.send({ message: result })
170
+ }
171
+
172
+ @Endpoint.DELETE('/:type/:id/:msgId', { middlewares: [Auth] })
173
+ public async delete(req: Request, res: Response): Promise<any> {
174
+ const { type, id, msgId } = req.params
175
+ const { accessHash } = req.query
176
+
177
+ let peer: Api.InputPeerChannel | Api.InputPeerUser | Api.InputPeerChat
178
+ if (type === 'channel') {
179
+ peer = new Api.InputPeerChannel({
180
+ channelId: bigInt(id),
181
+ accessHash: bigInt(accessHash as string) })
182
+ } else if (type === 'chat') {
183
+ peer = new Api.InputPeerChat({
184
+ chatId: bigInt(id)
185
+ })
186
+ } else if (type === 'user') {
187
+ peer = new Api.InputPeerUser({
188
+ userId: bigInt(id),
189
+ accessHash: bigInt(accessHash as string) })
190
+ }
191
+
192
+ try {
193
+ await req.tg.invoke(new Api.messages.DeleteMessages({ id: [Number(msgId)], revoke: true }))
194
+ } catch (error) {
195
+ await req.tg.invoke(new Api.channels.DeleteMessages({ id: [Number(msgId)], channel: peer }))
196
+ }
197
+ return res.status(202).send({ accepted: true })
198
+ }
199
+
200
+ @Endpoint.POST('/forward/:msgId', { middlewares: [Auth] })
201
+ public async forward(req: Request, res: Response): Promise<any> {
202
+ const { msgId } = req.params
203
+ const { from, to } = req.body as { from?: {
204
+ type: string,
205
+ id: number,
206
+ accessHash?: string
207
+ }, to: {
208
+ type: string,
209
+ id: number,
210
+ accessHash?: string
211
+ } | string }
212
+
213
+ let fromPeer: Api.InputPeerChannel | Api.InputPeerUser | Api.InputPeerChat | 'me'
214
+ let toPeer: Api.InputPeerChannel | Api.InputPeerUser | Api.InputPeerChat | string
215
+ if (!from) {
216
+ fromPeer = 'me'
217
+ } else if (from.type === 'channel') {
218
+ fromPeer = new Api.InputPeerChannel({
219
+ channelId: bigInt(from.id),
220
+ accessHash: bigInt(from.accessHash as string) })
221
+ } else if (from.type === 'chat') {
222
+ fromPeer = new Api.InputPeerChat({
223
+ chatId: bigInt(from.id)
224
+ })
225
+ } else if (from.type === 'user') {
226
+ fromPeer = new Api.InputPeerUser({
227
+ userId: bigInt(from.id),
228
+ accessHash: bigInt(from.accessHash as string) })
229
+ }
230
+
231
+ if (typeof to === 'string') {
232
+ toPeer = to
233
+ } else if (to.type === 'channel') {
234
+ toPeer = new Api.InputPeerChannel({
235
+ channelId: bigInt(to.id),
236
+ accessHash: bigInt(to.accessHash as string) })
237
+ } else if (to.type === 'chat') {
238
+ toPeer = new Api.InputPeerChat({
239
+ chatId: bigInt(to.id)
240
+ })
241
+ } else if (to.type === 'user') {
242
+ toPeer = new Api.InputPeerUser({
243
+ userId: bigInt(to.id),
244
+ accessHash: bigInt(to.accessHash as string) })
245
+ }
246
+
247
+ const result = await req.tg.invoke(new Api.messages.ForwardMessages({
248
+ id: [Number(msgId)],
249
+ fromPeer,
250
+ toPeer,
251
+ randomId: [bigInt.randBetween('-1e100', '1e100')]
252
+ }))
253
+ return res.send({ message: result })
254
+ }
255
+
256
+ @Endpoint.GET('/search', { middlewares: [Auth] })
257
+ public async search(req: Request, res: Response): Promise<any> {
258
+ const { q, offset, limit } = req.query
259
+ if (!q) {
260
+ throw { status: 400, body: { error: 'q is required' } }
261
+ }
262
+ const messages = await req.tg.invoke(new Api.messages.Search({
263
+ q: q as string,
264
+ filter: new Api.InputMessagesFilterEmpty(),
265
+ peer: new Api.InputPeerEmpty(),
266
+ limit: Number(limit) || 0,
267
+ minDate: 0,
268
+ maxDate: 0,
269
+ offsetId: 0,
270
+ addOffset: Number(offset) || 0,
271
+ maxId: 0,
272
+ minId: 0,
273
+ hash: bigInt(0),
274
+ }))
275
+ return res.send({ messages })
276
+ }
277
+
278
+ @Endpoint.GET('/globalSearch', { middlewares: [Auth] })
279
+ public async globalSearch(req: Request, res: Response): Promise<any> {
280
+ const { q, limit } = req.query
281
+ if (!q) {
282
+ throw { status: 400, body: { error: 'q is required' } }
283
+ }
284
+ const messages = await req.tg.invoke(new Api.messages.SearchGlobal({
285
+ q: q as string,
286
+ filter: new Api.InputMessagesFilterEmpty(),
287
+ offsetPeer: new Api.InputPeerEmpty(),
288
+ limit: Number(limit) || 0
289
+ }))
290
+ return res.send({ messages })
291
+ }
292
+
293
+ @Endpoint.GET('/:type/:id/avatar.jpg', { middlewares: [Auth] })
294
+ public async avatar(req: Request, res: Response): Promise<any> {
295
+ const { type, id } = req.params
296
+ let peer: Api.InputPeerChannel | Api.InputPeerUser | Api.InputPeerChat
297
+ if (type === 'channel') {
298
+ peer = new Api.InputPeerChannel({
299
+ channelId: bigInt(id),
300
+ accessHash: bigInt(req.query.accessHash as string) })
301
+ } else if (type === 'chat') {
302
+ peer = new Api.InputPeerChat({
303
+ chatId: bigInt(id)
304
+ })
305
+ } else if (type === 'user') {
306
+ peer = new Api.InputPeerUser({
307
+ userId: bigInt(id),
308
+ accessHash: bigInt(req.query.accessHash as string) })
309
+ }
310
+ try {
311
+ const file = await req.tg.downloadProfilePhoto(peer)
312
+ if (!file?.length) {
313
+ return res.redirect('https://upload.wikimedia.org/wikipedia/commons/7/7c/Profile_avatar_placeholder_large.png')
314
+ }
315
+ res.setHeader('Content-Disposition', `inline; filename=avatar-${id}.jpg`)
316
+ res.setHeader('Content-Type', 'image/jpeg')
317
+ res.setHeader('Content-Length', file.length)
318
+ res.write(file)
319
+ return res.end()
320
+ } catch (error) {
321
+ return res.redirect('https://upload.wikimedia.org/wikipedia/commons/7/7c/Profile_avatar_placeholder_large.png')
322
+ }
323
+ }
324
+ }