models.py 28.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
import datetime

from django.db import models
from django.db.models.signals import m2m_changed
from django.db.models import Count
from django.core.mail import EmailMessage
from django.urls import reverse
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from django.contrib.auth.models import Group
from django.contrib.staticfiles.storage import staticfiles_storage
from django.template import Template, Context
from django.contrib.contenttypes.fields import GenericRelation
from django.conf import settings
from autoslug import AutoSlugField

from .utils import hash_name

Bruno Martin's avatar
Bruno Martin committed
19 20
from discussion.models import Forum

21 22
from .videos.models import Video
from .notes.models import Note
23
from .course_material.models import CourseMaterial
24
from .classes.models import Class
Bruno Martin's avatar
Bruno Martin committed
25
from .classroom.models import Classroom, Event
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72

import re


class Course(models.Model):
    STATES = (
        ('draft', _('Draft')),
        ('published', _('Published')),
    )

    slug = models.SlugField(
        _('Slug'),
        max_length=255,
        unique=True,
    )
    name = models.CharField(
        _('Name'),
        max_length=255,
        blank=True,
    )
    intro_video = models.ForeignKey(
        Video,
        models.CASCADE,
        verbose_name=_('Intro video'),
        null=True,
        blank=True,
    )
    application = models.TextField(
        _('Application'),
        blank=True,
    )
    requirement = models.TextField(
        _('Requirement'),
        blank=True,
    )
    abstract = models.TextField(
        _('Abstract'),
        blank=True,
    )
    structure = models.TextField(
        _('Structure'),
        blank=True,
    )
    workload = models.TextField(
        _('Workload'),
        blank=True,
    )
73 74 75 76
    course_load = models.IntegerField(
        _('Course Load'),
        null=True,
    )
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
    pronatec = models.TextField(
        _('Pronatec'),
        blank=True,
    )
    status = models.CharField(
        _('Status'),
        choices=STATES,
        default=STATES[0][0],
        max_length=64,
    )
    thumbnail = models.ImageField(
        _('Thumbnail'),
        upload_to=hash_name('course_thumbnails', 'name'),
        null=True,
        blank=True,
    )
    professors = models.ManyToManyField(
        settings.AUTH_USER_MODEL,
        related_name='professorcourse_set',
        through='CourseProfessor',
    )
    authors = models.ManyToManyField(
        settings.AUTH_USER_MODEL,
        related_name='authorcourses',
        through='CourseAuthor',
    )
    students = models.ManyToManyField(
        settings.AUTH_USER_MODEL,
        related_name='studentcourse_set',
        through='CourseStudent',
    )
    home_thumbnail = models.ImageField(
        _('Home thumbnail'),
        upload_to=hash_name('home_thumbnails', 'name'),
        null=True,
        blank=True,
    )
    home_position = models.IntegerField(
        null=True,
        blank=True,
    )
    start_date = models.DateField(
        _('Start date'),
        default=None,
        blank=True,
        null=True,
    )
    home_published = models.BooleanField(
        default=False,
    )
    default_class = models.OneToOneField(
128
        'Class',
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
        models.SET_NULL,
        verbose_name=_('Default Class'),
        related_name='default_course',
        null=True,
        blank=True,
    )
    min_percent_to_complete = models.IntegerField(
        default=100,
        null=True,
        blank=True,
    )

    groups = models.ManyToManyField(
        Group,
        verbose_name=_('groups'),
        blank=True,
        help_text=_('The Groups that can have access to this forum. If empty, there are no group restrictions.'),
        related_name="courses",
    )

149 150 151 152 153
    is_public = models.BooleanField(
        _('Public'),
        default=False,
    )

Bruno Martin's avatar
Bruno Martin committed
154 155 156 157 158 159 160 161 162
    forum = models.OneToOneField(
        Forum,
        models.SET_NULL,
        verbose_name=_('Forum'),
        related_name='course',
        null=True,
        blank=True,
    )

163 164 165 166
    class Meta:
        verbose_name = _('Course')
        verbose_name_plural = _('Courses')

Bruno Martin's avatar
Bruno Martin committed
167
    def __str__(self):
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
        return self.name

    @property
    def unit_set(self):
        return Unit.objects.filter(lesson__in=self.lessons.all()).order_by('lesson')

    @property
    def public_lessons(self):
        return self.lessons.exclude(status='draft')

    def first_lesson(self):
        if self.lessons.exists():
            return self.lessons.all()[0]

    def enroll_student(self, student):
        if not Class.objects.filter(course=self, students=student).exists():
            self.default_class.students.add(student)

        if not CourseStudent.objects.filter(course=self, user=student).exists():
            CourseStudent.objects.create(course=self, user=student)

    def is_enrolled(self, user):
        return CourseStudent.objects.filter(course=self, user=user).exists()

    @property
    def thumbnail_url(self):
        return self.get_thumbnail_url()

    def get_thumbnail_url(self):
        if self.thumbnail:
            return self.thumbnail.url
        return ''

    def get_home_thumbnail_url(self):
        if self.home_thumbnail:
            return self.home_thumbnail.url
        return ''

    @property
    def has_started(self):
        if self.start_date and self.start_date <= datetime.date.today():
            return True
        else:
            return False

    def avg_lessons_users_progress(self, classes=None):
        if classes:
215
            student_enrolled = self.course_students.filter(
216
                user__classes__in=classes, user__is_active=True).count()
217
        else:
218
            student_enrolled = self.course_students.filter(user__is_active=True).count()
219 220 221 222 223 224 225 226 227 228
        progress_list = []
        for lesson in self.lessons.all():
            lesson_progress = {}
            lesson_progress['name'] = lesson.name
            lesson_progress['slug'] = lesson.slug
            lesson_progress['position'] = lesson.position
            units_len = lesson.unit_count()
            # avoid zero divisfion
            if units_len and student_enrolled:
                units_done = StudentProgress.objects.exclude(
229
                    complete=None, user__is_active=True).filter(unit__lesson=lesson)
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
                if classes:
                    units_done = units_done.filter(user__classes__in=classes)
                units_done_len = units_done.count()
                lesson_progress['progress'] = 100 * units_done_len / (
                    units_len * student_enrolled)
                # lesson_progress['forum_questions'] = lesson.forum_questions.count()
                # lesson_progress['progress'] =
                # lesson_progress['finish'] = self.get_lesson_finish_time(lesson)
            else:
                lesson_progress['progress'] = 0
                # lesson_progress['finish'] = ''
            progress_list.append(lesson_progress)
        return progress_list

    def forum_answers_by_lesson(self):
        return self.user.forum_answers.values('question__lesson').annotate(
            Count('question__lesson'))

    @property
    def authors_names(self):
        professors = self.course_authors.all()
        professors_names = ''
        if professors:
            last_elem_index = len(professors) - 1
            for index, professor in enumerate(professors):
                professors_names += professor.get_name()
                if last_elem_index != index:
                    professors_names += ', '
        return professors_names

    def get_professor_role(self, user):
        try:
            cp = self.course_professors.get(user=user)
            return cp.role
        except CourseProfessor.DoesNotExist:
            return False

    def get_role_professors(self, role):
        try:
            cp_set = self.course_professors.filter(role=role)
        except CourseProfessor.DoesNotExist:
            return False

        professors = []
        for cp in cp_set:
            professors.append(cp.user)

        return iter(professors)

    def is_course_assistant(self, user):
280
        if user.is_anonymous:
281 282 283 284 285 286
            return False

        return self.get_professor_role(user) == 'assistant'
        # return role =='assistant', 'coordinator'] or user.is_superuser

    def is_assistant_or_coordinator(self, user):
287
        if user.is_anonymous:
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
            return False

        if user.is_staff or user.is_superuser:
            return True

        role = self.get_professor_role(user)
        return role in ['assistant', 'coordinator'] or user.is_superuser

    def is_course_coordinator(self, user):
        course_coordinators = self.get_role_professors('coordinator')

        return user.is_superuser or user.is_staff or user in course_coordinators

    def has_perm_own_all_classes(self, user):
        role = self.get_professor_role(user)
        return role == 'coordinator' or user.is_superuser

    def save(self, *args, **kwargs):
        is_new = self.pk is None

        super(Course, self).save(*args, **kwargs)

        if is_new:
            c = Class.objects.create(name=self.name, course=self)
            self.default_class = c
            self.save()
            CourseMaterial.objects.create(course=self)


class CourseStudent(models.Model):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        models.CASCADE,
        verbose_name=_('Student'),
    )
    course = models.ForeignKey(
        Course,
        models.CASCADE,
        verbose_name=_('Course'),
327
        related_name='course_students',
328 329 330 331 332 333 334 335 336
    )
    start_date = models.DateTimeField(
        default=timezone.now,
    )

    class Meta:
        unique_together = (('user', 'course'),)
        ordering = ['course__start_date']

Bruno Martin's avatar
Bruno Martin committed
337
    def __str__(self):
338 339 340 341 342 343 344 345 346 347
        return u'{0} - {1}'.format(self.course, self.user)

    def save(self, *args, **kwargs):
        super(CourseStudent, self).save(*args, **kwargs)

    @property
    def units_done(self):
        return StudentProgress.objects.exclude(complete=None) \
            .filter(user=self.user, unit__lesson__course=self.course)

Bruno Martin's avatar
Bruno Martin committed
348 349
    def _activities_and_course_finished(self):
        """
350
        This method verifies if the user made all discussion activities
Bruno Martin's avatar
Bruno Martin committed
351 352
        AND has the perent progress
        """
353 354
        from courses_learning_objects.models import LearningObject, Answer
        activities = LearningObject.objects\
355 356 357 358 359 360
            .filter(unit__lesson__in=self.course.lessons
                    .filter(status='published'),
                    type='discussion')
        answers = Answer.objects\
            .filter(activity__in=activities, user=self.user)

Bruno Martin's avatar
Bruno Martin committed
361
        return self.percent_progress() >= self.min_percent_to_complete() and \
362 363 364 365 366 367 368 369
               activities.count() == answers.count()

    def _course_finished(self):
        return self.percent_progress() >= \
            self.course.min_percent_to_complete

    @property
    def course_finished(self):
Bruno Martin's avatar
Bruno Martin committed
370
        return self._course_finished()
371

372 373 374 375 376 377 378 379 380 381 382 383
    @property
    def finish_date(self):
        if not self.course_finished:
            return None

        progress = StudentProgress.objects\
            .exclude(complete=None)\
            .filter(user=self.user, unit__lesson__course=self.course)\
            .order_by('-complete')

        return progress.first().complete

384 385 386
    def can_emmit_receipt(self):
        if not self.get_current_class().user_can_certificate and not self.course_finished:
            return False
387
        if self.get_current_class().user_can_certificate_even_without_progress and self.certificate.document_type == 'certificate':
388 389 390 391
            return True
        return self.course_finished

    def get_current_class(self):
392 393
        try:
            return Class.objects.get(students=self.user, course=self.course)
394 395
        except Class.MultipleObjectsReturned:
            return Class.objects.filter(students=self.user, course=self.course).first()
396 397 398
        except Class.DoesNotExist:
            self.course.default_class.students.add(self.user)
            return self.course.default_class
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478

    def min_percent_to_complete(self):
        return self.course.min_percent_to_complete

    def reached_last_unit(self):
        try:
            last_unit_done = self.units_done.latest('complete')
            # try to get the next unit in same lesson
            next_unit = Unit.objects \
                .filter(lesson=last_unit_done.unit.lesson,
                        position__gt=last_unit_done.unit.position) \
                .order_by('position').first()

            if next_unit:
                return False
            else:
                next_lesson = self.course.lessons \
                    .filter(position__gt=last_unit_done.unit.lesson.position) \
                    .order_by('position').first()

                if next_lesson and next_lesson.first_unit():
                    return False
                else:
                    return True
        except StudentProgress.DoesNotExist:
            return False
        except AttributeError:
            pass
        return None

    def resume_next_unit(self):
        try:
            last_unit_done = self.units_done.latest('complete')
            # try to get the next unit in same lesson
            next_unit = Unit.objects.filter(lesson=last_unit_done.unit.lesson,
                                            position__gt=last_unit_done.unit.position).order_by(
                'position').first()

            if next_unit:
                return next_unit
            else:
                next_lesson = self.course.lessons.filter(
                    position__gt=last_unit_done.unit.lesson.position,
                    status='published').order_by(
                    'position').first()
                if next_lesson and next_lesson.first_unit():
                    return next_lesson.units.order_by('position').first()
                else:
                    return self.course.first_lesson().first_unit()
        except StudentProgress.DoesNotExist:
            first_lesson = self.course.first_lesson()
            if first_lesson:
                return first_lesson.first_unit()
        except AttributeError:
            pass
        return None

    def percent_progress(self):
        units_len = self.course.unit_set.count()
        if units_len <= 0:
            return 0
        units_done_len = self.units_done.count()
        return int(100.0 * units_done_len / units_len)

    def units_done_by_lesson(self, lesson):
        return StudentProgress.objects.exclude(complete=None)\
                                      .filter(user=self.user, unit__lesson=lesson)

    def get_lesson_finish_time(self, lesson):
        latest = StudentProgress.objects.exclude(complete=None).filter(user=self.user, unit__lesson=lesson).order_by('complete')
        if latest:
            return latest.latest('complete').complete
        else:
            return ''

    def percent_progress_by_lesson(self):
        """
        Returns a list with dictionaries with keys name (lesson name), slug (lesson slug) and progress (percent lesson progress, decimal)
        """
        # TODO refator to make one query to count unts done for all lessons
479
        from courses_learning_objects.models import LearningObject, Answer
480 481 482 483 484 485 486 487 488 489 490 491
        progress_list = []
        for lesson in self.course.lessons.filter(status='published'):
            lesson_progress = {}
            lesson_progress['name'] = lesson.name
            lesson_progress['slug'] = lesson.slug
            lesson_progress['position'] = lesson.position
            units_len = lesson.unit_count()
            lesson_progress['activities'] = []
            if units_len:
                units_done_len = self.units_done_by_lesson(lesson).count()
                lesson_progress['progress'] = 100 * units_done_len / units_len
                lesson_progress['finish'] = self.get_lesson_finish_time(lesson)
492
                activities = LearningObject.objects.filter(unit__lesson=lesson, type='discussion')
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
                i = 0
                for activity in activities:
                    i = i + 1
                    new_actv = {}
                    new_actv['name'] = 'Atividade ' + str(i)
                    new_actv['position'] = activity.unit.position
                    ans = Answer.objects.filter(activity=activity, user=self.user)
                    if ans:
                        new_actv['done'] = 'true'
                    else:
                        new_actv['done'] = 'false'
                    lesson_progress['activities'].append(new_actv)
            else:
                lesson_progress['progress'] = 0
                lesson_progress['finish'] = ''
            progress_list.append(lesson_progress)
        return progress_list

    def forum_questions_by_lesson(self):
        return self.user.forum_questions.values('lesson').annotate(Count('lesson'))

    def forum_answers_by_lesson(self):
        return self.user.forum_answers.values('question__lesson').annotate(Count('question__lesson'))


class CourseProfessor(models.Model):
    ROLES = (
        ('assistant', _('Assistant')),
        ('coordinator', _('Professor Coordinator')),
    )

    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        models.SET_NULL,
        verbose_name=_('Professor'),
        related_name='teaching_courses',
        blank=True,
        null=True
    )
    course = models.ForeignKey(
        Course,
        models.CASCADE,
        verbose_name=_('Course'),
        related_name='course_professors'
    )
    biography = models.TextField(
        _('Biography'),
        blank=True,
        null=True
    )
    role = models.CharField(_('Role'), choices=ROLES, default=ROLES[1][0], max_length=128)
    picture = models.ImageField(_('Picture'), upload_to=hash_name('bio-pictures', 'name'), blank=True, null=True)
    name = models.TextField(_('Name'), max_length=30, blank=True, null=True)
    is_course_author = models.BooleanField(default=False)

    class Meta:
        unique_together = (('user', 'course'),)
        verbose_name = _('Course Professor')
        verbose_name_plural = _('Course Professors')

Bruno Martin's avatar
Bruno Martin committed
553
    def __str__(self):
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
        return u'%s @ %s' % (self.user, self.course)

    def get_name(self):
        if self.name:
            return self.name
        elif self.user:
            return self.user.get_full_name()

    def get_biography(self):
        if self.biography:
            return self.biography
        elif self.user:
            return self.user.biography

    def get_picture_url(self):
        if self.picture:
            location = "/%s/%s" % (settings.MEDIA_URL, self.picture)
            return re.sub('/+', '/', location)
        elif self.user:
            return self.user.get_picture_thumb_url()

    def new_message(self, course, subject, message, to=[]):
        return ProfessorMessage.objects.create(subject=subject,
                                               message=message,
                                               course=course,
                                               users=to,
                                               professor=self)

    def get_current_user_classes(self):
        return Class.objects.filter(course=self.course, assistants=self.user)


class CourseAuthor(models.Model):

    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        models.SET_NULL,
        verbose_name=_('Professor'),
        related_name='authoring_courses',
        blank=True,
        null=True,
    )
    course = models.ForeignKey(
        Course,
        models.CASCADE,
        verbose_name=_('Course'),
        related_name='course_authors',
    )
    biography = models.TextField(
        _('Biography'),
        blank=True,
        null=True,
    )
    picture = models.ImageField(
        _('Picture'),
        upload_to=hash_name('bio-pictures', 'name'),
        blank=True,
        null=True,
    )
    name = models.TextField(
        _('Name'),
        max_length=30,
        blank=True,
        null=True,
    )
    position = models.IntegerField(
        default=100,
        null=True,
        blank=True,
    )

    class Meta:
        unique_together = (('user', 'course'),)
        verbose_name = _('Course Author')
        verbose_name_plural = _('Course Authors')
        ordering = ['position']

Bruno Martin's avatar
Bruno Martin committed
631
    def __str__(self):
632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
        return u'%s @ %s' % (self.user, self.course)

    def get_name(self):
        if self.name:
            return self.name
        elif self.user:
            return self.user.get_full_name()
        else:
            return ''

    def get_biography(self):
        if self.biography:
            return self.biography
        elif self.user:
            return self.user.biography

    def get_picture_url(self):
        if self.picture:
            location = "/%s/%s" % (settings.MEDIA_URL, self.picture)
            return re.sub('/+', '/', location)
        elif self.user:
            return self.user.get_picture_thumb_url()


class ProfessorMessage(models.Model):
    professor = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        models.PROTECT,
        verbose_name=_('Professor')
    )
    users = models.ManyToManyField(
        settings.AUTH_USER_MODEL,
        related_name='messages',
665
        blank=True,
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
    )
    subject = models.CharField(
        _('Subject'),
        max_length=255,
    )
    message = models.TextField(
        _('Message'),
    )
    date = models.DateTimeField(
        _('Date'),
        auto_now_add=True
    )
    course = models.ForeignKey(
        Course,
        models.CASCADE,
        verbose_name=_('Course'),
        null=True,
683
        blank=True,
684
    )
685 686 687 688
    groups = models.ManyToManyField(
        Group,
        verbose_name=_('groups'),
        blank=True,
689 690
        help_text=_('The Groups that will receive this message.'),
        related_name="message_groups",
691
    )
692
    classes = models.ManyToManyField(
693 694
        'Class',
        verbose_name=_('Default Class'),
695
        related_name='message_courses',
696 697 698 699 700 701
        blank=True,
    )
    classrooms = models.ManyToManyField(
        'Classroom',
        verbose_name=_('Classrooms'),
        related_name='messages',
702 703
        blank=True,
    )
704

705 706 707
    def __str__(self):
        return self.professor.name + " - " + self.subject + " - " + str(self.date)

708
    def send(self):
709 710
        # bcc = list with all destinataries
        # batch = bcc.split( constant )
711
        # for each batch ->
712 713 714 715 716
            # send message
            # save status
            # if it goes wrong
            # split batch by 2 and try it again (binary search)
        # check if everything is sent
717 718

        email_batch_size = settings.PROFESSOR_MESSAGE_CHUNK_SIZE
719 720 721 722 723 724 725
        bcc = [u.email for u in self.users.all() if u.is_active and re.match(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", u.email)]
        try:
            et = EmailTemplate.objects.get(name='professor-message')
        except EmailTemplate.DoesNotExist:
            et = EmailTemplate(name="professor-message", subject="{{subject}}", template="{{message|safe}}")
        subject = Template(et.subject).render(Context({'subject': self.subject}))
        message = Template(et.template).render(Context({'message': self.message}))
726 727 728 729 730 731 732 733 734 735 736 737 738 739

        # Iterate over the bcc list to send emails in chunks
        # Maximum chunk size is email_batch_size
        start = 0
        end = min(email_batch_size, len(bcc))
        while start < len(bcc):
            email = EmailMessage(subject, message, settings.DEFAULT_FROM_EMAIL,
                                 [settings.DEFAULT_FROM_EMAIL, ], bcc[start:end])
            email.content_subtype = "html"
            email.send()
            start = end
            end = min(end + email_batch_size, len(bcc))

        return None
740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821


class ProfessorMessageRead(models.Model):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        models.CASCADE,
        verbose_name=_('Student'),
    )
    message = models.ForeignKey(
        ProfessorMessage,
        models.CASCADE,
        verbose_name=_('ProfessorMessage'),
        related_name='read_status',
    )
    is_read = models.BooleanField(default=False)

    def __str__(self):
        return self.user.username + " " + self.message.subject + " " + str(self.is_read)

    class Meta:
        unique_together = ('user', 'message')


class PositionedModel(models.Model):
    collection_name = 'pk'

    class Meta:
        abstract = True

    def save(self, *args, **kwargs):
        if not self.id:
            filters = {self.collection_name: getattr(self, self.collection_name)}
            latest = self.__class__.objects.filter(**filters) \
                .aggregate(models.Max('position')) \
                .get('position__max')

            if latest is not None:
                self.position = latest + 1

        return super(PositionedModel, self).save(*args, **kwargs)


class Lesson(PositionedModel):
    STATES = (
        ('draft', _('Draft')),
        ('published', _('Published')),
    )

    course = models.ForeignKey(
        Course,
        models.CASCADE,
        verbose_name=_('Course'),
        related_name='lessons',
    )
    desc = models.TextField(
        _('Description')
    )
    name = models.CharField(
        _('Name'),
        max_length=255,
    )
    notes = models.TextField(
        _('Notes'),
        default="",
        blank=True,
    )
    position = models.IntegerField(
        default=0,
    )
    slug = AutoSlugField(
        _('Slug'),
        populate_from='name',
        max_length=128,
        editable=False,
        unique=True,
    )
    status = models.CharField(
        _('Status'),
        choices=STATES,
        default=STATES[0][0],
        max_length=64,
    )
822 823 824 825 826 827
    thumbnail = models.ImageField(
        _('Thumbnail'),
        upload_to=hash_name('lesson_thumbnails', 'name'),
        null=True,
        blank=True,
    )
828 829

    collection_name = 'course'
830 831 832 833
    class Meta:
        verbose_name = _('Lesson')
        verbose_name_plural = _('Lessons')
        ordering = ['position']
834 835 836 837 838

    @property
    def is_course_last_lesson(self):
        lessons = list(self.course.public_lessons)
        return len(lessons) > 0 and self == lessons[-1]
839

840 841


Bruno Martin's avatar
Bruno Martin committed
842
    def __str__(self):
843 844 845
        return self.name

    @property
846
    def thumbnail_url(self):
847 848 849 850 851
        try:
            first_vid_unit = self.units.exclude(video=None).order_by('position')[0]
            thumbnail = 'http://i1.ytimg.com/vi/' + first_vid_unit.video.youtube_id + '/hqdefault.jpg'
            return thumbnail
        except IndexError:
852 853
            if self.thumbnail:
                return self.thumbnail.url
854 855 856
            return staticfiles_storage.url('img/lesson-default.png')

    def activity_count(self):
857 858
        from courses_learning_objects.models import LearningObject
        return LearningObject.objects.filter(unit__lesson=self).count()
859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920

    def unit_count(self):
        return self.units.all().count()

    def video_count(self):
        return self.units.exclude(video=None).count()

    def is_ready(self):
        return self.status == 'published' and self.units.exists()

    def first_unit(self):
        if self.units.exists():
            try:
                return self.units.order_by('position').first()
            except AttributeError:
                return None


class Unit(PositionedModel):
    title = models.CharField(
        _('Title'),
        max_length=128,
        blank=True,
    )
    lesson = models.ForeignKey(
        Lesson,
        models.CASCADE,
        verbose_name=_('Lesson'),
        related_name='units',
    )
    video = models.ForeignKey(
        Video,
        models.SET_NULL,
        verbose_name=_('Video'),
        related_name='unit',
        null=True,
        blank=True,
    )
    side_notes = models.TextField(
        _('Side notes'),
        blank=True,
    )
    position = models.IntegerField(
        default=0,
    )
    notes = GenericRelation(
        Note,
    )
    chat_room = models.CharField(
        _('Chat Room'),
        max_length=255,
        blank=True,
        null=True,
    )

    collection_name = 'lesson'

    class Meta:
        verbose_name = _('Unit')
        verbose_name_plural = _('Units')
        ordering = ['lesson', 'position']

Bruno Martin's avatar
Bruno Martin committed
921 922
    def __str__(self):
        return '{} / {} / {} - {}'.format(self.lesson.course.name, self.lesson.name, self.title, self.position)
923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950


class StudentProgress(models.Model):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        models.CASCADE,
        verbose_name=_('Student'),
    )
    unit = models.ForeignKey(
        Unit,
        models.CASCADE,
        verbose_name=_('Unit'),
        related_name='progress',
    )
    complete = models.DateTimeField(
        editable=True,
        null=True,
        blank=True,
    )
    last_access = models.DateTimeField(
        auto_now=True,
        editable=False,
    )

    class Meta:
        unique_together = (('user', 'unit'),)
        verbose_name = _('Student Progress')

Bruno Martin's avatar
Bruno Martin committed
951
    def __str__(self):
952 953 954 955 956 957 958 959 960 961 962 963
        return u'%s @ %s c: %s la: %s' % (
            self.user, self.unit, self.complete, self.last_access)


class EmailTemplate(models.Model):
    name = models.CharField(
        max_length=255,
    )
    subject = models.CharField(
        max_length=255,
    )
    template = models.TextField()