CloudStorage / home /views.py
thejagstudio's picture
Update home/views.py
bc76f09 verified
from django.shortcuts import render, redirect, HttpResponse
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
import json
from .models import Userdata, ip_address, movies
import threading
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from django.core.mail import send_mail
import os
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
import requests
import geocoder
import folium
from oauth2client import client
import time
gauth = GoogleAuth()
content = '{"access_token": "ya29.a0AXooCgtLK5HzYMtRs4R9J7FRZSGR3i5jUkeMeVhGjorlrgq_BupFi8d9upA2skYC5FofxUqo23Nivk_P_Hy8eRn0DWM3deSKoiWMhA3lsy05JVakD0vd2fPRaFOXfRV20jAEGt6ql9yy_0up3Y9z8u9yXZ28IUxRRZAHaCgYKASQSARISFQHGX2MipVyGD4fFFZJWXGvyd-sJnQ0171", "client_id": "895306463817-h14aujg3ohgptue5safg2d81530qs4c3.apps.googleusercontent.com", "client_secret": "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", "refresh_token": "1//0gsu0CorccmScCgYIARAAGBASNwF-L9IrF-TDYDXR_MTQGAGGf4fY4BBBSBUipsz_7c0B6HjmRYZV3uxPVU4CAJjqWoWBm0T4pxA", "token_expiry": "2024-05-25T11:14:56Z", "token_uri": "https://oauth2.googleapis.com/token", "user_agent": null, "revoke_uri": "https://oauth2.googleapis.com/revoke", "id_token": null, "id_token_jwt": null, "token_response": {"access_token": "ya29.a0AXooCgtLK5HzYMtRs4R9J7FRZSGR3i5jUkeMeVhGjorlrgq_BupFi8d9upA2skYC5FofxUqo23Nivk_P_Hy8eRn0DWM3deSKoiWMhA3lsy05JVakD0vd2fPRaFOXfRV20jAEGt6ql9yy_0up3Y9z8u9yXZ28IUxRRZAHaCgYKASQSARISFQHGX2MipVyGD4fFFZJWXGvyd-sJnQ0171", "expires_in": 3599, "refresh_token": "1//0gsu0CorccmScCgYIARAAGBASNwF-L9IrF-TDYDXR_MTQGAGGf4fY4BBBSBUipsz_7c0B6HjmRYZV3uxPVU4CAJjqWoWBm0T4pxA", "scope": "https://www.googleapis.com/auth/drive", "token_type": "Bearer"}, "scopes": ["https://www.googleapis.com/auth/drive"], "token_info_uri": "https://oauth2.googleapis.com/tokeninfo", "invalid": false, "_class": "OAuth2Credentials", "_module": "oauth2client.client"}'
gauth.credentials = client.Credentials.new_from_json(content)
if gauth.access_token_expired:
# Refresh them if expired
gauth.Refresh()
else:
gauth.Authorize()
DRIVE = GoogleDrive(gauth)
def GoogleDriveUpload(filename, folder, file):
file1 = DRIVE.CreateFile({'title': filename, 'parents': [{'id': folder}]})
file1.content = file
file1.Upload()
@csrf_exempt
def index(request):
context = {
'user': request.user
}
return render(request, 'index.html', context=context)
@csrf_exempt
def movie(request):
all_movies = movies.objects.all()
context = {
'movies': all_movies.values()
}
return render(request, 'movie.html', context=context)
@csrf_exempt
def movieDetail(request, id):
url = "https://api.themoviedb.org/3/movie/"+id+"?append_to_response=images,reviews,similar,recommendations,credits"
headers = {
'Authorization': 'Bearer eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiI2MmY0Njg4NDE4ODI2MDNjODc1Y2EwZDMyMzE1NzkyZSIsInN1YiI6IjYyMDBlNmFmMWZkMzZmMDA2NmI5OTczNSIsInNjb3BlcyI6WyJhcGlfcmVhZCJdLCJ2ZXJzaW9uIjoxfQ.mt_t8wqYYl5b8AlDy5npgiF7sbb8ZaDh_XPauDgMt8I',
'accept': 'application/json'
}
response = requests.request("GET", url, headers=headers)
data = response.json()
try:
movie = movies.objects.filter(tmdbId=id).first()
data["driveLink"] = movie.driveLink
url = "https://drive.google.com/get_video_info?docid="+movie.driveLink + "&drive_originator_app=303"
response = requests.request("GET", url, headers=headers)
urlData = response.text
parsed_url = urlparse("https://drive.google.com/?"+urlData)
urlData = json.loads(parse_qs(parsed_url.query)["player_response"][0])
data["watchLink"] = urlData
except Exception as e:
print(e)
context = {
'data': data
}
return render(request, 'movieDetail.html', context=context)
@csrf_exempt
def user_login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
messages.success(request, ('You have been logged in!'))
# print('logged in')
return redirect('index')
else:
messages.success(request, ('Error logging in - please try again.'))
# print('error logging in')
return render(request, 'login.html')
return render(request, 'login.html')
@csrf_exempt
def sign_up(request):
if request.method == 'POST':
name = request.POST['name']
email = request.POST['email']
password = request.POST['password']
password2 = request.POST['password1']
user = authenticate(request, email=email, password=password)
if user is not None and password == password2:
login(request, user)
messages.success(request, ('You have been logged in!'))
# print('logged in')
return redirect('index')
elif user is None and password == password2:
user = User.objects.create_user(username=email, email=email, password=password, first_name=name)
user.save()
messages.success(request, ('Created new user!'))
login(request, user)
folder = '1N3uD81zuXY_23esOFWRvN2Fp4zEbCrzy'
new_folder = DRIVE.CreateFile({'title': name, 'mimeType': 'application/vnd.google-apps.folder', 'parents': [{'id': folder}]})
new_folder.Upload()
new_folder.InsertPermission({'type': 'user', 'value': email, 'role': 'writer'})
dataObj = Userdata(user_id=request.user, folder=new_folder['id'])
dataObj.save()
# print('new user created')
return redirect('index')
else:
pass
return render(request, 'signup.html')
@csrf_exempt
@login_required
def user_logout(request):
logout(request)
messages.success(request, ('You have been logged out!'))
# print('logged out')
return redirect('index')
@csrf_exempt
@login_required
def upload(request):
return render(request, 'upload.html')
@csrf_exempt
@login_required
def uploader(request):
global gauth
if gauth.access_token_expired:
# Refresh them if expired
gauth.Refresh()
if request.method == 'POST':
folder = 'files/'
file = request.FILES['file']
title = request.POST['title']
if title == '':
title = file.name
if file.name == '':
return redirect('/upload/')
folder_id = Userdata.objects.get(user_id=request.user).folder
thread = threading.Thread(target=GoogleDriveUpload, args=(title, folder_id, file))
thread.start()
thread.join()
return redirect('/upload/')
@csrf_exempt
def uploaderAI(request):
global gauth
if gauth.access_token_expired:
# Refresh them if expired
gauth.Refresh()
if request.method == 'POST':
try:
file = request.FILES['file']
title = request.POST['title']
prompt = request.POST['prompt']
if title == '':
title = file.name
folder_id = "1Hxpc5aT4xl9Nz1QUQJirJcnaT9J1QrzR"
file1 = DRIVE.CreateFile({'title': title, 'description':prompt, 'parents': [{'id': folder_id}]})
file1.content = file
file1.Upload()
return HttpResponse(json.dumps({'status': 'success'}), content_type='application/json')
except Exception as e:
return HttpResponse(json.dumps({'status': 'error','error':str(e)}), content_type='application/json')
@csrf_exempt
@login_required
def list(request):
global gauth
if gauth.access_token_expired:
# Refresh them if expired
gauth.Refresh()
files = []
folders = []
folder_id = Userdata.objects.get(user_id=request.user).folder
list_files = DRIVE.ListFile({'q': "'%s' in parents and trashed=false" % folder_id}).GetList()
for file in list_files:
if file['title'] != 'Deleted' and file['title'] != 'DeletedFile' and file['mimeType'] != 'application/vnd.google-apps.folder':
files.append([file['title'], file['embedLink'], file['id'], file["iconLink"].replace("/16/", "/32/"), file["webContentLink"]])
elif file['mimeType'] == 'application/vnd.google-apps.folder':
folders.append([file['title'], "/list/"+file['id'][::-1]])
else:
pass
context = {'files': files, 'folders': folders, 'back': False}
return render(request, 'list.html', context=context)
@csrf_exempt
@login_required
def folder_list(request, id):
global gauth
if gauth.access_token_expired:
# Refresh them if expired
gauth.Refresh()
files = []
folders = []
folder_id = id[::-1] # Userdata.objects.get(user_id=request.user).folder
list_files = DRIVE.ListFile({'q': "'%s' in parents and trashed=false" % folder_id}).GetList()
for file in list_files:
if file['title'] != 'Deleted' and file['mimeType'] != 'application/vnd.google-apps.folder':
files.append([file['title'], file['embedLink'], file['id'], file["iconLink"].replace("/16/", "/32/"), file["webContentLink"]])
elif file['mimeType'] == 'application/vnd.google-apps.folder':
folders.append([file['title'], "/list/"+file['id'][::-1]])
else:
pass
context = {'files': files, 'folders': folders, 'back': True}
return render(request, 'list.html', context=context)
@csrf_exempt
@login_required
def deleteFile(request):
global gauth
if gauth.access_token_expired:
# Refresh them if expired
gauth.Refresh()
if request.method == 'POST':
file_id = json.loads(request.body)['file_id']
file = DRIVE.CreateFile({'id': file_id})
file.Trash()
return HttpResponse(json.dumps({'status': 'success'}), content_type='application/json')
@csrf_exempt
@login_required
def renameFile(request):
global gauth
if gauth.access_token_expired:
# Refresh them if expired
gauth.Refresh()
if request.method == 'POST':
data = json.loads(request.body)
file_id = data['file_id']
new_name = data['new_name']
file = DRIVE.CreateFile({'id': file_id})
file.FetchMetadata(fields="title")
file['title'] = new_name
file.Upload()
return HttpResponse(json.dumps({'status': 'success'}), content_type='application/json')
def torrentDownloader(link):
import libtorrent as lt
ses = lt.session()
ses.listen_on(6881, 6891)
params = {
'save_path': '/tmp/',
'storage_mode': lt.storage_mode_t(2)
}
handle = lt.add_magnet_uri(ses, link, params)
ses.start_dht()
while (not handle.has_metadata()):
time.sleep(1)
while (handle.status().state != lt.torrent_status.seeding):
s = handle.status()
state_str = ['queued', 'checking', 'downloading metadata', 'downloading', 'finished', 'seeding', 'allocating']
print('%.2f%% complete (down: %.1f kb/s up: %.1f kB/s peers: %d) %s ' % (s.progress * 100, s.download_rate / 1000, s.upload_rate / 1000, s.num_peers, state_str[s.state]))
time.sleep(5)
with open('/tmp/'+handle.file_name, 'rb') as f:
file = f.read()
file1 = DRIVE.CreateFile({'title': handle.file_name, 'parents': [{'id': '1l6oqVFu-Ys025p7PKjIY0Nwgdr08MwlB'}]})
file1.content = file
file1.Upload()
print('Uploaded torrent file to drive from link: ', torrent_file.file_name)
@csrf_exempt
def movieDownloader(request):
if request.method == 'POST':
data = json.loads(request.body)
movie = data['movie']
tmdbId = data['tmdbId']
torrentLink = data['torrentLink']
t1 = threading.Thread(target=torrentDownloader, args=(torrentLink,))
t1.start()
return HttpResponse(json.dumps({'status': 'success'}), content_type='application/json')
def ipGetter(request):
ip = request.GET.get('ip', '')
ipIn = ip_address.objects.filter(ip=ip).first()
if ipIn is None:
new_entry = ip_address(ip=ip)
new_entry.save()
return HttpResponse(json.dumps({'status': 'success'}), content_type='application/json')
@login_required
def godMode(request):
if request.user.is_superuser:
ips = ip_address.objects.all()
ipF = ips[0].ip
g = geocoder.ip(ipF)
myAddress = g.latlng
my_map1 = folium.Map(location=myAddress, zoom_start=12)
for ip in ips:
g = geocoder.ip(ip.ip)
myAddress = g.latlng
folium.Marker(myAddress).add_to(my_map1)
my_map1.save('templates/godMode.html')
return render(request, 'godMode.html')