gitea-migrator/migrator/views.py
2020-08-03 22:05:16 +02:00

117 lines
3.2 KiB
Python

from django.shortcuts import render, redirect
from django.http import JsonResponse, HttpResponse
from . import settings
from .helper import get_dict_from_query
from .models import *
from . import tasks
from .api import *
def migration_create(request):
if request.method == "POST":
projects = get_dict_from_query(request.POST,"projects")
migration = Migration(
gitlab_token = request.POST["gitlab_token"],
gitea_token = request.POST["gitea_token"],
username = request.POST["username"],
)
migration.save()
for project in projects:
repo = Repository(
migration = migration,
path_with_namespace = project
)
repo.save()
tasks.migrate_repository(repo.id)
return redirect("migration_progress", migration.id)
return render(request, "migration_create.html")
def migration_progess(request, migration_key):
try:
migration = Migration.objects.prefetch_related('repositories').get(pk=migration_key)
except Migration.DoesNotExist:
return redirect("migration_create")
return render(request, "migration_progress.html", {
'migration': migration,
})
def migration_status(request, migration_key):
repositories = Repository.objects.filter(
migration_id = migration_key,
).all()
data = []
for repo in repositories:
info = { 'id': repo.id, 'status': repo.result }
if repo.result == Status.ERROR:
info['message'] = repo.error_message
data.append(info)
return JsonResponse(data,safe=False)
def fetch_gitlab_projects(request):
gitlab_token = request.GET.get("gitlab_token", None)
if gitlab_token is None:
return JsonResponse({ 'error' : 'Missing token' })
gitlabapi = GitlabAPI(gitlab_token)
response = gitlabapi.get('/user')
if response.status_code != 200:
return JsonResponse({ 'error' : 'API error' })
data = response.json()
try:
username = data['username']
except KeyError:
return JsonResponse({ 'error' : 'API error' })
projects = []
page = 1
while True:
response = gitlabapi.get('/projects', params={
'owned': 1,
'page': page,
'per_page': 100,
})
if response.status_code != 200:
return JsonResponse({ 'error' : 'API error' })
data = response.json()
if len(data) == 0:
break
for gitlab_project in data:
try:
projects.append(gitlab_project['path_with_namespace'])
except KeyError:
return JsonResponse({ 'error' : 'API error' })
page+=1
return JsonResponse({
'username' : username,
'projects' : sorted(projects)
})
def check_gitea_access(request):
gitea_token = request.GET.get("gitea_token", None)
if gitea_token is None:
return JsonResponse({ 'success': False })
response = GiteaAPI(gitea_token).get('/user')
if response.status_code == 200:
return JsonResponse({ 'success': True })
else:
return JsonResponse({ 'success': False })