File size: 9,653 Bytes
e566133
 
 
 
 
 
 
 
6c92dfc
e566133
 
 
 
 
 
 
 
 
87159d4
e566133
 
 
4abcb4b
 
 
 
e566133
 
 
 
 
 
 
4abcb4b
e566133
87159d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b12dfa5
87159d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4abcb4b
e566133
 
 
 
 
 
0616e4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4abcb4b
0616e4e
e566133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4abcb4b
e566133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f0d5402
 
 
 
 
 
 
e566133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c92dfc
c5553ae
6c92dfc
b938ac5
6c92dfc
 
f0d5402
6c92dfc
 
 
e566133
f0d5402
b938ac5
 
 
e1056a6
87159d4
e566133
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
import os

import json
import time
import math
import logging
import asyncio
import traceback
import aiohttp_cors
from aiohttp import web
from pyrogram import raw
from bson import ObjectId
from bson.json_util import dumps
from aiohttp.http_exceptions import BadStatusLine

from FileStream.bot import req_client
from FileStream.config import Telegram,Server
from FileStream.Database import Database
from FileStream.TMDB.Endpoint import search_tmdb_any,search_tmdb_tv,search_tmdb_movies
from FileStream.server.exceptions import FIleNotFound, InvalidHash

from .Functions.downloader import media_streamer
CORS_HEADERS = {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Headers": "*"
}
async def handle_v2(request):
    return web.Response(text="Hello from app api!")

async def list_all_files_db(request):
  db = Database(Telegram.DATABASE_URL, Telegram.SESSION_NAME)
  files= await db.get_all_files_api()
  #print(files, type(files))
  return web.json_response(json.loads(dumps(files)), headers=CORS_HEADERS)

async def list_all_tmdb_movies_from_db(request):
  db = Database(Telegram.DATABASE_URL, Telegram.SESSION_NAME)
  files= await db.get_all_files()
  #print(files)
  response=[]
  async for row in files:
    #print(row['file']['caption'])
    try :
      #print("* Response",search_tmdb(row['file']['caption'] if row['file']['caption'] else row['file']['file_name']))
      resp = search_tmdb_movies( str(row['file']['caption']) if str(row['file']['caption']) else str(row['file']['file_name']))
      if resp != None :
        #resp= dict(resp)
        #print("TMDB Response :",resp)
        response.append(resp)
      else:
        print("\n * Skipped:",row['file']['caption'],str(row['file']['file_name']))
        continue
    except Exception as e:
      print("Error ",e)
      break
    
  #print(response)
  # Convert Python data to JSON
  #json_response = json.dumps(response).encode('utf-8')
  # Return as aiohttp response using web.json_response
  #return web.json_response(response)
  return web.json_response(json.loads(dumps(response)),headers=CORS_HEADERS)

async def list_all_tmdb_tv_from_db(request):
  db = Database(Telegram.DATABASE_URL, Telegram.SESSION_NAME)
  files= await db.get_all_files()
  #print(files)
  response=[]
  async for row in files:
    #print(row['file']['caption'])
    try :
      #print("* Response",search_tmdb(row['file']['caption'] if row['file']['caption'] else row['file']['file_name']))
      resp = search_tmdb_tv( str(row['file']['caption']) if str(row['file']['caption']) else str(row['file']['file_name']))
      if resp != None :
        #resp= dict(resp)
        #print("TMDB Response :",resp)
        response.append(resp)
      else:
        print("\n * Skipped:",row['file']['caption'],str(row['file']['file_name']))
        continue
    except Exception as e:
      print("Error ",e)
      break
    
  #print(response)
  # Convert Python data to JSON
  #json_response = json.dumps(response).encode('utf-8')
  # Return as aiohttp response using web.json_response
  #return web.json_response(response)
  return web.json_response(json.loads(dumps(response)), headers=CORS_HEADERS)

#api.router.add_get('/tmdb/list', list_all_files_tmdb)
async def list_all_files_tmdb(request):
  db = Database(Telegram.DATABASE_URL, Telegram.SESSION_NAME)
  files= await db.get_all_files()
  #print(files)
  #response=[]
  async def data_generator():
    async for row in files:
      #print(row['file']['caption'])
      try :
        #print("* Response",search_tmdb(row['file']['caption'] if row['file']['caption'] else row['file']['file_name']))
        resp = search_tmdb_any( str(row['file']['caption']) if str(row['file']['caption']) else str(row['file']['file_name']))
        if resp != None :
          #resp= dict(resp)
          #print("TMDB Response :",resp)
          #response.append(resp)
          yield json.dumps(resp) +  + '\n'

        else:
          print("\n * Skipped:",row['file']['caption'],str(row['file']['file_name']))
          continue

      except Exception as e:
        print("Error ",e)
        break
              
  return web.Response(body=data_generator(), content_type='application/json', headers=CORS_HEADERS)
  #return web.json_response(json.loads(dumps(response)))

#api.router.add_get('/tmdb/files', list_all_files)
async def list_all_files(request):
  db = Database(Telegram.DATABASE_URL, Telegram.SESSION_NAME)
  files=await db.get_all_files_api()
  #print(files[0])
  """{"_id":
  {"$oid":"664b9bee136af99d40f36ac4"},
  "user_id":"780583126",
  "user_type":"TELEGRAM",
  "message_id":{"$numberInt":"230"},
  "location":{"$numberLong":"-1001713565158"},
  "file":{
    "file_id":"BAACAgIAAx0EZiLt5gAD5mZLm_BFwLE0BtOz3x74uJVDMPyKAAIISAACVyEJSugUJlXYybnGHgQ",
    "caption":"Godzilla x Kong: The New Empire (2024)IMDB  6.5/10..Audio - Hindi + English",
    "file_unique_id":"AgADCEgAAlchCUo",
    "file_name":"[Tg- @New_Movies_OnTG] Godzilla x Kong: The New Empire (2024.mkv",
    "file_size":{"$numberInt":"1191876267"},
    "mime_type":"video/x-matroska",
    "tagged_users":{"780583126":"PUBLIC","908083534":"PUBLIC"}},
    "time":"Tue May 21 00:22:28 2024",
    "privacy_type":"PUBLIC",
    "file_ids":{"7143040931":"BAACAgIAAx0CZiLt5gAD5mZLm_JkEd4FIhfPJMNx4yrn_ku2AAIISAACVyEJStMWKGOMGmA8HgQ","7137723582":"BAACAgIAAx0CZiLt5gAD5mZLm_L1n-OtIh2xs9VTfPg9ng-jAAIISAACVyEJSgwG7RQMGjI4HgQ","7186717764":"BAACAgIAAx0CZiLt5gAD5mZLm_LHCB1_h5anoEEStvf4l_fyAAIISAACVyEJSpNn5Oa7x8LDHgQ","6589995279":"BAACAgIAAx0CZiLt5gAD5mZLm_JkQEwGvFwxwQXtfMk9FrBYAAIISAACVyEJSovis_Nx3os5HgQ","6539834495":"BAACAgIAAx0CZiLt5gAD5mZblPC_hDA4ZXq9Uw2NiHhRZakvAAIISAACVyEJSk4a1yBMKm1jHgQ","7142960273":"BAACAgIAAx0CZiLt5gAD5mZblU_WJD3j98Z_fwS4zkhZU16WAAIISAACVyEJStP84jRi0R9YHgQ"}}
  """ 
  resp=[{
    "adult": False,
    "backdrop_path": "/c1bz69r0v065TGFA5nqBiKzPDys.jpg",
    "genre_ids": [
      35,
      10751,
      10402
    ],
    "id": f"{row['_id']}",
    "original_language": "en-hi",
    "original_title": f"{str(row['file']['caption'])}",
    "overview": "XRepo Movies",
    "popularity": 1710.176,
    "poster_path": "/irIS5Tn3TXjNi1R9BpWvGAN4CZ1.jpg",
    "release_date": "2022-10-07",
    "title": f"{str(row['file']['caption'])}",
    "link": f"{Server.URL}api/dl/{row['_id']}",
    "vote_average": 7.8,
    "vote_count": 122,
    } 
     for row in files]
  return web.json_response(json.loads(dumps(resp)), headers=CORS_HEADERS)

#----------------------------------------Upload----------------------------------------------#
#@routes.post("/upload")
async def upload_file(request: web.Request):

  data = await request.post()
  file = data.get('file').file
  chunk = file.read()
  """
  user_id :
  file_id :"BAACAgUAAxkBAAJBHGYI_aJSvyL_ijKwrVHQVzFgC1YZAAItDQACOnNAVMIpWwl6b63EHg…"
  file_unique_id :"AgADLQ0AAjpzQFQ"
  file_name :"Dadur_Kirti_S01_COMBINED_720p_HOICHOI_WEB_DL_Bengali@COOL_MOVIES.mp4"
  file_size : 1354816011
  mime_type : "video/mp4"
  time : 1711865251.1016757
  user_type: "TELEGRAM"/"WEB"
  privacy_type: "PUBLIC"/"PRIVATE"
  file_ids :
  """
  file_details = dict(user_id="thebinary1",
                      dropzone_id=str(data["dzuuid"]),
                      file=dict(file_id=str(data["dzuuid"]),
                      file_unique_id=str(data["dzuuid"]),
                      file_name=str(data.get('file').filename),
                      file_size=int(data["dztotalfilesize"]),
                      mime_type=mime_identifier(str(data.get('file').filename)),
                      part_size=int(data["dzchunksize"]),
                      file_part=int(data["dzchunkindex"]),
                      total_parts=int(data["dztotalchunkcount"])),
                      time=Time_ISTKolNow(),
                      user_type="WEB",
                      privacy_type="PRIVATE")

  print(file_details) if (file_details["file"]["file_part"] == 0) else None
  client_req = await req_client()
  #faster_client = client_req["client"]
  #index = client_req["index"]
  print("using :", client_req["index"])
  tg_connect = TeleUploader(client_req["client"])
  main = await tg_connect.upload_web_file(file_details, chunk)
  #print("Response:", main)
  return web.json_response({
      "status": main.get("status"),
      "message": main.get("message")
  })


#-------------Routes to Downloada File Witha Path-----------------#
#@routes.get("/dl/{path}", allow_head=True)
async def stream_handler(request: web.Request):
  try:
    path = request.match_info["path"]
    return await media_streamer(request, path)
  except InvalidHash as e:
    raise web.HTTPForbidden(text=e.message)
  except FIleNotFound as e:
    raise web.HTTPNotFound(text=e.message)
  except (AttributeError, BadStatusLine, ConnectionResetError):
    pass
  except Exception as e:
    traceback.print_exc()
    logging.critical(e.with_traceback(None))
    logging.debug(traceback.format_exc())
    raise web.HTTPInternalServerError(text=str(e))


api = web.Application()

cors = aiohttp_cors.setup(api, defaults={
    "*": aiohttp_cors.ResourceOptions(
        allow_credentials=False,
        expose_headers="*",
        allow_headers="*",
        allow_methods="*" #["GET"]  Allowing specific methods
    )
})

api.router.add_get('/', handle_v2)
cors.add(api.router.add_get('/files', list_all_files_db))
cors.add(api.router.add_get('/files/mix', list_all_files))
cors.add(api.router.add_get('/tmdb/mix', list_all_files_tmdb))
cors.add(api.router.add_get('/tmdb/tv', list_all_tmdb_tv_from_db))
cors.add(api.router.add_get('/tmdb/movies', list_all_tmdb_movies_from_db))

api.router.add_get('/upload', upload_file)
api.router.add_get('/dl/{path}', stream_handler)