This commit is contained in:
root 2022-06-24 20:12:16 +02:00
commit 3b0a63aae8
21 changed files with 77 additions and 73 deletions

View File

@ -177,7 +177,7 @@ USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_URL = 'static/'
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

View File

@ -24,6 +24,6 @@ class ExosFilter(django_filters.FilterSet):
withAllTags = list(filter(lambda t: all(
i in [t.id_code for t in t.tags.all()] for i in tags ), withT))
withAllTagsQ = parent.filter(id_code__in = [e.id_code for e in withAllTags])
print('WIRHA', withAllTagsQ)
return withAllTagsQ.filter(name__icontains=search)

View File

@ -40,16 +40,16 @@ def pdf_settings(path, number_in_serie, consigne):
def page_settings(exos):
# print(exos)
#
max = 100
total = 10 + 3 + 8
pages = [{'exos': [], 'index': 1, 'jump': 0}]
page_num = 0
for ex in list(map(lambda e: e['exos'], exos)):
#print(ex)
#
for e in ex:
if (total) + (len(e['exercice'][0])) <= max:
#print(total + len(e['exercice'][0]) + 2,
#
#total + len(e['exercice'][0]) + 2 < max, e['index'])
total += (len(e['exercice'][0]) * 2 * 2) + 4 + 3
e['notLast'] = True
@ -59,14 +59,14 @@ def page_settings(exos):
pages[page_num]['exos']) - 1]['notLast'] = False
rest = max - (total - 1)
pages[page_num]['jump'] = rest
#print('tot', pages[page_num]['jump'])
#
id = pages[page_num]['index']
page_num += 1
pages.append({'exos': [], 'index': id + 1, 'jump': 0})
pages[page_num]['exos'].append(e)
total = (len(e['exercice'][0]) * 2 * 2) + 4 + 10 + 3 + 3 + 8
#print('pgages', len(pages))
#
pages[len(pages) - 1]['exos'][len(pages[len(pages) - 1]
['exos']) - 1]['notLast'] = False
#print(list(map(lambda e:e['exos'],exos)))
#
return pages

View File

@ -17,7 +17,7 @@ def auto_delete_file_on_delete(sender, instance, **kwargs):
Deletes file from filesystem
when corresponding `MediaFile` object is deleted.
"""
print(instance, instance.exo_model.path, instance.id_code)
if instance.exo_model:
if os.path.isfile(instance.exo_model.path):
os.remove(instance.exo_model.path)

View File

@ -70,7 +70,11 @@ class ExerciceAPI(APIView):
userExosListSorted = userExos
if code != 'all' and code != 'pdf' and code != "web":
exo = Exercice.objects.get(id_code=code)
try:
exo = Exercice.objects.get(id_code=code)
except:
return Response({'error': "Not found"}, status= status.HTTP_404_NOT_FOUND)
isUser = False
if request.user == exo.author:
isUser = True
@ -111,7 +115,7 @@ class ExerciceAPI(APIView):
# sleep(2)
return Response({"status": "200", "errors": {}, "data": {**ExerciceSerializer(new_exo).data, "author": UserSerializer(new_exo.author).data if new_exo.author != None else None, 'exo_model': {'filename': new_exo.exo_model.name.split('/')[-1], "data": open(new_exo.exo_model.name, 'r').read()}, "tags": [{**TagSerializer(t).data, 'value': t.id_code, 'label': t.name} for t in new_exo.tags.all()]}}, status=status.HTTP_200_OK)
print(create_serializer.errors, 'errs')
return Response({"status": "400", "errors": create_serializer.errors}, status=status.HTTP_400_BAD_REQUEST)
@method_decorator(login_required)
@ -241,7 +245,7 @@ def getExoModelFile(request):
return Response({'errors': 'Not found'}, status=status.HTTP_404_NOT_FOUND)
exo = exo[0]
model = exo.exo_model
print(model.name)
with open(model.name, 'r') as f:
response = HttpResponse(f.read(), content_type='text/x-python')
@ -259,7 +263,7 @@ def fav(request):
originExo = exo[0]
exo = exo[0]
with open(exo.exo_model.path, 'r') as f:
print(f.name.split('/')[-1])
exo.pk = None
exo.id = None
exo.id_code = generate_unique_code_step()
@ -291,7 +295,7 @@ class TagsAPI(APIView):
tagsList = []
for o in options:
# print(o)
#
if o['value'].startswith('new_opt'):
newTag = Tag(name=o['label'],
color=o['color'], user=request.user)
@ -347,7 +351,7 @@ class Editor(APIView):
script.write(code)
proc = subprocess.Popen(['python3.10', 'tmp.py', ],
stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=tempdir)
print(open(os.path.join(tempdir, "tmp.py"), 'r').read())
out, err = proc.communicate()
out = out.decode().splitlines()
return Response({"out": out, "error": err.decode('utf-8').splitlines()}, status=status.HTTP_200_OK)
@ -382,7 +386,7 @@ def pdfGen(request):
for e in range(len(exos)):
for exo in range(len(exos[e]['exos'])):
# print(exos[e]['exos'][exo])
#
exos[e]['exos'][exo]['calcul'] = sympy.latex(
exos[e]['exos'][exo]['calcul'])
@ -447,11 +451,11 @@ def pdfGen(request):
fich_name = request.data.get('file')
if fich_name.count('.') >= 1:
ext = fich_name.split('.')[-1]
# print(ext)
#
if ext == 'pdf':
fich_name = fich_name
elif ext != 'pdf':
# print('nipe')
#
fich_name = fich_name.replace(f'.{ext}', '.pdf')
else:
fich_name = fich_name + '.pdf'
@ -463,7 +467,7 @@ class PDF(APIView):
exos = list(map(lambda ex: pdf_settings(
Exercice.objects.filter(id_code=ex['id_code'])[0].exo_model.name, 14, int(ex['numberInExo']), int(ex['numberOfExo']), 1, ex['consigne']), request.data.get('exos')))
# print(exos)
#
# dans str mettre space(0.5) replace by \hspace{0.5cm}
template_name = 'test.tex'
symbols = {
@ -475,7 +479,7 @@ class PDF(APIView):
# a refaire pour supp les symbols
for e in range(len(exos)):
for exo in range(len(exos[e]['exos'])):
# print(exos[e]['exos'][exo])
#
exos[e]['exos'][exo]['calcul'] = sympy.latex(
exos[e]['exos'][exo]['calcul'])
@ -509,7 +513,7 @@ class PDF(APIView):
template = get_template('test.tex')
latex = template.render(context) # latex to compile
# print(latex)
#
with tempfile.TemporaryDirectory() as tempdir:
direct = tempdir
with open(os.path.join(direct, 'tmp.tex'), 'x', encoding='utf-8') as f:
@ -541,11 +545,11 @@ class PDF(APIView):
fich_name = request.data.get('file')
if fich_name.count('.') >= 1:
ext = fich_name.split('.')[-1]
# print(ext)
#
if ext == 'pdf':
fich_name = fich_name
elif ext != 'pdf':
# print('nipe')
#
fich_name = fich_name.replace(f'.{ext}', '.pdf')
else:
fich_name = fich_name + '.pdf'
@ -560,7 +564,7 @@ class Test(APIView):
code = "VZRKLZ"
ex = Exercice.objects.filter(id_code=code)[0]
model = ex.exo_model
print('model', model.name)
oplist = Generateur(model.name, 2, 'calcul')
return Response({"data": oplist}, status=status.HTTP_200_OK)
@ -569,6 +573,6 @@ class ExoModelApi(APIView):
def get(self, request, format=None):
code = request.GET.get('id_code')
exo = Exercice.objects.filter(id_code=code)[0]
print(exo.exo_model.name)
model = open(exo.exo_model.name, 'rb')
return FileResponse(model, status=status.HTTP_200_OK)

View File

@ -19,21 +19,21 @@ class RoomConsumer(AsyncWebsocketConsumer):
self.user = None
try:
self.room = await self.get_room()
print('Connected')
await self.accept()
await self.send(json.dumps({'type': 'connect', "clientId": self.clientId}))
except:
print('closed')
await self.close()
async def receive(self, text_data):
text_data_json = json.loads(text_data)
type = text_data_json['data']['type']
print("EVENT", type)
print('USER', self.scope['user'])
if type == "login":
print('LOF', self.scope['user'])
participants = await self.get_participants()
if self.scope['user'].is_anonymous:
nick = text_data_json['data']['nick']
@ -84,7 +84,7 @@ class RoomConsumer(AsyncWebsocketConsumer):
new_participant = await self.add_participant(nick, str(uuid4()))
else:
new_participant = await self.add_user(code)
print(new_participant)
await self.del_waiter_db(code)
await self.channel_layer.group_send(f'waiter__{code}', {"type": "accept_room", 'id_code': self.room_id, 'code': new_participant['code']})
@ -118,7 +118,7 @@ class RoomConsumer(AsyncWebsocketConsumer):
participant = list(
filter(lambda p: p['code'] == code, participants))[0]
await self.channel_layer.group_discard(f'waiter__{code}', self.channel_name)
print('new user', participant)
self.clientId = participant['clientId']
await self.channel_layer.group_add(self.room_id, self.channel_name)
self.user = participant
@ -179,7 +179,7 @@ class RoomConsumer(AsyncWebsocketConsumer):
elif type == "reconnect":
client = text_data_json['data']['clientId']
print("reconeect", self.scope['user'].is_anonymous)
if not self.scope['user'].is_anonymous:
userInRoom = await self.userInRoom()
if not userInRoom:
@ -199,7 +199,7 @@ class RoomConsumer(AsyncWebsocketConsumer):
await self.connect_participant()
self.clientId = self.scope['user'].clientId
print('SENDING')
await self.send(json.dumps({'type': "reconnected", "clientId": self.scope['user'].clientId, 'id_code': self.room_id, 'identity': self.user}))
await self.channel_layer.group_send(self.room_id, {"type": "reconnect.event", 'nick': self.user['nick']})
await self.channel_layer.group_send(f'owner__{self.room_id}', {"type": "reconnect.event", 'nick': self.user['nick']})
@ -214,10 +214,10 @@ class RoomConsumer(AsyncWebsocketConsumer):
filter(lambda p: p['clientId'] == client, participants))[0]
if participant['clientId'] == self.room.owner['clientId'] and participant['code'] == self.room.owner['code']:
print('add in admin')
await self.channel_layer.group_add(f'owner__{self.room_id}', self.channel_name)
else:
print('add in users')
await self.channel_layer.group_add(self.room_id, self.channel_name)
participant['online'] = True
self.user = participant
@ -245,11 +245,11 @@ class RoomConsumer(AsyncWebsocketConsumer):
clientId = text_data_json['data']["clientId"]
status = 'anonymous' if len(code) == 6 else 'user'
print('EST')
if status == 'anonymous':
participants = await self.get_participants()
participant = [p for p in participants if p['code'] == code]
print('PARTICIPANR', participant)
if len(participant) == 0:
pass
else:
@ -259,7 +259,7 @@ class RoomConsumer(AsyncWebsocketConsumer):
await self.channel_layer.group_send(f'owner__{self.room_id}', {'type': "ban_participant", "code": code, "nick": nick})
else:
user = await self.get_user(code)
print('USER', user, code)
if self.scope['user'] == user:
await self.del_user(code)
await self.channel_layer.group_send(self.room_id, {'type': "ban_participant", "code": code, "nick": nick})
@ -346,7 +346,7 @@ class RoomConsumer(AsyncWebsocketConsumer):
id_code=self.room.id_code)) != 0
async def disconnect(self, close_code):
print('Disconnect')
if self.waiter == False and self.user != None:
await self.disconnect_participant()
await self.channel_layer.group_discard(self.room_id, self.channel_name)

View File

@ -115,12 +115,10 @@ class RoomManager(models.Manager):
return None
waiters = room.waiters
print('NEWNAME', new_name, new_name in list(
map(lambda p: p['nick'], waiters)), list(map(lambda p: p['nick'], waiters)), waiters)
if new_name in list(map(lambda p: p['nick'], waiters)):
return None
print('PASSED')
if code == None:
while True:
code = ''.join(random.choices(string.ascii_uppercase, k=6))
@ -232,7 +230,7 @@ class ParcoursManager(models.Manager):
challengers = parcours.challenger
challengers = [c for c in challengers if c['code'] == user_code]
if len(challengers) == 0:
print('NOPE', user_code)
return None
c = challengers[0]
return {'value': round(functools.reduce(lambda a, b: a+b, [e['note']['value'] for e in c['exos']])/len(c['exos']), 2), 'total': c['exos'][0]['note']['total']}

View File

@ -105,7 +105,7 @@ class ParcoursCreateSerializer(serializers.ModelSerializer):
'timer', 'exercices', 'success_condition') # + challenger ?
def validate_exercices(self, value):
print('EXOS', value)
if len(value) == 0:
raise serializers.ValidationError('Aucun exercice séléctioné')
return value

View File

@ -104,7 +104,7 @@ class RoomAPI(APIView):
else:
return Response({'error': 'Unauthorized'}, status=status.HTTP_401_UNAUTHORIZED)
else:
print('CLIENTID', clientId, room.owner)
if clientId == room.owner['clientId']:
room.delete()
else:
@ -122,7 +122,7 @@ class RoomAPI(APIView):
room = Room.objects.filter(id_code=code)[0]
except IndexError:
return Response({'error': 'No room'}, status=status.HTTP_502_BAD_GATEWAY)
# print(room)
if 'roomsJoined' not in request.session:
request.session['roomsJoined'] = []
elif 'roomsJoined' in request.session:
@ -224,7 +224,7 @@ def getEditParcours(request):
@api_view(['POST'])
def lockRoom(request):
print('DATA', request.data)
room_id = request.data['id_code']
if request.user.is_authenticated:
@ -245,7 +245,7 @@ def lockRoom(request):
@api_view(['POST'])
def publicResultToggler(request):
print('DATA', request.data)
room_id = request.data['id_code']
if request.user.is_authenticated:
@ -267,7 +267,7 @@ def publicResultToggler(request):
@api_view(['POST'])
def changeRoomName(request):
print('DATA', request.data)
room_id = request.data['id_code']
if request.user.is_authenticated:
@ -396,10 +396,10 @@ class ChallengeAPI(APIView):
filter(lambda c: c['order'] == a['order'], correctionExos['exos']))[0]
correctInputs = exoCorrect['inputs']
print('correcti', correctInputs)
studentsInput = sorted(
a['inputs'], key=lambda i: i.get('order'))
print('correctiinnnn\n\n', studentsInput)
corrigedInputs = [{**inp, "value": studentsInput[inp['order']]['value'], "isCorrect": (str(studentsInput[inp['order']]['value']) == str(
inp['correction'])) if inp['correction'] != "" else None} for inp in correctInputs]
corrigedList.append({**a, 'inputs': corrigedInputs})
@ -486,7 +486,7 @@ class ParcoursAPI(APIView):
id_code = request.data.get('id_code')
code = request.data.get('code')
print(f'id_code={id_code};code={code}')
parcours = Parcours.objects.filter(id_code=id_code)
if len(parcours) == 0:
@ -527,7 +527,7 @@ class ParcoursAPI(APIView):
if not serial.is_valid():
return Response(serial.errors, status=status.HTTP_400_BAD_REQUEST)
parcours = serial.create(serial.validated_data)
print('PARCOURS', parcours)
layer = get_channel_layer()
async_to_sync(layer.group_send)(room_code, {
'type': 'new_parcours', 'parcours': ParcoursFullSerializer(parcours).data})

View File

@ -24,7 +24,7 @@ function CardComp({ step, setActive, deleted, tags, queryKey }) {
{
onSuccess: (data, variables, context) => {
queryClient.setQueryData(queryKey, (old) => {
console.log("test old", old);
return {
...old,
results: [
@ -47,7 +47,7 @@ function CardComp({ step, setActive, deleted, tags, queryKey }) {
setTagMode(false);
},
onError: (data) => {
console.log("ERROR", data);
notificationService.error(
"Erreur",
`Les tags de ${step.name} n'ont pu être modifiés !`
@ -68,7 +68,7 @@ function CardComp({ step, setActive, deleted, tags, queryKey }) {
queryClient.invalidateQueries(queryKey);
}
queryClient.setQueriesData(queryKey, (old) => {
console.log("test old", old);
return {
...old,
results: [
@ -92,7 +92,7 @@ function CardComp({ step, setActive, deleted, tags, queryKey }) {
setTagMode(false);
},
onError: (e) => {
console.log(e);
notificationService.error(
"Erreur",
`Le tag n'a pu être retiré de ${step.name} !`

View File

@ -143,7 +143,7 @@ export default function ExoCreateForm({ cancel, resetFilter }) {
type="checkbox"
checked={newExo.private}
onChange={(e) => {
console.log(e.target);
setNewExo({ ...newExo, private: !newExo.private });
}}
/>

View File

@ -133,7 +133,7 @@ export function ExoEditForm({ step, cancel, setFull, full }) {
type="checkbox"
checked={spec.private}
onChange={(e) => {
console.log(e.target);
setSpec({ ...spec, private: !spec.private });
}}
/>

View File

@ -29,14 +29,16 @@ export default function ModalCard({ step, onClose, onDelete, tags, queryKey }) {
const alert = useAlert();
const [edit, setEdit] = useState(false);
const queryClient = useQueryClient();
const {
isLoading: isUpdating,
isFetching,
data: step_data,
} = useQuery(
["exo-data", step.id_code],
async () => await getExos(step.id_code),
async () => await getExos(step.id_code).catch(() => {
notificationService.error('Erreur', "Exercice introuvable")
}),
{ initialData: step, refetchOnWindowFocus: !edit }
);
const [selected, setSelected] = useState([]);
@ -120,7 +122,7 @@ export default function ModalCard({ step, onClose, onDelete, tags, queryKey }) {
return { ...old, tags: data.data.tags };
});
queryClient.setQueryData(queryKey, (old) => {
console.log("test old", old);
return {
...old,
results: [

View File

@ -97,7 +97,7 @@ export function Pagination({ setPage, page, pages }) {
: page + 3
)
.map((p) => {
console.log("new pagin", p);
return (
<p
onClick={() => {

View File

@ -21,7 +21,7 @@ export default function StepOptions({ pageChange, serieChange }) {
e.target.value == ''
);
if (!isNaN(parseInt(e.target.value, 10))) {
console.log("nope");
if (parseInt(e.target.value, 10) > 100) {
setPage(100);
pageChange && pageChange(100);

View File

@ -72,7 +72,7 @@ export default function ModelInput({
var filename = e.target.files[0].name;
var splitting = filename.split(".");
if (splitting[splitting.length - 1] != "py") {
console.log("nope");
} else {
setModel({ filename: e.target.files[0].name, data: text });
}

View File

@ -9,7 +9,7 @@ export default function TagContainer({ tags }) {
const [invisible, setInvisible] = useState([]);
useLayoutEffect(() => {
if (ref.current.clientWidth < ref.current.scrollWidth) {
console.log("overflow", ref);
var element = ref.current;
var invi = [];
for (var i = 0; i < element.childElementCount; i++) {
@ -24,7 +24,7 @@ export default function TagContainer({ tags }) {
element.children[i].style.display = "none";
}
}
console.log(invi);
setInvisible([...invi]);
}
}, [ref]);

View File

@ -229,7 +229,7 @@ export default function ParcoursView({ parcours_id, room_code, user }) {
}, [parcours]);
const router = useRouter();
console.log("PARCOURS", parcours);
const [dataCorrection, setDataCorrection] = useState();
const [onglet, setOnglet] = useState("tab");

View File

@ -24,11 +24,11 @@ export const WebsocketProvider = ({ children }) => {
});
};
ws.current.onclose = (c) => {
console.log("CLOSED", c);
setConnected(false);
};
ws.current.onerror = (e) => {
console.log("ERROR", e);
//router.push({ pathname: '/room/join' })
ws.current.close();

View File

@ -29,7 +29,7 @@ export default function Login() {
router.push({ pathname: "/dashboard" });
})
.catch((err) => {
console.log(err.response.data);
setError({ ...err.response.data });
});
}}

View File

@ -39,7 +39,7 @@ export default function Register() {
router.push({ pathname: "/dashboard" });
})
.catch((err) => {
console.log(err.response.data);
setError({ ...err.response.data });
});
}}