~azzar1/unity/add-show-desktop-key

« back to all changes in this revision

Viewing changes to ivle/database.py

  • Committer: William Grant
  • Date: 2010-07-28 05:06:15 UTC
  • Revision ID: grantw@unimelb.edu.au-20100728050615-uwbxn9frla3pdw8m
Encode content_type when downloading files. cjson made us write bad code.

Show diffs side-by-side

added added

removed removed

Lines of Context:
26
26
import hashlib
27
27
import datetime
28
28
import os
 
29
import urlparse
 
30
import urllib
29
31
 
30
32
from storm.locals import create_database, Store, Int, Unicode, DateTime, \
31
33
                         Reference, ReferenceSet, Bool, Storm, Desc
148
150
            Offering.semester_id == Semester.id,
149
151
            Offering.subject_id == Subject.id).order_by(
150
152
                Desc(Semester.year),
151
 
                Desc(Semester.semester),
 
153
                Desc(Semester.display_name),
152
154
                Desc(Subject.code)
153
155
            )
154
156
 
229
231
        """Find a user in a store by login name."""
230
232
        return store.find(cls, cls.login == unicode(login)).one()
231
233
 
 
234
    def get_svn_url(self, config):
 
235
        """Get the subversion repository URL for this user or group."""
 
236
        url = config['urls']['svn_addr']
 
237
        path = 'users/%s' % self.login
 
238
        return urlparse.urljoin(url, path)
 
239
 
232
240
    def get_permissions(self, user, config):
233
241
        """Determine privileges held by a user over this object.
234
242
 
290
298
        """
291
299
        return self.offerings.find(Offering.semester_id == Semester.id,
292
300
                               Semester.year == unicode(year),
293
 
                               Semester.semester == unicode(semester)).one()
 
301
                               Semester.url_name == unicode(semester)).one()
294
302
 
295
303
class Semester(Storm):
296
304
    """A semester in which subjects can be run."""
299
307
 
300
308
    id = Int(primary=True, name="semesterid")
301
309
    year = Unicode()
302
 
    semester = Unicode()
 
310
    code = Unicode()
 
311
    url_name = Unicode()
 
312
    display_name = Unicode()
303
313
    state = Unicode()
304
314
 
305
315
    offerings = ReferenceSet(id, 'Offering.semester_id')
311
321
    __init__ = _kwarg_init
312
322
 
313
323
    def __repr__(self):
314
 
        return "<%s %s/%s>" % (type(self).__name__, self.year, self.semester)
 
324
        return "<%s %s/%s>" % (type(self).__name__, self.year, self.code)
315
325
 
316
326
class Offering(Storm):
317
327
    """An offering of a subject in a particular semester."""
429
439
        # XXX: Respect extensions.
430
440
        return self.projects.find(Project.deadline > datetime.datetime.now())
431
441
 
 
442
    def has_worksheet_cutoff_passed(self, user):
 
443
        """Check whether the worksheet cutoff has passed.
 
444
        A user is required, in case we support extensions.
 
445
        """
 
446
        if self.worksheet_cutoff is None:
 
447
            return False
 
448
        else:
 
449
            return self.worksheet_cutoff < datetime.datetime.now()
 
450
 
432
451
    def clone_worksheets(self, source):
433
452
        """Clone all worksheets from the specified source to this offering."""
434
453
        import ivle.worksheet.utils
593
612
        return "<%s '%s' in %r>" % (type(self).__name__, self.short_name,
594
613
                                  self.project_set.offering)
595
614
 
596
 
    def can_submit(self, principal, user):
 
615
    def can_submit(self, principal, user, late=False):
 
616
        """
 
617
        @param late: If True, does not take the deadline into account.
 
618
        """
597
619
        return (self in principal.get_projects() and
598
 
                not self.has_deadline_passed(user))
 
620
                (late or not self.has_deadline_passed(user)))
599
621
 
600
 
    def submit(self, principal, path, revision, who):
 
622
    def submit(self, principal, path, revision, who, late=False):
601
623
        """Submit a Subversion path and revision to a project.
602
624
 
603
625
        @param principal: The owner of the Subversion repository, and the
605
627
        @param path: A path within that repository to submit.
606
628
        @param revision: The revision of that path to submit.
607
629
        @param who: The user who is actually making the submission.
 
630
        @param late: If True, will not raise a DeadlinePassed exception even
 
631
            after the deadline. (Default False.)
608
632
        """
609
633
 
610
 
        if not self.can_submit(principal, who):
 
634
        if not self.can_submit(principal, who, late=late):
611
635
            raise DeadlinePassed()
612
636
 
613
637
        a = Assessed.get(Store.of(self), principal, self)
649
673
            return
650
674
        return assessed.submissions
651
675
 
 
676
    @property
 
677
    def can_delete(self):
 
678
        """Can only delete if there are no submissions."""
 
679
        return self.submissions.count() == 0
652
680
 
 
681
    def delete(self):
 
682
        """Delete the project. Fails if can_delete is False."""
 
683
        if not self.can_delete:
 
684
            raise IntegrityError()
 
685
        for assessed in self.assesseds:
 
686
            assessed.delete()
 
687
        Store.of(self).remove(self)
653
688
 
654
689
class ProjectGroup(Storm):
655
690
    """A group of students working together on a project."""
705
740
            Semester.id == Offering.semester_id,
706
741
            (not active_only) or (Semester.state == u'current'))
707
742
 
 
743
    def get_svn_url(self, config):
 
744
        """Get the subversion repository URL for this user or group."""
 
745
        url = config['urls']['svn_addr']
 
746
        path = 'groups/%s_%s_%s_%s' % (
 
747
                self.project_set.offering.subject.short_name,
 
748
                self.project_set.offering.semester.year,
 
749
                self.project_set.offering.semester.url_name,
 
750
                self.name
 
751
                )
 
752
        return urlparse.urljoin(url, path)
708
753
 
709
754
    def get_permissions(self, user, config):
710
755
        if user.admin or user in self.members:
802
847
 
803
848
        return a
804
849
 
 
850
    def delete(self):
 
851
        """Delete the assessed. Fails if there are any submissions. Deletes
 
852
        extensions."""
 
853
        if self.submissions.count() > 0:
 
854
            raise IntegrityError()
 
855
        for extension in self.extensions:
 
856
            extension.delete()
 
857
        Store.of(self).remove(self)
805
858
 
806
859
class ProjectExtension(Storm):
807
860
    """An extension granted to a user or group on a particular project.
814
867
    id = Int(name="extensionid", primary=True)
815
868
    assessed_id = Int(name="assessedid")
816
869
    assessed = Reference(assessed_id, Assessed.id)
817
 
    deadline = DateTime()
 
870
    days = Int()
818
871
    approver_id = Int(name="approver")
819
872
    approver = Reference(approver_id, User.id)
820
873
    notes = Unicode()
821
874
 
 
875
    def delete(self):
 
876
        """Delete the extension."""
 
877
        Store.of(self).remove(self)
 
878
 
822
879
class SubmissionError(Exception):
823
880
    """Denotes a validation error during submission."""
824
881
    pass
858
915
        return "/files/%s/%s/%s?r=%d" % (user.login,
859
916
            self.assessed.checkout_location, submitpath, self.revision)
860
917
 
 
918
    def get_svn_url(self, config):
 
919
        """Get subversion URL for this submission"""
 
920
        princ = self.assessed.principal
 
921
        base = princ.get_svn_url(config)
 
922
        if self.path.startswith(os.sep):
 
923
            return os.path.join(base,
 
924
                    urllib.quote(self.path[1:].encode('utf-8')))
 
925
        else:
 
926
            return os.path.join(base, urllib.quote(self.path.encode('utf-8')))
 
927
 
 
928
    def get_svn_export_command(self, req):
 
929
        """Returns a Unix shell command to export a submission"""
 
930
        svn_url = self.get_svn_url(req.config)
 
931
        username = (req.user.login if req.user.login.isalnum() else
 
932
                "'%s'"%req.user.login)
 
933
        export_dir = self.assessed.principal.short_name
 
934
        return "svn export --username %s -r%d '%s' %s"%(req.user.login,
 
935
                self.revision, svn_url, export_dir)
 
936
 
861
937
    @staticmethod
862
938
    def test_and_normalise_path(path):
863
939
        """Test that path is valid, and normalise it. This prevents possible
877
953
            raise SubmissionError("Path must not contain '\\n', '[' or ']'")
878
954
        return os.path.normpath(path)
879
955
 
 
956
    @property
 
957
    def late(self):
 
958
        """True if the project was submitted late."""
 
959
        return self.days_late > 0
 
960
 
 
961
    @property
 
962
    def days_late(self):
 
963
        """The number of days the project was submitted late (rounded up), or
 
964
        0 if on-time."""
 
965
        # XXX: Need to respect extensions.
 
966
        return max(0,
 
967
            (self.date_submitted - self.assessed.project.deadline).days + 1)
 
968
 
880
969
# WORKSHEETS AND EXERCISES #
881
970
 
882
971
class Exercise(Storm):
889
978
    id = Unicode(primary=True, name="identifier")
890
979
    name = Unicode()
891
980
    description = Unicode()
 
981
    _description_xhtml_cache = Unicode(name='description_xhtml_cache')
892
982
    partial = Unicode()
893
983
    solution = Unicode()
894
984
    include = Unicode()
937
1027
 
938
1028
        return perms
939
1029
 
940
 
    def get_description(self):
941
 
        """Return the description interpreted as reStructuredText."""
942
 
        return rst(self.description)
 
1030
    def _cache_description_xhtml(self, invalidate=False):
 
1031
        # Don't regenerate an existing cache unless forced.
 
1032
        if self._description_xhtml_cache is not None and not invalidate:
 
1033
            return
 
1034
 
 
1035
        if self.description:
 
1036
            self._description_xhtml_cache = rst(self.description)
 
1037
        else:
 
1038
            self._description_xhtml_cache = None
 
1039
 
 
1040
    @property
 
1041
    def description_xhtml(self):
 
1042
        """The XHTML exercise description, converted from reStructuredText."""
 
1043
        self._cache_description_xhtml()
 
1044
        return self._description_xhtml_cache
 
1045
 
 
1046
    def set_description(self, description):
 
1047
        self.description = description
 
1048
        self._cache_description_xhtml(invalidate=True)
943
1049
 
944
1050
    def delete(self):
945
1051
        """Deletes the exercise, providing it has no associated worksheets."""
964
1070
    assessable = Bool()
965
1071
    published = Bool()
966
1072
    data = Unicode()
 
1073
    _data_xhtml_cache = Unicode(name='data_xhtml_cache')
967
1074
    seq_no = Int()
968
1075
    format = Unicode()
969
1076
 
1016
1123
 
1017
1124
        return perms
1018
1125
 
1019
 
    def get_xml(self):
1020
 
        """Returns the xml of this worksheet, converts from rst if required."""
1021
 
        if self.format == u'rst':
1022
 
            ws_xml = rst(self.data)
1023
 
            return ws_xml
 
1126
    def _cache_data_xhtml(self, invalidate=False):
 
1127
        # Don't regenerate an existing cache unless forced.
 
1128
        if self._data_xhtml_cache is not None and not invalidate:
 
1129
            return
 
1130
 
 
1131
        if self.format == u'rst':
 
1132
            self._data_xhtml_cache = rst(self.data)
 
1133
        else:
 
1134
            self._data_xhtml_cache = None
 
1135
 
 
1136
    @property
 
1137
    def data_xhtml(self):
 
1138
        """The XHTML of this worksheet, converted from rST if required."""
 
1139
        # Update the rST -> XHTML cache, if required.
 
1140
        self._cache_data_xhtml()
 
1141
 
 
1142
        if self.format == u'rst':
 
1143
            return self._data_xhtml_cache
1024
1144
        else:
1025
1145
            return self.data
1026
1146
 
 
1147
    def set_data(self, data):
 
1148
        self.data = data
 
1149
        self._cache_data_xhtml(invalidate=True)
 
1150
 
1027
1151
    def delete(self):
1028
1152
        """Deletes the worksheet, provided it has no attempts on any exercises.
1029
1153