Example #1
0
    def get(self, *args, **kwargs):
        assignment_id = self.request.GET['assignmentId']
        worker_id = self.request.GET['workerId']
        if self.session.mturk_qualification_type_id:
            with MTurkConnection(
                    self.request,
                    self.session.mturk_sandbox) as mturk_connection:
                try:
                    mturk_connection.assign_qualification(
                        self.session.mturk_qualification_type_id, worker_id)
                except MTurkRequestError as e:
                    if (e.error_code ==
                            'AWS.MechanicalTurk.QualificationAlreadyExists'):
                        pass
                    else:
                        raise
        try:
            participant = self.session.participant_set.get(
                mturk_worker_id=worker_id, mturk_assignment_id=assignment_id)
        except Participant.DoesNotExist:
            with global_lock():
                try:
                    participant = self.session.get_participants().filter(
                        visited=False).order_by('start_order')[0]
                except IndexError:
                    return HttpResponseNotFound(NO_PARTICIPANTS_LEFT_MSG)

            # 2014-10-17: needs to be here even if it's also set in
            # the next view to prevent race conditions
            participant.visited = True
            participant.mturk_worker_id = worker_id
            participant.mturk_assignment_id = assignment_id
            participant.save()
        return HttpResponseRedirect(participant._start_url())
Example #2
0
    def get(self, *args, **kwargs):
        assignment_id = self.request.GET["assignmentId"]
        worker_id = self.request.GET["workerId"]
        if self.session.mturk_qualification_type_id:
            with MTurkConnection(self.request, self.session.mturk_sandbox) as mturk_connection:
                try:
                    mturk_connection.assign_qualification(self.session.mturk_qualification_type_id, worker_id)
                except MTurkRequestError as e:
                    if e.error_code == "AWS.MechanicalTurk.QualificationAlreadyExists":
                        pass
                    else:
                        raise
        try:
            participant = self.session.participant_set.get(mturk_worker_id=worker_id, mturk_assignment_id=assignment_id)
        except Participant.DoesNotExist:
            with global_lock():
                try:
                    participant = self.session.get_participants().filter(visited=False).order_by("start_order")[0]
                except IndexError:
                    return HttpResponseNotFound(NO_PARTICIPANTS_LEFT_MSG)

            # 2014-10-17: needs to be here even if it's also set in
            # the next view to prevent race conditions
            participant.visited = True
            participant.mturk_worker_id = worker_id
            participant.mturk_assignment_id = assignment_id
            participant.save()
        return HttpResponseRedirect(participant._start_url())
Example #3
0
 def load_participant_labels_to_db(self):
     if self.has_participant_labels():
         encodings = ['ascii', 'utf-8', 'utf-16']
         for e in encodings:
             try:
                 plabel_path = self.participant_label_file
                 with codecs.open(plabel_path, "r", encoding=e) as f:
                     seen = set()
                     labels = []
                     for line in f:
                         label = line.strip()
                         if not label:
                             continue
                         label = validate_alphanumeric(
                             line.strip(),
                             identifier_description='participant label'
                         )
                         if label not in seen:
                             labels.append(label)
                             seen.add(label)
             except UnicodeDecodeError:
                 continue
             except OSError as err:
                 # this code is equivalent to "except FileNotFoundError:"
                 # but works in py2 and py3
                 if err.errno == errno.ENOENT:
                     msg = (
                         'settings.ROOMS: The room "{}" references '
                         ' nonexistent participant_label_file "{}".'
                     )
                     raise IOError(
                         msg.format(self.name, self.participant_label_file)
                     ) from None
                 raise err
             else:
                 with global_lock():
                     # before I used select_for_update to prevent race
                     # conditions. But the queryset was not evaluated
                     # so it did not hit the DB. maybe simpler to use an
                     # explicit lock
                     ExpectedRoomParticipant.objects.select_for_update()
                     ExpectedRoomParticipant.objects.filter(
                         room_name=self.name).delete()
                     ExpectedRoomParticipant.objects.bulk_create(
                         ExpectedRoomParticipant(
                             room_name=self.name,
                             participant_label=participant_label
                         ) for participant_label in labels
                     )
                 self._participant_labels_loaded = True
                 return
         raise Exception(
             'settings.ROOMS: participant_label_file "{}" '
             'not encoded correctly.'.format(self.participant_label_file)
         )
     raise Exception('no guestlist')
Example #4
0
    def get(self, *args, **kwargs):

        anonymous_code = kwargs["anonymous_code"]
        session = get_object_or_404(otree.models.Session, _anonymous_code=anonymous_code)
        with global_lock():
            try:
                participant = session.get_participants().filter(visited=False).order_by("start_order")[0]
            except IndexError:
                return HttpResponseNotFound(NO_PARTICIPANTS_LEFT_MSG)

            # 2014-10-17: needs to be here even if it's also set in
            # the next view to prevent race conditions
            participant.visited = True
            participant.label = self.request.GET.get("participant_label") or participant.label
            participant.save()
        return HttpResponseRedirect(participant._start_url())
 def _player_ready(self, match, data):
     with global_lock():
         self._players_ready.add(match.groupdict()['participant_code'])
         if self._players_ready == set([
                 player.participant.code
                 for player in self.group.get_players()
         ]):
             if RedwoodEvent.objects.filter(
                     component='period_start',
                     session=self.session,
                     subsession=self.subsession.name(),
                     round=self.round_number,
                     group=self.group.id_in_subsession).count() == 0:
                 self.when_all_players_ready()
                 RedwoodEvent(component='period_start',
                              session=self.session,
                              subsession=self.subsession.name(),
                              round=self.round_number,
                              group=self.group.id_in_subsession).save()
Example #6
0
    def get(self, *args, **kwargs):

        anonymous_code = kwargs['anonymous_code']
        session = get_object_or_404(otree.models.Session,
                                    _anonymous_code=anonymous_code)
        with global_lock():
            try:
                participant = session.get_participants().filter(
                    visited=False).order_by('start_order')[0]
            except IndexError:
                return HttpResponseNotFound(NO_PARTICIPANTS_LEFT_MSG)

            # 2014-10-17: needs to be here even if it's also set in
            # the next view to prevent race conditions
            participant.visited = True
            participant.label = (self.request.GET.get('participant_label')
                                 or participant.label)
            participant.save()
        return HttpResponseRedirect(participant._start_url())
Example #7
0
    def dispatch(self, request, *args, **kwargs):
        get_redis_conn()
        session_info = BrowserBotsLauncherSessionCode.objects.first()
        if session_info:
            session = Session.objects.get(code=session_info.code)
            with global_lock():
                participant = session.get_participants().filter(visited=False).order_by("start_order").first()
                if not participant:
                    return HttpResponseNotFound(NO_PARTICIPANTS_LEFT_MSG)

                # 2014-10-17: needs to be here even if it's also set in
                # the next view to prevent race conditions
                participant.visited = True
                participant.save()

            return HttpResponseRedirect(participant._start_url())
        else:
            ctx = {"view": self, "title_text": "Please wait", "body_text": "Waiting for browser bots session to begin"}
            return render_to_response("otree/WaitPage.html", ctx)
Example #8
0
    def dispatch(self, request, *args, **kwargs):
        get_redis_conn()
        session_info = BrowserBotsLauncherSessionCode.objects.first()
        if session_info:
            session = Session.objects.get(code=session_info.code)
            with global_lock():
                participant = session.get_participants().filter(
                    visited=False).order_by('start_order').first()
                if not participant:
                    return HttpResponseNotFound(NO_PARTICIPANTS_LEFT_MSG)

                # 2014-10-17: needs to be here even if it's also set in
                # the next view to prevent race conditions
                participant.visited = True
                participant.save()

            return HttpResponseRedirect(participant._start_url())
        else:
            ctx = {
                'view': self,
                'title_text': 'Please wait',
                'body_text': 'Waiting for browser bots session to begin'
            }
            return render_to_response("otree/WaitPage.html", ctx)
Example #9
0
    def dispatch(self, request, *args, **kwargs):
        self.room_name = kwargs['room']
        try:
            room = ROOM_DICT[self.room_name]
        except KeyError:
            return HttpResponseNotFound('Invalid room specified in url')

        self.uses_pin = room.has_pin_code()

        participant_label = self.request.GET.get('participant_label', '')

        if room.has_participant_labels():
            if not participant_label:
                if not room.use_secure_urls:
                    return super(AssignVisitorToRoom, self).get(args, kwargs)

            if participant_label not in room.get_participant_labels():
                return HttpResponseNotFound(_('Invalid participant label.'))

            if room.use_secure_urls:
                hash = self.request.GET.get('hash')
                if hash != make_hash(participant_label):
                    return HttpResponseNotFound('Invalid hash parameter.')

        if self.uses_pin:
            pin_code = self.request.GET.get('pin')
            if not pin_code:
                return super(AssignVisitorToRoom, self).get(args, kwargs)

            if pin_code != room.get_pin_code():
                return HttpResponseNotFound('The given pin code is incorrect.')

        session = room.session
        if session is None:
            self.tab_unique_id = otree.common_internal.random_chars_10()
            self._socket_url_params = ','.join([
                self.room_name,
                participant_label,
                # random chars in case the participant has multiple tabs open
                self.tab_unique_id,
            ])
            return render_to_response(
                "otree/WaitPageRoom.html", {
                    'view': self,
                    'title_text': _('Please wait'),
                    'body_text': _('Waiting for your session to begin')
                })

        assign_new = not room.has_participant_labels()
        if not assign_new:
            try:
                participant = session.get_participants().get(
                    label=participant_label)
            except Participant.DoesNotExist:
                assign_new = True

        if assign_new:
            with global_lock():
                try:
                    participant = session.get_participants().filter(
                        visited=False).order_by('start_order')[0]
                except IndexError:
                    return HttpResponseNotFound(NO_PARTICIPANTS_LEFT_MSG)

                participant.label = participant_label
                # 2014-10-17: needs to be here even if it's also set in
                # the next view to prevent race conditions
                participant.visited = True
                participant.save()

        return HttpResponseRedirect(participant._start_url())
Example #10
0
    def dispatch(self, request, *args, **kwargs):
        self.room_name = kwargs["room"]
        try:
            room = ROOM_DICT[self.room_name]
        except KeyError:
            return HttpResponseNotFound("Invalid room specified in url")

        self.uses_pin = room.has_pin_code()

        participant_label = self.request.GET.get("participant_label", "")

        if room.has_participant_labels():
            if not participant_label:
                if not room.use_secure_urls:
                    return super(AssignVisitorToRoom, self).get(args, kwargs)

            if participant_label not in room.get_participant_labels():
                return HttpResponseNotFound(_("Invalid participant label."))

            if room.use_secure_urls:
                hash = self.request.GET.get("hash")
                if hash != make_hash(participant_label):
                    return HttpResponseNotFound("Invalid hash parameter.")

        if self.uses_pin:
            pin_code = self.request.GET.get("pin")
            if not pin_code:
                return super(AssignVisitorToRoom, self).get(args, kwargs)

            if pin_code != room.get_pin_code():
                return HttpResponseNotFound("The given pin code is incorrect.")

        session = room.session
        if session is None:
            self.tab_unique_id = otree.common_internal.random_chars_10()
            self._socket_url_params = ",".join(
                [
                    self.room_name,
                    participant_label,
                    # random chars in case the participant has multiple tabs open
                    self.tab_unique_id,
                ]
            )
            return render_to_response(
                "otree/WaitPageRoom.html",
                {"view": self, "title_text": _("Please wait"), "body_text": _("Waiting for your session to begin")},
            )

        assign_new = not room.has_participant_labels()
        if not assign_new:
            try:
                participant = session.get_participants().get(label=participant_label)
            except Participant.DoesNotExist:
                assign_new = True

        if assign_new:
            with global_lock():
                try:
                    participant = session.get_participants().filter(visited=False).order_by("start_order")[0]
                except IndexError:
                    return HttpResponseNotFound(NO_PARTICIPANTS_LEFT_MSG)

                participant.label = participant_label
                # 2014-10-17: needs to be here even if it's also set in
                # the next view to prevent race conditions
                participant.visited = True
                participant.save()

        return HttpResponseRedirect(participant._start_url())