Merge branch 'development' of https://github.com/rushilwiz/SkoolOs into development

This commit is contained in:
Rushil Umaretiya 2020-06-16 00:18:11 -04:00
commit 37451e7071
12 changed files with 235 additions and 157 deletions

View File

@ -1 +0,0 @@
{"username": "2022rkhondak", "grade": 10, "is_student": true, "password": "hackgroup1"}

View File

@ -9,7 +9,18 @@ import time
import pyperclip
from distutils.dir_util import copy_tree
from datetime import datetime
# from django.conf import settings
# import django
# from Website.config.settings import DATABASES, INSTALLED_APPS
# INSTALLED_APPS.remove('users.apps.UsersConfig')
# INSTALLED_APPS.remove('api')
# INSTALLED_APPS.remove('skoolos.apps.SkoolosConfig')
# INSTALLED_APPS.append('Website.api')
# settings.configure(DATABASES=DATABASES, INSTALLED_APPS=INSTALLED_APPS)
# django.setup()
# from ..Website.api.models import *
#git clone student directory ==> <student-id>/classes/assignments
#get teacher info from api
@ -33,6 +44,10 @@ def getDB(url):
r = requests.get(url = url, auth=('raffukhondaker','hackgroup1'))
print("GET:" + str(r.status_code))
return(r.json())
def patchDB(data, url):
r = requests.patch(url = url, data=data, auth=('raffukhondaker','hackgroup1'))
print("PATCH:" + str(r.status_code))
return(r.json())
def postDB(data, url):
r = requests.post(url = url, data=data, auth=('raffukhondaker','hackgroup1'))
@ -69,25 +84,11 @@ class Teacher:
self.git=data['git']
self.username=data['ion_user']
self.url= "http://127.0.0.1:8000/api/teachers/" + self.username + "/"
self.email = data['email']
self.id = data['user']
#classes in id form (Example: 4,5)
cid=data['classes'].split(",")
try:
cid.remove('')
except:
pass
try:
cid.remove("")
except:
pass
classes=[]
for c in cid:
url = "http://127.0.0.1:8000/api/classes/" + str(c) + "/"
classes.append(getDB(url))
self.classes = classes
self.sclass=str(data['classes'])
#array
self.classes=data['classes']
if(os.path.isdir(self.username + "/Students")):
print("Synced to " + self.username)
else:
@ -149,41 +150,31 @@ class Teacher:
#make class from existing directory, add to git and api
def addClass(self, path):
if (self.checkClass(path)):
cname = path.split("/")
cname = cname[len(cname)-1]
for c in self.classes:
if c == cname:
print(cname + " already exists.")
return
if (self.checkClass(path)):
cpath = self.username + "/" + cname
data = {
"name": cname,
"repo": "",
"path": cpath,
"teacher": self.username,
"assignments": "",
"default_file": "",
"confirmed": "",
"unconfirmed": ""
"owner":self.id
}
#make class instance in db
data = postDB(data, 'http://127.0.0.1:8000/api/classes/')
postDB(data, 'http://127.0.0.1:8000/api/classes/')
self.classes.append(cname)
#add to instance
#upate self.classes
self.classes.append(data)
if(len(self.sclass)==0):
self.sclass = data['name']
else:
self.sclass = self.sclass + "," + str(data['name'])
#update teacher instance in db, classes field
teacher={
'git':self.git,
'ion_user':self.username,
'url':self.url,
'classes':self.sclass,
data = {
'classes':self.classes
}
putDB(teacher, self.url)
return teacher
print(self.username)
print(patchDB(data, 'http://127.0.0.1:8000/api/teachers/' + self.username + "/"))
#make a new class from scratch
#subject: string, assignments: list
@ -219,8 +210,7 @@ class Teacher:
# f.close()
# os.chdir(cdir)
data = self.addClass(path)
return data
self.addClass(path)
def deleteClass(self, path):
if(os.path.exists(path) == False):
@ -235,22 +225,12 @@ class Teacher:
print("DELETE: " + self.classes[i]['name'])
for i in range(len(self.classes)):
c = self.classes[i]
if(c['name'] == cname):
if(c == cname):
del self.classes[i]
s=""
#recreate sclass field, using ids
for c in self.classes:
s = s + str(c['name']) + ","
print(s)
s = s[:-1]
print(s)
data={
'git':self.git,
'ion_user':self.username,
'url':self.url,
'classes':s,
}
print(putDB(data, self.url))
# data={
# 'classes':self.classes,
# }
# print(patchDB(data, self.url))
delDB("http://127.0.0.1:8000/api/classes/" + cname + "/")
break
@ -274,49 +254,37 @@ class Teacher:
print(sname + " does not exist.")
return False
course = getDB("http://127.0.0.1:8000/api/classes/" + cname)
if(sname in course['unconfirmed']):
print (sname + " already requested.")
return True
if(sname in course['confirmed']):
print (sname + " alredy enrolled.")
return False
# if(sname in str(course['unconfirmed'])):
# print (sname + " already requested.")
# return True
# if(sname in str(course['confirmed'])):
# print (sname + " alredy enrolled.")
# return False
student = getDB("http://127.0.0.1:8000/api/students/" + sname)
try:
if(student['added_to']==""):
student['added_to']=course['name']
else:
student['added_to']=student['added_to']+ "," + course['name']
except:
print(sname + " does not exist.")
return False
print(student['added_to'])
s={
'git':student["git"],
'ion_user':student["ion_user"],
'added_to':student['added_to'],
'classes':student["classes"],
'grade':student["grade"],
'completed':student["completed"],
'repo':student["repo"]
}
student = putDB(s, student['url'])
if(course['unconfirmed']==""):
# student = getDB("http://127.0.0.1:8000/api/students/" + sname)
# try:
# if(student['added_to']==""):
# student['added_to']=course['name']
# else:
# student['added_to']=student['added_to']+ "," + course['name']
# except:
# print(sname + " does not exist.")
# return False
# print(student['added_to'])
# data={
# 'added_to':student['added_to'],
# }
# student = patchDB(data, "http://localhost:8000/api/students/" + student['ion_user'] + "/")
student = getDB( "http://localhost:8000/api/students/" + (sname)+ "/")
if(course['unconfirmed']==[]):
course['unconfirmed']=student['ion_user']
else:
course['unconfirmed']=course['unconfirmed']+ "," + student['ion_user']
course['unconfirmed']=course['unconfirmed'].append(student['ion_user'])
cinfo = {
"name": course['name'],
"repo": "",
"path": self.username + "/" + course['name'],
"teacher": self.username,
"assignments": course['assignments'],
"default_file": "",
"confirmed": course["confirmed"],
"unconfirmed": course['unconfirmed']
}
print(putDB(cinfo, course['url']))
print(cinfo)
patchDB(cinfo, "http://localhost:8000/api/classes/" + course['name'] + "/")
return True
#Student should have confirmed on their endd, but class had not been updated yet
@ -378,16 +346,10 @@ class Teacher:
course['unconfirmed']= course['unconfirmed'].replace(student['ion_user']+",", "")
cinfo = {
"name": course['name'],
"repo": "",
"path": course['path'],
"teacher": self.username,
"assignments": course['assignments'],
"default_file": "",
"confirmed": course["confirmed"],
"unconfirmed": course['unconfirmed']
}
print(putDB(cinfo, course['url']))
print(patchDB(cinfo, "http://localhost:8000/api/classes/" + course['name'] + "/"))
return True
#goes through list of studennts, tries to add, then request, return unconfirmed students
@ -405,10 +367,10 @@ class Teacher:
parts = path.split("/")
aname = parts[len(parts)-1]
if(os.path.isdir(path) == 0 or len(parts) < 3) or aname in self.sclass:
if(os.path.isdir(path) == 0 or len(parts) < 3) or aname in str(self.classes):
print("Not valid path.")
return False
if((parts[1] in self.sclass) == False):
if((parts[1] in str(self.classes)) == False):
print("Not in valid class directory")
return False
#parts of assignment name (Essay1, APLit)
@ -433,7 +395,7 @@ class Teacher:
return False
course = getDB("http://127.0.0.1:8000/api/classes/" + course)
if(aname in course['assignments']):
if(aname in str(course['assignments'])):
print("Assignment name already taken.")
return False
@ -447,7 +409,7 @@ class Teacher:
slist = os.listdir(os.getcwd() + "/" + self.username + "/Students/" + course['name'])
cdir = os.getcwd()
for st in slist:
if st in course['confirmed']:
if st in str(course['confirmed']):
spath = os.path.join(os.getcwd() + "/" + self.username + "/Students/" + course['name'], st)
if(os.path.exists(spath + "/" + aname) == False):
os.mkdir(spath + "/" + aname)
@ -475,21 +437,14 @@ class Teacher:
}
postDB(ass, 'http://127.0.0.1:8000/api/assignments/')
if(course['assignments'] == ""):
course['assignments'] = aname
course['assignments'] = ass
else:
course['assignments'] = course['assignments'] + "," + aname
course['assignments'] = course['assignments'].append(ass)
cinfo = {
"name": course['name'],
"repo": "",
"path": course['path'],
"teacher": "eharris1",
"assignments": course['assignments'],
"default_file": "",
"confirmed": course["confirmed"],
"unconfirmed": course['unconfirmed']
}
putDB(cinfo, "http://127.0.0.1:8000/api/classes/" + course['name'] + "/")
patchDB(cinfo, "http://127.0.0.1:8000/api/classes/" + course['name'] + "/")
return True
else:
print("Assignment already addedd")
@ -498,18 +453,22 @@ class Teacher:
#try to avoid
#copy modified assignments to student directories
def updateAssignment(self, path, course, due):
parts = path.split("/")
aname = parts[len(parts)-1]
if(os.path.isdir(path) == False):
print(path + " is not an assignment.")
return
try:
if(due != None or due == ""):
datetime.strptime(due, '%Y-%m-%d %H:%M:%S.%f')
d = {
'due_date':due,
}
patchDB(d, 'http://localhost:8000/api/assignments/' + aname + "/")
print("Due-date changed " + due)
except:
print("Due-date format is incorrect")
return
print("Due-date is the same")
input()
parts = path.split("/")
aname = parts[len(parts)-1]
course = getDB("http://127.0.0.1:8000/api/classes/" + course)
slist = os.listdir(os.getcwd() + "/" + self.username + "/Students/" + course['name'])
cdir = os.getcwd()
@ -642,12 +601,12 @@ class Teacher:
data = getTeacher("eharris1")
t = Teacher(data)
# t.makeClass("APLit_eharris1")
#t.addAssignment("eharris1/APLit_eharris1/Lab3_APLit_eharris1", "APLit_eharris1", '2020-08-11 16:58:33.383124')
#t.addClass("eharris1/APLit_eharris1")
#t.addAssignment("eharris1/APLit_eharris1/Essay1_eharris1", "APLit_eharris1", '2020-08-11 16:58:33.383124')
#ar = ['2022rkhondak','2022inafi','2023rumareti']
#extra = t.reqAddStudentList(ar, "APLit_eharris1")
#print(extra)
# t.getStudents('2022rkhondak')
t.reqStudent('2022rkhondak', 'APLit_eharris1')
# t.getChanges('2022rkhondak','APLit_eharris1', 10)
'''

View File

@ -6,7 +6,7 @@ import secrets
class Student(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
ion_user = models.CharField(max_length=100)
ion_user = models.CharField(max_length=100, primary_key=True)
grade = models.IntegerField(default=0, blank=True)
git=models.CharField(default="", max_length=100, blank=True)
repo=models.URLField(default="", blank=True)
@ -20,12 +20,28 @@ class Student(models.Model):
def __str__(self):
return f"{self.user.username}'s Profile"
class Assignment(models.Model):
owner = models.ForeignKey('auth.User', related_name='assignments', on_delete=models.CASCADE)
name=models.CharField(max_length=100, primary_key=True)
due_date=models.DateTimeField()
# files = models.ManyToManyField(DefFiles)
files=models.CharField(max_length=100, default="", blank=True)
path=models.CharField(max_length=100)
classes=models.CharField(max_length=100)
teacher=models.CharField(max_length=100)
def __str__(self):
return '%s' % (self.name)
class Class(models.Model):
owner = models.ForeignKey('auth.User', related_name='classes', on_delete=models.CASCADE)
teacher = models.CharField(max_length=100)
name = models.CharField(primary_key=True, max_length=100)
id = models.CharField(max_length=8, blank=True, null=True)
description = models.CharField(default="Class Description", max_length=500)
repo=models.URLField(default="", blank=True)
path=models.CharField(blank=True, max_length=100, default="")
path=models.CharField(max_length=100, default="")
assignments=models.ManyToManyField(Assignment, blank=True)
default_file=models.CharField(max_length=100, default="", blank=True)
confirmed=models.ManyToManyField(Student, blank=True, related_name='confirmed')
unconfirmed=models.ManyToManyField(Student, blank=True, related_name='unconfirmed')
@ -48,13 +64,12 @@ class Teacher(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
classes=models.ManyToManyField(Class, blank=True, related_name='classes')
git=models.CharField(max_length=100, default="", blank=True)
ion_user=models.CharField(primary_key=True, blank=True, max_length=100)
ion_user=models.CharField(primary_key=True, max_length=100)
def __str__(self):
return f"{self.user.username}'s Profile"
def save(self, *args, **kwargs):
self.ion_user = self.user.username
super(Teacher, self).save(*args, **kwargs)
# class Student(models.Model):
@ -68,19 +83,6 @@ class Teacher(models.Model):
# completed=models.TextField(default="", blank=True)
class Assignment(models.Model):
myClass = models.ForeignKey(Class, related_name='assignments', on_delete=models.CASCADE)
name=models.CharField(max_length=100, primary_key=True)
due_date=models.DateTimeField()
# files = models.ManyToManyField(DefFiles)
files=models.CharField(max_length=100, default="", blank=True)
path=models.CharField(max_length=100, blank=True)
def __str__(self):
return f'{self.name}'
class DefFiles(models.Model):
name=models.CharField(max_length=100)
path=models.CharField(max_length=100)

View File

@ -25,18 +25,18 @@ class AssignmentSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Assignment
# fields = ['url','name', 'due_date', 'path' , "Class","teacher",'owner']
fields = ['name', 'due_date', 'path' , "Class","teacher",'owner']
fields = ['name', 'due_date', 'path' ,"teacher",'owner']
class ClassSerializer(serializers.HyperlinkedModelSerializer):
class ClassSerializer(serializers.ModelSerializer):
# assignments = AssignmentSerializer(many=True, read_only=True,allow_null=True)
# default_file=DefFilesSerializer(many=True, read_only=True,allow_null=True)
#owner = serializers.ReadOnlyField(source='owner.username')
class Meta:
model = Class
# fields = ['url','name', 'repo','path', "teacher",'assignments',"default_file", 'confirmed', 'unconfirmed','owner']
fields = ['name', 'repo','path','assignments',"default_file", 'confirmed', 'unconfirmed']
fields = ['name', 'repo','path','assignments',"teacher","default_file", 'confirmed', 'unconfirmed','owner']
class StudentSerializer(serializers.HyperlinkedModelSerializer):
class StudentSerializer(serializers.ModelSerializer):
# Class = ClassSerializer(many=True, read_only=True,allow_null=True)
class Meta:
model = Student
@ -44,7 +44,7 @@ class StudentSerializer(serializers.HyperlinkedModelSerializer):
fields = ['url','grade', 'ion_user','git','user','classes','added_to','completed', 'repo']
class TeacherSerializer(serializers.ModelSerializer):
# Class = ClassSerializer(many=True, read_only=True,allow_null=True)
#classes = ClassSerializer(many=True, read_only=True,allow_null=True)
#owner = serializers.ReadOnlyField(source='owner.username')
class Meta:
model = Teacher

View File

@ -24,8 +24,6 @@ class StudentViewSet(viewsets.ModelViewSet):
queryset = Student.objects.all()
serializer_class = StudentSerializer
permission_Class = [permissions.IsAuthenticated, IsOwnerOrReadOnly]
g, created = Group.objects.get_or_create(name='teachers')
def perform_create(self, serializer):
serializer.save(user=self.request.user)

View File

@ -2,6 +2,7 @@ import time
import sys
import os
import pyinotify
import checker
class EventHandler(pyinotify.ProcessEvent):
@ -77,18 +78,24 @@ class EventHandler(pyinotify.ProcessEvent):
NOTIFIER = None
STDOUT = sys.stdout
DIR = None
START_TIME = None
def watch_dir(watched_dir="/tmp", logdir="/tmp/skooloslogs"):
global DIR
global START_TIME
global NOTIFIER
DIR = watched_dir
if not os.path.exists(logdir):
os.makedirs(logdir)
logfile = open(
logdir + "/skoolos_" +
time.strftime("%m%d%Y-%H%M%S", time.localtime()), 'w')
sys.stdout = logfile
START_TIME = time.time()
print("Start time: " +
time.strftime("%A, %B %d, %Y %H:%M:%S", time.localtime()) + "\n\n")
global NOTIFIER
wm = pyinotify.WatchManager()
mask = pyinotify.IN_CREATE | pyinotify.IN_CLOSE_WRITE | pyinotify.IN_DELETE | \
pyinotify.IN_MOVED_TO | pyinotify.IN_MOVED_FROM | pyinotify.IN_OPEN
@ -99,7 +106,17 @@ def watch_dir(watched_dir="/tmp", logdir="/tmp/skooloslogs"):
def stop_watching():
NOTIFIER.stop()
now = time.time()
print("End time: " +
time.strftime("%A, %B %d, %Y %H:%M:%S", time.localtime()))
print("\nTotal work time: " +
time.strftime("%H:%M:%S", time.gmtime(now - START_TIME)))
suspicious_files = checker.file_check(DIR)
if suspicious_files != []:
print(
"\n\n--------------------------------------------------\n\n\n" +
"WARNING: One or more file did not have file extensions that are acceptable.\n"
+ "The paths to these files are listed below:\n")
print(*suspicious_files, sep='\n')
sys.stdout = STDOUT
print("Done watching.\n")

100
bgservice/checker.py Normal file
View File

@ -0,0 +1,100 @@
import os
from glob import glob
file_whitelist = [
# text and document files
".doc",
".docx",
".odt",
".pdf",
".rtf",
".tex",
".txt",
".wpd",
# video files
".3g2",
".3gp",
".avi",
".flv",
".h264",
".m4v",
".mkv",
".mov",
".mp4",
".mpg",
".mpeg",
".rm",
".swf",
".vob",
".wmv",
# spreadsheet files
".ods",
".xls",
".xlsm",
".xlsx",
".csv",
# programming files
".c",
".class",
".cpp",
".cs",
".go",
".h",
".java",
".pl",
".sh",
".swift",
".vb",
# presentation files
".key",
".odp",
".pps",
".ppt",
".pptx",
# image files
".ai",
".bmp",
".gif",
".ico",
".jpeg",
".jpg",
".png",
".ps",
".psd",
".svg",
".tif",
".tiff",
]
def shell_check():
bash_history = [
line.strip()
for line in open(os.path.expanduser("~/.bash_history"), 'r')
]
zsh_history = [
line.strip() for line in open(os.path.expanduser("~/.histfile"), 'r')
]
report = "Suspicios commands found:\n"
for i in bash_history + zsh_history:
if "git" in i:
report += i + "\n"
if report != "Suspicios commands found:\n":
return report
return "Nothing suspicious found in bash or zsh history."
def verify_file(file_):
for ext in file_whitelist:
if file_[len(file_) - len(ext):] == ext:
return True
return False
def file_check(dir_):
files = glob(dir_ + "/**/*", recursive=True)
suspicious_files = []
for file_ in files:
if not verify_file(file_):
suspicious_files.append(file_)
return suspicious_files

View File

View File

@ -23,6 +23,7 @@ lazy-object-proxy==1.4.3
mccabe==0.6.1
meson==0.53.2
msgpack==0.6.2
numpy==1.18.5
oauthlib==3.1.0
ordered-set==3.1.1
packaging==20.1
@ -59,3 +60,4 @@ webencodings==0.5.1
Werkzeug==1.0.1
wpgtk==6.1.3
wrapt==1.12.1
yapf==0.30.0

View File

@ -40,7 +40,7 @@ def main():
URL = "http://127.0.0.1:8000/api/"
r = requests.get(url = URL)
except:
print("Stop any processes running on http://127.0.0.1:8000/ before continuing")
print("Run Django server on http://127.0.0.1:8000/ before continuing")
sys.exit(0)
input("Welcome to SkoolOS. Press any key to create an account")

17
snew.py
View File

@ -84,16 +84,17 @@ class Students:
# c = Class.objects.get(name='Math5')
data = requests.get(url = "http://localhost:8000/api/classes/Math5", auth=('raffukhondaker','hackgroup1')).json()
c = Class(
name="data['name']"
)
# print("POST:" + str(r.status_code))
r = requests.post(url = "http://localhost:8000/api/classes/", data={'name':'English11', 'teacher':'eharris1', 'owner':2}, auth=('raffukhondaker','hackgroup1'))
print("POST:" + str(r.json()))
# print(r.json())
c = {
'classes':"http://localhost:8000/api/classes/Math5/"
}
# print(c.name)
# c = {
# 'classes':c
# }
# print(c)
r = requests.patch(url = "http://localhost:8000/api/teachers/2/", data=c, auth=('raffukhondaker','hackgroup1'))
r = requests.patch(url = "http://localhost:8000/api/teachers/eharris1/", data={'classes':['English11']}, auth=('raffukhondaker','hackgroup1'))
print(r.json())