models.py 31.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
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
Glaucia S. Santos's avatar
Glaucia S. Santos committed
12
from django.contrib.postgres.fields import ArrayField
13 14 15 16 17 18 19
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
20 21
from discussion.models import Forum

22 23
from .videos.models import Video
from .notes.models import Note
24
from .course_material.models import CourseMaterial
25
from .classes.models import Class
Bruno Martin's avatar
Bruno Martin committed
26
from .classroom.models import Classroom, Event
27 28 29 30

import re


Matheus Miranda's avatar
Matheus Miranda committed
31 32 33 34 35 36 37 38
class CourseCategory(models.Model):
    parent = models.ForeignKey('self', models.CASCADE, verbose_name=_("course category parent"), null=True, blank=True)
    name = models.CharField(_("title"), max_length=124)
    slug = AutoSlugField(populate_from="name", unique=True)
    description = models.TextField(_("description"), blank=True)
    color = models.CharField(_("color"), max_length=7, blank=True,
                             help_text=_("Title color in hex format (i.e: #1aafd0)."))

Matheus Miranda's avatar
Matheus Miranda committed
39 40 41 42
    class Meta:
        verbose_name = _('Course Category')
        verbose_name_plural = _('Course Categories')

Matheus Miranda's avatar
Matheus Miranda committed
43 44 45 46
    def __str__(self):
        return self.name


Matheus Miranda's avatar
Matheus Miranda committed
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 73 74 75 76 77 78 79 80 81
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,
    )
Glaucia S. Santos's avatar
Glaucia S. Santos committed
82 83 84 85 86 87 88 89
    informations = models.TextField(
        _('Informations'),
        blank=True,
    )
    description = models.TextField(
        _('Description'),
        blank=True,
    )
90 91 92 93 94 95 96 97
    structure = models.TextField(
        _('Structure'),
        blank=True,
    )
    workload = models.TextField(
        _('Workload'),
        blank=True,
    )
98 99 100 101
    course_load = models.IntegerField(
        _('Course Load'),
        null=True,
    )
102 103 104 105 106 107 108 109 110 111
    pronatec = models.TextField(
        _('Pronatec'),
        blank=True,
    )
    status = models.CharField(
        _('Status'),
        choices=STATES,
        default=STATES[0][0],
        max_length=64,
    )
Glaucia S. Santos's avatar
Glaucia S. Santos committed
112 113 114 115 116 117 118 119
    lang = ArrayField(
        models.CharField(
            choices=settings.LANGUAGES,
            blank=True,
            default=settings.LANGUAGES[0],
            max_length=64),
        blank=True,
        null=True,
Glaucia S. Santos's avatar
Glaucia S. Santos committed
120
    )
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
    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(
162
        'Class',
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
        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",
    )

183 184 185 186 187
    is_public = models.BooleanField(
        _('Public'),
        default=False,
    )

Bruno Martin's avatar
Bruno Martin committed
188 189 190 191 192 193 194 195
    forum = models.OneToOneField(
        Forum,
        models.SET_NULL,
        verbose_name=_('Forum'),
        related_name='course',
        null=True,
        blank=True,
    )
Matheus Miranda's avatar
Matheus Miranda committed
196
    category = models.ManyToManyField(CourseCategory, verbose_name=_('category'), blank=True)
Bruno Martin's avatar
Bruno Martin committed
197

198 199 200 201
    class Meta:
        verbose_name = _('Course')
        verbose_name_plural = _('Courses')

Bruno Martin's avatar
Bruno Martin committed
202
    def __str__(self):
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
        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:
250
            student_enrolled = self.course_students.filter(
251
                user__classes__in=classes, user__is_active=True).count()
252
        else:
253
            student_enrolled = self.course_students.filter(user__is_active=True).count()
254 255 256 257 258 259 260 261 262 263
        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(
264
                    complete=None, user__is_active=True).filter(unit__lesson=lesson)
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 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
                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):
315
        if user.is_anonymous:
316 317 318 319 320 321
            return False

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

    def is_assistant_or_coordinator(self, user):
322
        if user.is_anonymous:
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
            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)


Matheus Miranda's avatar
Matheus Miranda committed
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
class CourseTrack(models.Model):
    name = models.CharField(
        _('Name'),
        max_length=255,
    )
    slug = AutoSlugField(
        _('Slug'),
        populate_from="name",
        unique=True
    )
    courses = models.ManyToManyField(
        Course,
        verbose_name='courses',
        blank=True,
    )
Matheus Miranda's avatar
Matheus Miranda committed
367 368
    home_position = models.IntegerField(
        null=True,
369
        blank=True,
Matheus Miranda's avatar
Matheus Miranda committed
370
    )
Matheus Miranda's avatar
Matheus Miranda committed
371 372 373 374 375 376 377 378 379

    class Meta:
        verbose_name = _('Course Track')
        verbose_name_plural = _('Course Tracks')

    def __str__(self):
        return self.name


380 381 382 383 384 385 386 387 388 389
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'),
390
        related_name='course_students',
391 392 393 394 395 396 397 398 399
    )
    start_date = models.DateTimeField(
        default=timezone.now,
    )

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

Bruno Martin's avatar
Bruno Martin committed
400
    def __str__(self):
401 402 403 404 405 406 407 408 409 410
        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
411 412
    def _activities_and_course_finished(self):
        """
413
        This method verifies if the user made all discussion activities
Bruno Martin's avatar
Bruno Martin committed
414 415
        AND has the perent progress
        """
416 417
        from courses_learning_objects.models import LearningObject, Answer
        activities = LearningObject.objects\
418 419 420 421 422 423
            .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
424
        return self.percent_progress() >= self.min_percent_to_complete() and \
425 426 427 428 429 430 431 432
               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
433
        return self._course_finished()
434

435 436 437 438 439 440 441 442 443 444 445 446
    @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

447 448 449
    def can_emmit_receipt(self):
        if not self.get_current_class().user_can_certificate and not self.course_finished:
            return False
450
        if self.get_current_class().user_can_certificate_even_without_progress and self.certificate.document_type == 'certificate':
451 452 453 454
            return True
        return self.course_finished

    def get_current_class(self):
455 456
        try:
            return Class.objects.get(students=self.user, course=self.course)
457 458
        except Class.MultipleObjectsReturned:
            return Class.objects.filter(students=self.user, course=self.course).first()
459 460 461
        except Class.DoesNotExist:
            self.course.default_class.students.add(self.user)
            return self.course.default_class
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 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

    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
542
        from courses_learning_objects.models import LearningObject, Answer
543 544 545 546 547 548 549 550 551 552 553 554
        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)
555
                activities = LearningObject.objects.filter(unit__lesson=lesson, type='discussion')
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
                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
616
    def __str__(self):
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 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 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
        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
694
    def __str__(self):
695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
        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',
728
        blank=True,
729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745
    )
    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,
746
        blank=True,
747
    )
748 749 750 751
    groups = models.ManyToManyField(
        Group,
        verbose_name=_('groups'),
        blank=True,
752 753
        help_text=_('The Groups that will receive this message.'),
        related_name="message_groups",
754
    )
755
    classes = models.ManyToManyField(
756 757
        'Class',
        verbose_name=_('Default Class'),
758
        related_name='message_courses',
759 760 761 762 763 764
        blank=True,
    )
    classrooms = models.ManyToManyField(
        'Classroom',
        verbose_name=_('Classrooms'),
        related_name='messages',
765 766
        blank=True,
    )
767

768
    def __str__(self):
769
        return self.subject + " - " + str(self.date)
770

771 772 773 774 775 776 777 778 779 780 781 782 783
    def send_emails(self, bcc, message, subject, email_batch_size):
        # 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))

784
    def send(self):
785 786
        # bcc = list with all destinataries
        # batch = bcc.split( constant )
787
        # for each batch ->
788 789 790 791 792
            # send message
            # save status
            # if it goes wrong
            # split batch by 2 and try it again (binary search)
        # check if everything is sent
793 794

        email_batch_size = settings.PROFESSOR_MESSAGE_CHUNK_SIZE
795

796 797 798 799
        try:
            et = EmailTemplate.objects.get(name='professor-message')
        except EmailTemplate.DoesNotExist:
            et = EmailTemplate(name="professor-message", subject="{{subject}}", template="{{message|safe}}")
800

801 802 803 804
        if settings.MULTILINGUAL_EMAIL_SEND:
            bcc_en = [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) and u.preferred_language == 'en']
            bcc_es = [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) and u.preferred_language == 'es']
            bcc_pt_br = [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) and u.preferred_language == 'pt-br']
805

806 807 808 809 810 811 812
            subject_en = Template(et.subject).render(Context({'subject': self.subject_en}))
            message_en = Template(et.template).render(Context({'message': self.message_en}))
            self.send_emails(bcc_en, message_en, subject_en, email_batch_size)

            subject_es = Template(et.subject).render(Context({'subject': self.subject_es}))
            message_es = Template(et.template).render(Context({'message': self.message_es}))
            self.send_emails(bcc_es, message_es, subject_es, email_batch_size)
813

814 815 816 817 818 819 820 821 822 823
            subject_pt_br = Template(et.subject).render(Context({'subject': self.subject_pt_br}))
            message_pt_br = Template(et.template).render(Context({'message': self.message_pt_br}))
            self.send_emails(bcc_pt_br, message_pt_br, subject_pt_br, email_batch_size)
        else:
            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)]
            subject = Template(et.subject).render(Context({'subject': self.subject}))
            message = Template(et.template).render(Context({'message': self.message}))
            self.send_emails(bcc, message, subject, email_batch_size)

        return None
824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 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

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,
    )
905 906 907 908 909 910
    thumbnail = models.ImageField(
        _('Thumbnail'),
        upload_to=hash_name('lesson_thumbnails', 'name'),
        null=True,
        blank=True,
    )
911 912

    collection_name = 'course'
913 914 915 916
    class Meta:
        verbose_name = _('Lesson')
        verbose_name_plural = _('Lessons')
        ordering = ['position']
917 918 919 920 921

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

923 924


Bruno Martin's avatar
Bruno Martin committed
925
    def __str__(self):
926 927 928
        return self.name

    @property
929
    def thumbnail_url(self):
930 931 932 933 934
        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:
935 936
            if self.thumbnail:
                return self.thumbnail.url
937 938 939
            return staticfiles_storage.url('img/lesson-default.png')

    def activity_count(self):
940 941
        from courses_learning_objects.models import LearningObject
        return LearningObject.objects.filter(unit__lesson=self).count()
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003

    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
1004 1005
    def __str__(self):
        return '{} / {} / {} - {}'.format(self.lesson.course.name, self.lesson.name, self.title, self.position)
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033


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
1034
    def __str__(self):
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
        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()