예제 #1
0
    def set_tg(self, access_token):
        """ Try to grab the treatment group number for the student.
        If there is no treatment group number available, request it
        from the server.
        """
        # Checks to see the student currently has a treatment group number. If
        # not, calls helper function in auth.py
        if not os.path.isfile(self.current_working_dir + LOCAL_TG_FILE):
            cur_email = auth.get_student_email(access_token)
            log.info("Current email is %s", cur_email)
            if not cur_email:
                self.tg_id = -1
                return EMPTY_MISUCOUNT_TGID_PRNTEDMSG

            tg_url = ("{}{}/{}{}".format(TGSERVER, cur_email,
                                         self.assignment_name,
                                         TG_SERVER_ENDING))
            try:
                log.info("Accessing treatment server at %s", tg_url)
                data = json.loads((urlopen(tg_url,
                                           timeout=1).read().decode("utf-8")))
            except IOError:
                data = {"tg": -1}
                log.warning("Failed to communicate to server", exc_info=True)

            if data.get("tg") is None:
                log.warning("Server returned back a bad treatment group ID.")
                data = {"tg": -1}

            with open(self.current_working_dir + LOCAL_TG_FILE, "w") as fd:
                fd.write(str(data["tg"]))

        tg_file = open(self.current_working_dir + LOCAL_TG_FILE, 'r')
        self.tg_id = int(tg_file.read())
예제 #2
0
파일: hinting.py 프로젝트: hbgtjxzbbx/cs61a
    def query_server(self, messages, test):
        access_token, _, _ = auth.get_storage()
        user = auth.get_student_email(access_token) or access_token
        if user:
            # The hinting server should not recieve identifying information
            user = hash(user)

        data = {
            'assignment': self.assignment.endpoint,
            'test': test,
            'messages': messages,
            'user': user
        }

        serialized_data = json.dumps(data).encode(encoding='utf-8')

        address = self.HINT_SERVER + self.HINT_ENDPOINT

        log.info('Sending hint request to %s', address)
        request = urllib.request.Request(address)
        request.add_header("Content-Type", "application/json")

        response = urllib.request.urlopen(request, serialized_data, 35)
        return json.loads(response.read().decode('utf-8'))
예제 #3
0
 def get_student_email(self):
     return auth.get_student_email(self.cmd_args, endpoint=self.endpoint)
예제 #4
0
 def get_student_email(self):
     return auth.get_student_email(self.cmd_args, endpoint=self.endpoint)
예제 #5
0
    def start_firebase(self, messages):
        access_token = auth.authenticate(False)
        email = auth.get_student_email(access_token)
        identifier = auth.get_identifier(token=access_token, email=email)

        firebase = pyrebase.initialize_app(self.FIREBASE_CONFIG)
        self.fire_auth = firebase.auth()
        self.fire_db = firebase.database()

        self.user_email = email
        self.hostname = platform.node()

        data = {
            'access_token': access_token,
            'email': email,
            'identifier': identifier,
            'assignment': self.assignment.endpoint,
            'file_contents': messages.get('file_contents'),
            'analytics': messages.get('analytics'),
        }

        # Check for existing sessions first - TBD Future
        # existing_sessions = self.send_messages(data, endpoint='/collab/list')
        # response = self.prompt_for_existing_session(existing_sessions.get('sessions'))
        # if response:
        #     data['desired_session'] = response

        # Send data to collaborate server
        response_data = self.send_messages(data, self.LONG_TIMEOUT)
        if 'error' in response_data or 'session' not in response_data:
            print("There was an error while starting the session: {} Try again later"
                  .format(response_data.get('error')))
            log.warning("Error: {}".format(response_data.get('error')))
            return

        self.session_id = response_data['session']
        self.short_url = response_data['short_url']
        self.login_user = response_data.get('login_user')

        # Login as the firebase user
        email, password = response_data.get('login_user'), response_data.get('password')

        try:
            self.fire_user = self.fire_auth.sign_in_with_email_and_password(email,
                                                                            password)
            self.fire_uid = self.fire_user['localId']
        except (ValueError, KeyError) as e:
            log.warning("Could not login", exc_info=True)
            print("Could not login to the collaboration server.")
            return

        self.stream = (self.get_firebase()
                           .child('actions').stream(self.stream_listener,
                                                    self.fire_user['idToken']))

        self.presence = (self.get_firebase()
                             .child('clients').push({'computer': platform.node(),
                                                     'uid': self.fire_uid,
                                                     'owner': self.user_email,
                                                     'email': self.user_email},
                                                    self.fire_user['idToken']))

        # Parse response_url
        if response_data:
            open_url = response_data['url']
            if 'access_token' not in open_url:
                open_url = open_url + "?access_token={}".format(access_token)
            could_open = webbrowser.open_new(open_url)
            if not could_open:
                print("Could not open browser. Go to {}".format(open_url))
        else:
            log.error("There was an error with the server. Please try again later!")
            return

        print("Tell your group members or course staff to go to {}"
              .format(self.short_url))

        while True:
            data = input("[{}] Type exit to disconnect: ".format(self.short_url))
            if data.strip().lower() == 'exit':
                raise ValueError('Done with session')