Exemplo n.º 1
0
def intent():
    errors = []

    if request.json:
        if 'text' not in request.json:
            errors.append(dict(MissingParameterException('text')))

        if errors:
            return jsonify({'errors': errors}), 400

        text = request.json['text']
        language = request.json.get('language')
        if language:
            if language not in LANGUAGES_CODE:
                return jsonify({
                    'errors': [
                        dict(
                            BadParameterException('language',
                                                  valid_values=LANGUAGES_CODE))
                    ]
                }), 400
        try:
            res = recast_send_request_intent(text, language)
            return jsonify(res['results']), 200
        except InvalidCredentialsException as e:
            return jsonify({'errors': [dict(e)]}), e.status_code
        except ExternalAPIException as e:
            return jsonify({'errors': [dict(e)]}), e.status_code
        except Exception as e:
            logger.error(e)
            return jsonify({'errors': [dict(APIException('nlp_intent'))]}), 500

    else:
        errors.append(dict(APIException('no_content')))
        return jsonify({'errors': errors}), 400
Exemplo n.º 2
0
    def rainwave_auth(self):
        user_id_present = "user_id" in self.request.arguments

        if self.auth_required and not user_id_present:
            raise APIException("missing_argument",
                               argument="user_id",
                               http_code=400)
        if user_id_present and not fieldtypes.numeric(
                self.get_argument("user_id")):
            # do not spit out the user ID back at them, that would create a potential XSS hack
            raise APIException("invalid_argument",
                               argument="user_id",
                               reason="not numeric.",
                               http_code=400)
        if (self.auth_required
                or user_id_present) and not "key" in self.request.arguments:
            raise APIException("missing_argument",
                               argument="key",
                               http_code=400)

        if user_id_present:
            self.user = User(long(self.get_argument("user_id")))
            self.user.ip_address = self.request.remote_ip
            self.user.authorize(self.sid, self.get_argument("key"))
            if not self.user.authorized:
                raise APIException("auth_failed", http_code=403)
            else:
                self._update_phpbb_session(
                    self._get_phpbb_session(self.user.id))
Exemplo n.º 3
0
def request_invite(
        data: schema.UserEmailIn,
        session: db.Session = Depends(get_session),
        _=Depends(anonymous_required),
):
    """Request an invite be sent to the given email.

    Will fail if requested by an authenticated user.
    """
    email = data.email.lower()
    user = session.query(User).filter(User.email == email).first()
    if user:
        raise APIException(detail="This email is already in use.", )
    invitation = get_invite_for_email(session, email)
    # Email the user
    if not send_message(
            recipient=invitation.email,
            template_id=settings.sendgrid_invite_template,
            data={
                "invite_token": str(invitation.uuid),
                "email": invitation.email,
            },
    ):
        if settings.debug:
            logger.debug(f"INVITE TOKEN FOR {email}: {invitation.uuid}")
        raise APIException(
            detail=
            "Unable to send invitation email; please report this to Skaak#0007 on Discord!"
        )
    return {
        "detail":
        "Your invitation has been sent! Please follow the link in your email to set your password."
    }
Exemplo n.º 4
0
    def from_url(cls, url: str) -> 'WebPage':
        existing = cls.objects.filter(url=url).first()

        if existing and existing.content_score is None:
            raise APIException.info(
                'Cet article est en cours de traitement. Merci de réessayer dans quelques minutes.'
            )

        if (existing
                and existing.scores_version == WebPage.CURRENT_SCORES_VERSION
                and existing.updated_at >
                timezone.now() - datetime.timedelta(days=7)):
            logger.info(f"Returning existing object for url {url}")
            return existing

        elif not existing:
            base_domain = extract_base_domain(url)
            logger.debug(f"Base domain found {base_domain}")
            domain, created = BaseDomain.objects.get_or_create(
                base_domain=base_domain)
            existing = cls.objects.create(
                url=url,
                scores_version=WebPage.CURRENT_SCORES_VERSION,
                base_domain=domain,
                total_articles=0)

        try:
            return existing.compute_scores()
        except APIException as e:
            raise e
        except Exception as e:
            existing.delete()
            raise APIException.error("Erreur lors du calcul du score.",
                                     internal_message=str(e))
Exemplo n.º 5
0
 def post(self):
     try:
         album = playlist.Album.load_from_id_with_songs(
             self.get_argument("id"),
             self.sid,
             self.user,
             sort=self.get_argument("sort"),
         )
         album.load_extra_detail(self.sid,
                                 self.get_argument("all_categories"))
     except MetadataNotFoundError:
         self.return_name = "album_error"
         valid_sids = db.c.fetch_list(
             "SELECT sid FROM r4_album_sid WHERE album_id = %s AND sid != 0 ORDER BY sid",
             (self.get_argument("id"), ),
         )
         if not valid_sids:
             raise APIException("album_is_dj_only")
         elif config.get("default_station") in valid_sids:
             raise APIException(
                 "album_on_other_station",
                 available_station=config.station_id_friendly[config.get(
                     "default_station")],
                 available_sid=valid_sids[0],
             )
         else:
             raise APIException(
                 "album_on_other_station",
                 available_station=config.station_id_friendly[
                     valid_sids[0]],
                 available_sid=valid_sids[0],
             )
     self.append("album", album.to_dict_full(self.user))
Exemplo n.º 6
0
 def post(self):
     if self.user.is_anonymous():
         raise APIException("must_login_and_tune_in_to_request")
     if self.user.add_request(self.sid, self.get_argument("song_id")):
         self.append_standard("request_success")
         self.append("requests", self.user.get_requests(self.sid))
     else:
         raise APIException("request_failed")
Exemplo n.º 7
0
	def prepare(self):
		if self.local_only and not self.request.remote_ip in config.get("api_trusted_ip_addresses"):
			log.info("api", "Rejected %s request from %s, untrusted address." % (self.url, self.request.remote_ip))
			raise APIException("rejected", text="You are not coming from a trusted address.")

		if self.allow_cors:
			self.set_header("Access-Control-Allow-Origin", "*")
			self.set_header("Access-Control-Max-Age", "600")
			self.set_header("Access-Control-Allow-Credentials", "false")

		if not isinstance(self.locale, locale.RainwaveLocale):
			self.locale = self.get_browser_locale()

		self.setup_output()

		if 'in_order' in self.request.arguments:
			self._output = []
			self._output_array = True
		else:
			self._output = {}

		self.sid = fieldtypes.integer(self.get_cookie("r4_sid", None))
		hostname = self.request.headers.get('Host', None)
		if hostname:
			hostname = unicode(hostname).split(":")[0]
			if hostname in config.station_hostnames:
				self.sid = config.station_hostnames[hostname]
		sid_arg = fieldtypes.integer(self.get_argument("sid", None))
		if sid_arg is not None:
			self.sid = sid_arg
		if self.sid is None and self.sid_required:
			raise APIException("missing_station_id", http_code=400)

		self.arg_parse()

		self.sid_check()

		if self.sid:
			self.set_cookie("r4_sid", str(self.sid), expires_days=365, domain=config.get("cookie_domain"))

		if self.phpbb_auth:
			self.do_phpbb_auth()
		else:
			self.rainwave_auth()

		if not self.user and self.auth_required:
			raise APIException("auth_required", http_code=403)
		elif not self.user and not self.auth_required:
			self.user = User(1)
			self.user.ip_address = self.request.remote_ip

		self.user.refresh(self.sid)

		if self.user and config.get("store_prefs"):
			self.user.save_preferences(self.request.remote_ip, self.get_cookie("r4_prefs", None))

		self.permission_checks()
Exemplo n.º 8
0
	def permission_checks(self):
		if (self.login_required or self.admin_required or self.dj_required) and (not self.user or self.user.is_anonymous()):
			raise APIException("login_required", http_code=403)
		if self.tunein_required and (not self.user or not self.user.is_tunedin()):
			raise APIException("tunein_required", http_code=403)
		if self.admin_required and (not self.user or not self.user.is_admin()):
			raise APIException("admin_required", http_code=403)
		if self.perks_required and (not self.user or not self.user.has_perks()):
			raise APIException("perks_required", http_code=403)

		if self.unlocked_listener_only and not self.user:
			raise APIException("auth_required", http_code=403)
		elif self.unlocked_listener_only and self.user.data['lock'] and self.user.data['lock_sid'] != self.sid:
			raise APIException("unlocked_only", station=config.station_id_friendly[self.user.data['lock_sid']], lock_counter=self.user.data['lock_counter'], http_code=403)

		is_dj = False
		if self.dj_required and not self.user:
			raise APIException("dj_required", http_code=403)
		if self.dj_required and not self.user.is_admin():
			potential_djs = cache.get_station(self.sid, "dj_user_ids")
			if not potential_djs or not self.user.id in potential_djs:
				raise APIException("dj_required", http_code=403)
			is_dj = True
			self.user.data['dj'] = True
		elif self.dj_required and self.user.is_admin():
			is_dj = True
			self.user.data['dj'] = True

		if self.dj_preparation and not is_dj and not self.user.is_admin():
			if not db.c.fetch_var("SELECT COUNT(*) FROM r4_schedule WHERE sched_used = 0 AND sched_dj_user_id = %s", (self.user.id,)):
				raise APIException("dj_required", http_code=403)
Exemplo n.º 9
0
	def arg_parse(self):
		for field, field_attribs in self.__class__.fields.iteritems():
			type_cast, required = field_attribs
			parsed = None
			if required and field not in self.request.arguments:
				raise APIException("missing_argument", argument=field, http_code=400)
			elif field in self.request.arguments:
				parsed = type_cast(self.get_argument(field), self)
				if parsed == None and required != None:
					raise APIException("invalid_argument", argument=field, reason="%s %s" % (field, getattr(fieldtypes, "%s_error" % type_cast.__name__)), http_code=400)
			self.cleaned_args[field] = parsed
Exemplo n.º 10
0
	def post(self):
		songs = cache.get_user(self.user.id, "dj_election")
		if not songs:
			raise APIException("no_dj_election", "No songs found queued for a DJ election.")
		if self.get_argument("sched_id", None) and not self.user.is_admin:
			if not self.user.id == db.c.fetch_var("SELECT sched_dj_user_id FROM r4_schedule WHERE sched_id = %s", (self.get_argument("sched_id"),)):
				raise APIException("auth_required", http_code=403)
		elec = events.election.Election.create(self.sid, self.get_argument("sched_id"))
		for song in songs:
			elec.add_song(song)
		cache.set_user(self.user.id, "dj_election", None)
		self.append(self.return_name, { "success": True })
Exemplo n.º 11
0
 def prepare(self):
     if not self.request.headers.get("Referer"):
         raise APIException("auth_failed", "Error reporting cannot be made from an external address. (no referral)")
     refhost = urlsplit(self.request.headers.get("Referer")).hostname
     failed = True
     if refhost in config.station_hostnames:
         failed = False
     elif config.has("accept_error_reports_from_hosts") and refhost in config.get("accept_error_reports_from_hosts"):
         failed = False
     if failed:
         raise APIException("auth_failed", "Error reporting cannot be made from an external address. (%s)" % refhost)
     else:
         return super(ErrorReport, self).prepare()
Exemplo n.º 12
0
	def add_request(self, sid, song_id):
		song = playlist.Song.load_from_id(song_id, sid)
		for requested in db.c.fetch_all("SELECT r4_request_store.song_id, r4_songs.album_id FROM r4_request_store JOIN r4_songs USING (song_id) WHERE r4_request_store.user_id = %s", (self.id,)):
			if song.id == requested['song_id']:
				raise APIException("same_request_exists")
			if not self.has_perks():
				if song.albums[0].id == requested['album_id']:
					raise APIException("same_request_album")
		self._check_too_many_requests()
		updated_rows = db.c.update("INSERT INTO r4_request_store (user_id, song_id, sid) VALUES (%s, %s, %s)", (self.id, song_id, sid))
		if self.data['sid'] == sid and self.is_tunedin():
			self.put_in_request_line(sid)
		return updated_rows
Exemplo n.º 13
0
	def add_request(self, sid, song_id):
		self._check_too_many_requests()
		song = playlist.Song.load_from_id(song_id, sid)
		for requested in self.get_requests(sid):
			if song.id == requested['id']:
				raise APIException("same_request_exists")
			for album in song.albums:
				for requested_album in requested['albums']:
					if album.id == requested_album['id']:
						raise APIException("same_request_album")
		updated_rows = db.c.update("INSERT INTO r4_request_store (user_id, song_id, sid) VALUES (%s, %s, %s)", (self.id, song_id, sid))
		if self.data['sid'] == sid and self.is_tunedin():
			self.put_in_request_line(sid)
		return updated_rows
Exemplo n.º 14
0
 def rate(self, song_id, rating):
     # if not self.user.data['radio_rate_anything']:
     acl = cache.get_station(self.sid, "user_rating_acl")
     if not cache.get_station(self.sid,
                              "sched_current").get_song().id == song_id:
         if not song_id in acl or not self.user.id in acl[song_id]:
             raise APIException("cannot_rate_now")
     elif not self.user.is_tunedin():
         raise APIException("tunein_to_rate_current_song")
     albums = ratinglib.set_song_rating(song_id, self.user.id, rating)
     self.append_standard("rating_submitted",
                          updated_album_ratings=albums,
                          song_id=song_id,
                          rating_user=rating)
Exemplo n.º 15
0
    def get_or_raise(self, *args, **kwargs):
        try:
            return self.get(*args, **kwargs)

        except DoesNotExist:
            raise APIException("Resource not found %s %s" % (args, kwargs),
                               status_code=404)
        except MultipleObjectsReturned:
            raise APIException("Multiple resources found %s %s" %
                               (args, kwargs),
                               status_code=404)
        except ValidationError:
            raise APIException("Invalid values provided %s %s" %
                               (args, kwargs),
                               status_code=400)
Exemplo n.º 16
0
def weather():
    errors = []

    if request.json:
        if 'latitude' not in request.json:
            errors.append(dict(MissingParameterException('latitude')))

        if 'longitude' not in request.json:
            errors.append(dict(MissingParameterException('longitude')))

        if 'time' not in request.json:
            errors.append(dict(MissingParameterException('time')))

        if 'language' not in request.json:
            errors.append(dict(MissingParameterException('language')))

        if errors:
            return jsonify({'errors': errors}), 400

        latitude = request.json['latitude']
        longitude = request.json['longitude']
        time = request.json['time']
        language = request.json['language']
        try:
            res = forecast_get_weather(latitude, longitude, time, language)
            output = {
                "currently": res["currently"],
                "daily": res["daily"]["data"][0],
                "timezone": res["timezone"]
            }
            return jsonify(output), 200
        except InvalidCredentialsException as e:
            return jsonify({'errors': [dict(e)]}), e.status_code
        except ExternalAPIException as e:
            return jsonify({'errors': [dict(e)]}), e.status_code
        except Exception as e:
            logger.error(e)
            return jsonify({
                'errors': [
                    dict(
                        APIException('weather_parse({})'.format(
                            type(e).__name__)))
                ]
            }), 500

    else:
        errors.append(dict(APIException('no_content')))
        return jsonify({'errors': errors}), 400
Exemplo n.º 17
0
def speak():
    errors = []

    if 'text' not in request.json:
        errors.append(dict(MissingParameterException('text')))

    if 'language' not in request.json:
        errors.append(dict(MissingParameterException('language')))

    if errors:
        return jsonify({'errors': errors}), 400

    text = request.json['text']
    language = request.json['language']

    if language not in LANGUAGES_CODE:
        return jsonify({'errors': [dict(BadParameterException('language', valid_values=LANGUAGES_CODE))]}), 400

    try:
        res = ibm_send_request(text, language)
    except (InvalidCredentialsException, ExternalAPIException) as e:
        return jsonify({'errors': [dict(e)]}), e.status_code
    except Exception as e:
        logger.error(e)
        api_e = APIException()
        return jsonify({'errors': [dict(api_e)]}), api_e.status_code

    return Response(res, mimetype="audio/wav", status=200)
Exemplo n.º 18
0
    def prepare(self):
        super(MainIndex, self).prepare()

        if not cache.get_station(self.sid, "sched_current"):
            raise APIException(
                "server_just_started",
                "Rainwave is Rebooting, Please Try Again in a Few Minutes",
                http_code=500)

        # self.json_payload = {}
        self.jsfiles = None

        if not self.user:
            self.user = User(1)
        self.user.ensure_api_key()

        if self.beta or config.get("web_developer_mode") or config.get(
                "developer_mode") or config.get("test_mode"):
            buildtools.bake_beta_css()
            buildtools.bake_beta_templates()
            self.jsfiles = []
            for root, subdirs, files in os.walk(
                    os.path.join(os.path.dirname(__file__),
                                 "../static/%s" % self.js_dir)):  #pylint: disable=W0612
                for f in files:
                    if f.endswith(".js"):
                        self.jsfiles.append(
                            os.path.join(
                                root[root.find("static/%s" % self.js_dir):],
                                f))
Exemplo n.º 19
0
	def post(self):
		if self.get_argument("date_start"):
			self.date_start = time.mktime(self.get_argument("date_start").timetuple())
		else:
			self.date_start = (timestamp() - (7 * 86400) + 1)
		if self.get_argument("date_end"):
			self.date_end = time.mktime(self.get_argument("date_end").timetuple())
		else:
			self.date_end = timestamp()
		if self.date_start >= self.date_end:
			raise APIException("invalid_argument", text="Start date cannot be after end date.")
		timespan = self.date_end - self.date_start
		if timespan <= (86400 * 2):
			sql = "SELECT (lc_time - (lc_time %% 3600)) AS lc_time, ROUND(CAST(AVG(lc_guests) AS NUMERIC), 1) AS lc_listeners FROM r4_listener_counts WHERE lc_time > %s AND lc_time < %s AND sid = %s GROUP BY (lc_time - (lc_time %% 3600)) ORDER BY lc_time"
			dateformat = "%Y-%m-%d %H:00"
		elif timespan <= (86400 * 7):
			sql = "SELECT (lc_time - (lc_time %% (3600 * 6))) AS lc_time, ROUND(CAST(AVG(lc_guests) AS NUMERIC), 1) AS lc_listeners FROM r4_listener_counts WHERE lc_time > %s AND lc_time < %s AND sid = %s GROUP BY (lc_time - (lc_time %% (3600 * 6))) ORDER BY lc_time"
			dateformat = "%Y-%m-%d %H:00"
		elif timespan <= (86400 * 30):
			sql = "SELECT (lc_time - (lc_time %% 86400)) AS lc_time, ROUND(CAST(AVG(lc_guests) AS NUMERIC), 1) AS lc_listeners FROM r4_listener_counts WHERE lc_time > %s AND lc_time < %s AND sid = %s GROUP BY (lc_time - (lc_time %% 86400)) ORDER BY lc_time"
			dateformat = "%Y-%m-%d"
		else:
			sql = "SELECT (lc_time - (lc_time %% (86400 * 7))) AS lc_time, ROUND(CAST(AVG(lc_guests) AS NUMERIC), 1) AS lc_listeners FROM r4_listener_counts WHERE lc_time > %s AND lc_time < %s AND sid = %s GROUP BY (lc_time - (lc_time %% (86400 * 7))) ORDER BY lc_time"
			dateformat = "%Y-%m-%d"
		res = {}
		config.station_ids = (1, 2, 3, 4, 5)
		for sid in config.station_ids:
			res[sid] = db.c.fetch_all(sql, (self.date_start, self.date_end, sid))
			for row in res[sid]:
				dt = datetime.datetime.fromtimestamp(row['lc_time'])
				row['lc_time'] = dt.strftime(dateformat)
		self.append(self.return_name, res)
Exemplo n.º 20
0
	def update(self):
		handler = APIHandler(websocket=True)
		handler.locale = self.locale
		handler.request = FakeRequestObject({}, self.request.cookies)
		handler.sid = self.sid
		handler.user = self.user
		handler.return_name = "sync_result"
		try:
			startclock = timestamp()
			handler.prepare_standalone()

			if not cache.get_station(self.sid, "backend_ok"):
				raise APIException("station_offline")

			self.refresh_user()
			api_requests.info.attach_info_to_request(handler, live_voting=True)
			if self.user.is_dj():
				api_requests.info.attach_dj_info_to_request(handler)
			handler.append("user", self.user.to_private_dict())
			handler.append("api_info", { "exectime": timestamp() - startclock, "time": round(timestamp()) })
		except Exception as e:
			if handler:
				handler.write_error(500, exc_info=sys.exc_info(), no_finish=True)
			log.exception("websocket", "Exception during update.", e)
		finally:
			if handler:
				self.write_message(handler._output) 	#pylint: disable=W0212
Exemplo n.º 21
0
	def update_user(self):
		if not cache.get_station(self.user.request_sid, "backend_ok"):
			raise APIException("station_offline")

		self.user.refresh()
		self.append("user", self.user.to_private_dict())
		self.finish()
Exemplo n.º 22
0
    def post(self):
        if self.request.remote_ip not in config.get("api_trusted_ip_addresses"):
            raise APIException("auth_failed", f"{self.request.remote_ip} is not allowed to access this endpoint.")

        discord_user_id = self.get_argument("discord_user_id")
        nickname = self.get_argument("nickname")

        possible_id = db.c.fetch_var(
            "SELECT user_id FROM phpbb_users WHERE discord_user_id = %s",
            (discord_user_id,),
        )
        if possible_id:
            db.c.update(
                (
                    "UPDATE phpbb_users SET "
                    "  radio_username = %s "
                    "WHERE user_id = %s"
                ),
                (
                    nickname,
                    possible_id,
                ),
            )

        self.append_standard("yes")
Exemplo n.º 23
0
    def prepare(self):
        if self.path_kwargs.get("station"):
            self.sid = config.stream_filename_to_sid.get(
                self.path_kwargs["station"])
            if not self.sid:
                self.redirect(config.get("base_site_url"))
                return

        super(MainIndex, self).prepare()

        if self.path_kwargs.get("station") is None:
            self.redirect("{}{}/".format(
                config.get("base_site_url"),
                config.station_mount_filenames[self.sid],
            ))
            return

        if config.get("enforce_ssl") and self.request.protocol != "https":
            self.redirect("{}{}/".format(
                config.get("base_site_url"),
                config.station_mount_filenames[self.sid],
            ))
            return

        if not config.get("developer_mode"
                          ) and self.request.host != config.get("hostname"):
            self.redirect("{}{}/".format(
                config.get("base_site_url"),
                config.station_mount_filenames[self.sid],
            ))
            return

        if not cache.get_station(self.sid, "sched_current"):
            raise APIException(
                "server_just_started",
                "Rainwave is Rebooting, Please Try Again in a Few Minutes",
                http_code=500,
            )

        self.jsfiles = None

        if not self.user:
            self.user = User(1)
        self.user.ip_address = self.request.remote_ip
        self.user.ensure_api_key()

        if (self.beta or config.get("web_developer_mode")
                or config.get("developer_mode") or config.get("test_mode")):
            buildtools.bake_beta_css()
            buildtools.bake_beta_templates()
            self.jsfiles = []
            for root, _subdirs, files in os.walk(
                    os.path.join(os.path.dirname(__file__),
                                 "../static/%s" % self.js_dir)):
                for f in files:
                    if f.endswith(".js"):
                        self.jsfiles.append(
                            os.path.join(
                                root[root.find("static/%s" % self.js_dir):],
                                f))
Exemplo n.º 24
0
    def post(self):
        object_id = self.get_argument(self._fave_type + "_id")
        fave = self.get_argument("fave")
        result = False

        if self._fave_type == "song_batched":
            result = rating.set_song_fave(self._batched_id, self.user.id, fave)
        elif self._fave_type == "song":
            result = rating.set_song_fave(object_id, self.user.id, fave)
        elif self._fave_type == "album":
            result = rating.set_album_fave(self.sid, object_id, self.user.id,
                                           fave)
        if result:
            text = None
            if fave:
                text = "Favourited " + self._fave_type + "."
            else:
                text = "Unfavourited " + self._fave_type + "."
            self.append_standard("fave_success",
                                 text,
                                 id=object_id,
                                 fave=fave,
                                 sid=self.sid)
        else:
            raise APIException("fave_failed", "Fave failed.")
Exemplo n.º 25
0
    def fetch_file(self, file_id, limit=5, timeout=5, max_pages=MAX_PAGES):
        """
        Fetch a file via a paginated API. We limit the calls to MAX_PAGES pages.
        The method will spawn a gevent green thread for each API call.

        I am not sure if this is the optimal approach, but given the contraints
        I think looking at 1000 records (default MAX_PAGES = 200) concurrently is a good start.
        We can change the no. of records by changing MAX_PAGES environment variable.

        TODO: What can be the maximum number of records I may have to check to find a file?

        The organic way of doing this will be for the file processing service to push a message
        when it completes a file processing. Then we can consume that message and store in DB
        for faster response to the user. This will require an async message queue system like RabbitMQ.
        """
        # local import to avoid installing this package if we are employing another strategy.
        import gevent

        jobs = [gevent.spawn(FetchFilesJob(file_id, self._api, limit, offset, timeout)) for offset in range(0, max_pages + 1)]
        gevent.joinall(jobs)

        if self.is_all_error(jobs):
            raise APIException("Could not fetch the file at the moment.")
        if self.is_file_not_found(jobs):
            raise FileNotFound(f"File {file_id} not found in {max_pages} pages.")

        # I see multiple pages return same file data.
        finished_files = self.get_data(jobs, filter_fn=self.is_finished_filter)
        if len(finished_files) == 0:
            raise FileInvalidStatusError(f"File {file_id} is not in {FileStatus.FINISHED} status.")
        return finished_files[0]
Exemplo n.º 26
0
 def sid_check(self):
     if self.sid is None and not self.sid_required:
         self.sid = config.get("default_station")
     if self.sid == 0 and self.allow_sid_zero:
         pass
     elif not self.sid in config.station_ids:
         raise APIException("invalid_station_id", http_code=400)
Exemplo n.º 27
0
	def add_registered(self, sid):
		real_key = db.c.fetch_var("SELECT radio_listenkey FROM phpbb_users WHERE user_id = %s", (self.user_id,))
		if real_key != self.listen_key:
			raise APIException("invalid_argument", reason="mismatched listen_key.")
		tunedin = db.c.fetch_var("SELECT COUNT(*) FROM r4_listeners WHERE user_id = %s", (self.user_id,))
		if tunedin:
			db.c.update(
				"UPDATE r4_listeners "
				"SET sid = %s, listener_ip = %s, listener_purge = FALSE, listener_icecast_id = %s, listener_relay = %s, listener_agent = %s "
				"WHERE user_id = %s",
				(sid, self.get_argument("ip"), self.get_argument("client"), self.relay, self.agent, self.user_id))
			self.append("%s update: %s %s %s %s %s %s." % ('{:<5}'.format(self.user_id), sid, '{:<15}'.format(self.get_argument("ip")), '{:<15}'.format(self.relay), '{:<10}'.format(self.get_argument("client")), self.agent, self.listen_key))
			self.failed = False
		else:
			db.c.update("INSERT INTO r4_listeners "
				"(sid, user_id, listener_ip, listener_icecast_id, listener_relay, listener_agent) "
				"VALUES (%s, %s, %s, %s, %s, %s)",
				(sid, self.user_id, self.get_argument("ip"), self.get_argument("client"), self.relay, self.agent))
			self.append("%s new   : %s %s %s %s %s %s." % ('{:<5}'.format(self.user_id), sid, '{:<15}'.format(self.get_argument("ip")), '{:<15}'.format(self.relay), '{:<10}'.format(self.get_argument("client")), self.agent, self.listen_key))
			self.failed = False
		if not self.failed:
			u = user.User(self.user_id)
			u.get_listener_record(use_cache=False)
			if u.has_requests():
				u.put_in_request_line(sid)
		sync_to_front.sync_frontend_user_id(self.user_id)
Exemplo n.º 28
0
 def _verify_api_template_creds_json(self, request_data):
     """
     Validate incoming POST request data and create pairs of templates and os_builds
     to import to a specific resource handler.
     """
     logger.info("Confirming Payload for set-template-creds")
     if not isinstance(request_data, list):
         request_data = [
             request_data]
     requested_templates, requested_usernames, requested_passwords, requested_sshkeys = [], [], [], []
     for template in request_data:
         requested_template = template.get('template', None)
         requested_username = template.get('user-name', None)
         requested_password = template.get('password', None)
         requested_sshkey = template.get('ssh-key', None)
         if requested_sshkey == '':
             requested_sshkey = None
         logger.info(requested_sshkey)
         if requested_template in requested_templates:
             raise APIException(_('Bad Request: Duplicate Names'),
                 code=400,
                 details=_("'template' and 'os_build' must be assigned unique values for each entry in POST request"))
         else:
             requested_templates.append(requested_template)
             requested_usernames.append(requested_username)
             requested_passwords.append(requested_password)
             requested_sshkeys.append(requested_sshkey)
     return zip(requested_templates, requested_usernames, requested_passwords, requested_sshkeys)
Exemplo n.º 29
0
 def post(self):
     if self.user.add_favorited_requests(self.sid,
                                         self.get_argument("limit")) > 0:
         self.append_standard("request_favorited_songs_success")
         self.append("requests", self.user.get_requests(self.sid))
     else:
         raise APIException("request_favorited_failed")
Exemplo n.º 30
0
    def post(self):
        if self.request.remote_ip not in config.get("api_trusted_ip_addresses"):
            raise APIException("auth_failed", f"{self.request.remote_ip} is not allowed to access this endpoint.")

        discord_user_id = self.get_argument("discord_user_id")
        avatar = self.get_argument("avatar")
        avatar_url = f"https://cdn.discordapp.com/avatars/{discord_user_id}/{avatar}.png?size=320"
        user_avatar_type = "avatar.driver.remote"

        possible_id = db.c.fetch_var(
            "SELECT user_id FROM phpbb_users WHERE discord_user_id = %s",
            (discord_user_id,),
        )
        if possible_id:
            db.c.update(
                (
                    "UPDATE phpbb_users SET "
                    "  user_avatar_type = %s, "
                    "  user_avatar = %s "
                    "WHERE user_id = %s"
                ),
                (
                    user_avatar_type,
                    avatar_url,
                    possible_id,
                ),
            )

        self.append_standard("yes")