Create base structure for Django project
This commit is contained in:
parent
95f8d5741a
commit
3294ef2a82
13 changed files with 405 additions and 258 deletions
0
musik/__init__.py
Normal file
0
musik/__init__.py
Normal file
|
@ -1,118 +0,0 @@
|
|||
import argparse
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
from .list import generate_list, write_blacklist, write_results
|
||||
|
||||
ROOT_PATH = Path("./lists")
|
||||
BLACKLIST = Path("./blacklists")
|
||||
RESULTS = Path("./results")
|
||||
NUM_MUS = 2
|
||||
|
||||
|
||||
def main():
|
||||
# Lecture arguments console
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="python -m musik",
|
||||
description="Lancer une partie de Musik",
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
)
|
||||
parser.add_argument(
|
||||
"-a",
|
||||
"--no-api",
|
||||
action="store_true",
|
||||
help="Désactiver l'API Youtube ; affiche la liste des liens",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-c",
|
||||
"--no-save-creds",
|
||||
action="store_true",
|
||||
help="Désactiver l'enregistrement de la connexion Youtube",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-b",
|
||||
"--no-blacklist",
|
||||
action="store_true",
|
||||
help="Désactiver le méchanisme de blacklist en lecture et écriture",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-n",
|
||||
"--number",
|
||||
type=int,
|
||||
default=NUM_MUS,
|
||||
help="Modifier le nombre de musiques par joueur",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--lists",
|
||||
type=Path,
|
||||
default=ROOT_PATH,
|
||||
help="Sélectionner le dossier contenant les listes de musiques",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--blacklists",
|
||||
type=Path,
|
||||
default=BLACKLIST,
|
||||
help="Sélectionner le dossier contenant les blacklist",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--results",
|
||||
type=Path,
|
||||
default=RESULTS,
|
||||
help="Sélectionner le dossier pour stocker les résultats",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-v",
|
||||
"--verbose",
|
||||
action="store_const",
|
||||
const=logging.DEBUG,
|
||||
default=logging.INFO,
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
if not args.no_api:
|
||||
from .youtube import create_playlist
|
||||
|
||||
# Configuration logs
|
||||
logger = logging.getLogger("musik")
|
||||
logging.basicConfig(
|
||||
level=args.verbose, format="%(asctime)s\t%(levelname)s\t%(message)s"
|
||||
)
|
||||
|
||||
logger.info("Vérification")
|
||||
if not args.lists.is_dir():
|
||||
logger.error(f"Le dossier <{args.lists}> n'existe pas.")
|
||||
return
|
||||
if not args.blacklists.is_dir():
|
||||
logger.warning(f"Le dossier <{args.blacklists}> n'existe pas, il va être créé.")
|
||||
args.blacklists.mkdir()
|
||||
if not args.results.is_dir():
|
||||
logger.warning(f"Le dossier <{args.results}> n'existe pas, il va être créé.")
|
||||
args.results.mkdir()
|
||||
if args.number < 1:
|
||||
logger.error("Le nombre de musiques est inférieur à 1.")
|
||||
return
|
||||
|
||||
# Lecture des fichiers musique dans ROOT_PATH
|
||||
# Faire un dossier différent pour les gens qui ne jouent pas
|
||||
logger.info("Génération de la liste de musiques")
|
||||
musik_list = generate_list(args)
|
||||
|
||||
if not args.no_api:
|
||||
create_playlist(musik_list, args)
|
||||
else:
|
||||
logger.info("Liste des musiques :")
|
||||
for _, musik in musik_list:
|
||||
logger.info(f"# https://www.youtube.com/watch?v={musik}")
|
||||
|
||||
# Écriture des résultats
|
||||
logger.info("Écriture des résultats")
|
||||
write_results(musik_list, args)
|
||||
|
||||
# Écriture de la blacklist
|
||||
if not args.no_blacklist:
|
||||
logger.info("Écriture de la blacklist")
|
||||
write_blacklist(musik_list, args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
16
musik/asgi.py
Normal file
16
musik/asgi.py
Normal file
|
@ -0,0 +1,16 @@
|
|||
"""
|
||||
ASGI config for musik project.
|
||||
|
||||
It exposes the ASGI callable as a module-level variable named ``application``.
|
||||
|
||||
For more information on this file, see
|
||||
https://docs.djangoproject.com/en/5.2/howto/deployment/asgi/
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from django.core.asgi import get_asgi_application
|
||||
|
||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "musik.settings")
|
||||
|
||||
application = get_asgi_application()
|
|
@ -1,72 +0,0 @@
|
|||
import logging
|
||||
import random
|
||||
import sys
|
||||
from datetime import datetime
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
logger = logging.getLogger("musik.list")
|
||||
|
||||
|
||||
def bl_path(bl, user):
|
||||
return bl.joinpath(user).with_suffix(".txt")
|
||||
|
||||
|
||||
def parse_musik(raw):
|
||||
if "youtube.com" in raw:
|
||||
return parse_qs(urlparse(raw).query).get("v", [None])[0]
|
||||
elif "youtu.be" in raw:
|
||||
return urlparse(raw).path[1:]
|
||||
|
||||
return raw
|
||||
|
||||
|
||||
def generate_list(args):
|
||||
musik_list = []
|
||||
user_list = []
|
||||
|
||||
for q in args.lists.iterdir():
|
||||
_u = q.stem
|
||||
logger.info(f"Musiques de {_u}")
|
||||
if (not args.no_blacklist) and bl_path(args.blacklists, _u).exists():
|
||||
logger.debug("Blacklist")
|
||||
with bl_path(args.blacklists, _u).open("r") as blf:
|
||||
blacklist = blf.read().splitlines()
|
||||
else:
|
||||
blacklist = []
|
||||
|
||||
logger.debug("Lecture de la liste")
|
||||
with q.open() as f:
|
||||
_raw_musiks = [parse_musik(_musik) for _musik in f.read().splitlines()]
|
||||
_musiks = list(set(filter(lambda _m: _m not in blacklist, _raw_musiks)))
|
||||
|
||||
if len(_musiks) < args.number:
|
||||
logger.error(
|
||||
f"{_u} a {len(_musiks)} musique(s) non black-listée(s) "
|
||||
f"au lieu de {args.number}"
|
||||
)
|
||||
sys.exit()
|
||||
|
||||
logger.debug("Ajout des musiques à la liste")
|
||||
musik_list += random.sample(_musiks, args.number)
|
||||
user_list += [_u] * args.number
|
||||
|
||||
# Shuffle musics
|
||||
logger.info("Classement aléatoire des musiques")
|
||||
user_musik_list = list(zip(user_list, musik_list))
|
||||
random.shuffle(user_musik_list)
|
||||
return user_musik_list
|
||||
|
||||
|
||||
def write_blacklist(musik_list, args):
|
||||
for user, musik in musik_list:
|
||||
with bl_path(args.blacklists, user).open("a") as f:
|
||||
f.write("\n")
|
||||
f.write(musik)
|
||||
|
||||
|
||||
def write_results(musik_list, args):
|
||||
with args.results.joinpath(datetime.now().strftime("%Y%m%d %H%M%S")).with_suffix(
|
||||
".txt"
|
||||
).open("a") as f:
|
||||
f.write(f"Résultats {datetime.now()}\n\n")
|
||||
f.write("\n".join("\t".join(um) for um in musik_list))
|
122
musik/settings.py
Normal file
122
musik/settings.py
Normal file
|
@ -0,0 +1,122 @@
|
|||
"""
|
||||
Django settings for musik project.
|
||||
|
||||
Generated by 'django-admin startproject' using Django 5.2.3.
|
||||
|
||||
For more information on this file, see
|
||||
https://docs.djangoproject.com/en/5.2/topics/settings/
|
||||
|
||||
For the full list of settings and their values, see
|
||||
https://docs.djangoproject.com/en/5.2/ref/settings/
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
# Build paths inside the project like this: BASE_DIR / 'subdir'.
|
||||
BASE_DIR = Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
# Quick-start development settings - unsuitable for production
|
||||
# See https://docs.djangoproject.com/en/5.2/howto/deployment/checklist/
|
||||
|
||||
# SECURITY WARNING: keep the secret key used in production secret!
|
||||
SECRET_KEY = "django-insecure-&z*xu$^w8btr(%1!y#+0a98)l_q*+*6z54611pi678mdpsar_="
|
||||
|
||||
# SECURITY WARNING: don't run with debug turned on in production!
|
||||
DEBUG = True
|
||||
|
||||
ALLOWED_HOSTS = []
|
||||
|
||||
|
||||
# Application definition
|
||||
|
||||
INSTALLED_APPS = [
|
||||
"django.contrib.admin",
|
||||
"django.contrib.auth",
|
||||
"django.contrib.contenttypes",
|
||||
"django.contrib.sessions",
|
||||
"django.contrib.messages",
|
||||
"django.contrib.staticfiles",
|
||||
]
|
||||
|
||||
MIDDLEWARE = [
|
||||
"django.middleware.security.SecurityMiddleware",
|
||||
"django.contrib.sessions.middleware.SessionMiddleware",
|
||||
"django.middleware.common.CommonMiddleware",
|
||||
"django.middleware.csrf.CsrfViewMiddleware",
|
||||
"django.contrib.auth.middleware.AuthenticationMiddleware",
|
||||
"django.contrib.messages.middleware.MessageMiddleware",
|
||||
"django.middleware.clickjacking.XFrameOptionsMiddleware",
|
||||
]
|
||||
|
||||
ROOT_URLCONF = "musik.urls"
|
||||
|
||||
TEMPLATES = [
|
||||
{
|
||||
"BACKEND": "django.template.backends.django.DjangoTemplates",
|
||||
"DIRS": [],
|
||||
"APP_DIRS": True,
|
||||
"OPTIONS": {
|
||||
"context_processors": [
|
||||
"django.template.context_processors.request",
|
||||
"django.contrib.auth.context_processors.auth",
|
||||
"django.contrib.messages.context_processors.messages",
|
||||
],
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
WSGI_APPLICATION = "musik.wsgi.application"
|
||||
|
||||
|
||||
# Database
|
||||
# https://docs.djangoproject.com/en/5.2/ref/settings/#databases
|
||||
|
||||
DATABASES = {
|
||||
"default": {
|
||||
"ENGINE": "django.db.backends.sqlite3",
|
||||
"NAME": BASE_DIR / "db.sqlite3",
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
# Password validation
|
||||
# https://docs.djangoproject.com/en/5.2/ref/settings/#auth-password-validators
|
||||
|
||||
AUTH_PASSWORD_VALIDATORS = [
|
||||
{
|
||||
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
|
||||
},
|
||||
{
|
||||
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
|
||||
},
|
||||
{
|
||||
"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
|
||||
},
|
||||
{
|
||||
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
# Internationalization
|
||||
# https://docs.djangoproject.com/en/5.2/topics/i18n/
|
||||
|
||||
LANGUAGE_CODE = "en-us"
|
||||
|
||||
TIME_ZONE = "UTC"
|
||||
|
||||
USE_I18N = True
|
||||
|
||||
USE_TZ = True
|
||||
|
||||
|
||||
# Static files (CSS, JavaScript, Images)
|
||||
# https://docs.djangoproject.com/en/5.2/howto/static-files/
|
||||
|
||||
STATIC_URL = "static/"
|
||||
|
||||
# Default primary key field type
|
||||
# https://docs.djangoproject.com/en/5.2/ref/settings/#default-auto-field
|
||||
|
||||
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
|
23
musik/urls.py
Normal file
23
musik/urls.py
Normal file
|
@ -0,0 +1,23 @@
|
|||
"""
|
||||
URL configuration for musik project.
|
||||
|
||||
The `urlpatterns` list routes URLs to views. For more information please see:
|
||||
https://docs.djangoproject.com/en/5.2/topics/http/urls/
|
||||
Examples:
|
||||
Function views
|
||||
1. Add an import: from my_app import views
|
||||
2. Add a URL to urlpatterns: path('', views.home, name='home')
|
||||
Class-based views
|
||||
1. Add an import: from other_app.views import Home
|
||||
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
|
||||
Including another URLconf
|
||||
1. Import the include() function: from django.urls import include, path
|
||||
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
|
||||
"""
|
||||
|
||||
from django.contrib import admin
|
||||
from django.urls import path
|
||||
|
||||
urlpatterns = [
|
||||
path("admin/", admin.site.urls),
|
||||
]
|
16
musik/wsgi.py
Normal file
16
musik/wsgi.py
Normal file
|
@ -0,0 +1,16 @@
|
|||
"""
|
||||
WSGI config for musik project.
|
||||
|
||||
It exposes the WSGI callable as a module-level variable named ``application``.
|
||||
|
||||
For more information on this file, see
|
||||
https://docs.djangoproject.com/en/5.2/howto/deployment/wsgi/
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from django.core.wsgi import get_wsgi_application
|
||||
|
||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "musik.settings")
|
||||
|
||||
application = get_wsgi_application()
|
|
@ -1,68 +0,0 @@
|
|||
import logging
|
||||
import pickle
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
import google_auth_oauthlib.flow
|
||||
import googleapiclient.discovery
|
||||
import googleapiclient.errors
|
||||
|
||||
logger = logging.getLogger("musik.youtube")
|
||||
|
||||
|
||||
def create_playlist(musik_list, args):
|
||||
pickle_path = Path("./youtube.pickle")
|
||||
|
||||
# Connexion à l'API youtube, obtention d'un jeton OAuth
|
||||
logger.info("Connexion à l'API Youtube")
|
||||
flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
|
||||
"./secret.json", ["https://www.googleapis.com/auth/youtube.force-ssl"]
|
||||
)
|
||||
if (not args.no_save_creds) and pickle_path.is_file():
|
||||
with pickle_path.open("rb") as f:
|
||||
credentials = pickle.load(f)
|
||||
else:
|
||||
credentials = flow.run_local_server(port=0)
|
||||
if not args.no_save_creds:
|
||||
with pickle_path.open("wb") as f:
|
||||
pickle.dump(credentials, f)
|
||||
|
||||
youtube = googleapiclient.discovery.build("youtube", "v3", credentials=credentials)
|
||||
|
||||
# Création d'une playlist
|
||||
logger.info("Création de la playlist")
|
||||
pl_request = youtube.playlists().insert(
|
||||
part="snippet,status",
|
||||
body={
|
||||
"snippet": {
|
||||
"title": f"Musik {date.today().strftime('%x')}",
|
||||
},
|
||||
"status": {
|
||||
"privacyStatus": "private",
|
||||
},
|
||||
},
|
||||
)
|
||||
pl_response = pl_request.execute()
|
||||
logger.info(
|
||||
"Playlist créée : "
|
||||
f"https://www.youtube.com/playlist?list={pl_response['id']}",
|
||||
)
|
||||
|
||||
# Insertion des musiques dans la playlist
|
||||
logger.info("Insertion des musiques dans la playlist")
|
||||
for _, musik in musik_list:
|
||||
logger.debug(musik)
|
||||
request = youtube.playlistItems().insert(
|
||||
part="snippet",
|
||||
body={
|
||||
"snippet": {
|
||||
"playlistId": pl_response.get("id"),
|
||||
"position": 0,
|
||||
"resourceId": {
|
||||
"kind": "youtube#video",
|
||||
"videoId": musik,
|
||||
},
|
||||
}
|
||||
},
|
||||
)
|
||||
request.execute()
|
Loading…
Add table
Add a link
Reference in a new issue