Пример #1
0
 def confirmation(self):
   try:
     if str(self.data["group_id"]) == str(config["API"]["vk"]["group_id"]):
       return str(config["API"]["vk"]["confirm"])
     else:
       raise InvalidUsage('Confirmation is fail', status_code=503)
   except Exception as e:
     raise InvalidUsage('Confirmation error', status_code=410)
Пример #2
0
def contacts_geojson(username):
    if not username:
        raise InvalidUsage("Missing username", status_code=400)

    user = User.query.filter(User.name == username).first()
    if not user:
        raise InvalidUsage("User not found", status_code=404)

    _contacts = Contact.query.filter(User.id == user.id).all()

    if not is_valid_qth(user.locator, 6):
        raise InvalidUsage("QTH is not valid", status_code=400)
    _u = qth_to_coords(user.locator, 6)  # precision, latitude, longitude

    j = [{
        "type": "Feature",
        "properties": {
            "name": user.cutename(),
            "callsign": user.callsign,
            "own": True,
            "icon": "home"
        },
        "geometry": {
            "type": "Point",
            "coordinates": [_u["longitude"], _u["latitude"]]
        },
    }]

    for log in _contacts:
        if log.gridsquare:
            if not is_valid_qth(log.gridsquare, 6):
                raise InvalidUsage("QTH is not valid", status_code=400)
            _f = qth_to_coords(log.gridsquare,
                               6)  # precision, latitude, longitude
        else:
            _f = log.country_grid_coords()
            if not _f:
                continue  # No grid at all ? Skit ip

        f = {
            "type": "Feature",
            "properties": {
                "callsign": log.callsign,
                "distance": log.distance,
                "bearing": log.bearing,
                "bearing_star": log.bearing_star,
                "icon": "qso",
            },
            "geometry": {
                "type": "Point",
                "coordinates": [_f["longitude"], _f["latitude"]]
            },
        }
        j.append(f)

    return Response(json.dumps(j), mimetype="application/json")
Пример #3
0
 def validation(self):
   super().validation()
   try:
     if str(self.data["secret_key"]) != str(config["API"]["vk"]["secret_key"]):
       raise InvalidUsage("Bad vk secret_key", status_code=503)
   except Exception as e:
     if hasattr(e, 'message'):
       raise
     else:
       InvalidUsage("Fail validation: {}".format(e.args[0]))
Пример #4
0
def attach():
    form = NewAttachmentForm()
    if request.method == "POST":
        try:
            if not form.validate() or form.file.name not in request.files:
                raise InvalidUsage("Invalid form data.", 400)
            raw_data = request.files[form.file.name].read()

            try:
                data = json.loads(raw_data)
            except:
                raise InvalidUsage("Invalid JSON file", 400)

            try:
                ureport.validate_attachment(data)
            except Exception as ex:
                raise InvalidUsage("Validation failed: %s" % ex, 400)

            attachment = data

            max_attachment_length = 2048

            if len(str(attachment)) > max_attachment_length:
                err = "uReport attachment may only be {0} bytes long" \
                      .format(max_attachment_length)
                raise InvalidUsage(err, 413)

            fname = str(uuid.uuid4())
            fpath = os.path.join(paths["attachments_incoming"], fname)
            with open(fpath, "w") as file:
                file.write(raw_data)

            if request_wants_json():
                json_response = jsonify({"result": True})
                json_response.status_code = 202
                return json_response
            else:
                flash("The attachment was saved successfully. Thank you.",
                      "success")
                return render_template("reports/attach.html",
                                       form=form), 202

        except InvalidUsage as e:
            if request_wants_json():
                response = jsonify({"error": e.message})
                response.status_code = e.status_code
                return response
            else:
                flash(e.message, "danger")
                return render_template("reports/attach.html",
                                       form=form), e.status_code

    return render_template("reports/attach.html",
                           form=form)
Пример #5
0
def login():
    try:
        args = request.args.to_dict()
        user_data = {}

        if app.config.get('DEV_USER_ID'):
            user_data = {
                'user_id': app.config.get('DEV_USER_ID'),
                'name': 'Dev User',
                'email': '*****@*****.**'
            }
        else:
            code = args.get('code')

            # If the is no code, redirect to the users site to get a code
            if not all([code]):
                next = args.get('next')
                oauthUrl = app.config.get('OAUTH_URL')

                # include the next url if there is one
                if next is not None:
                    oauthUrl += '?next=' + args.get('next')

                return redirect(oauthUrl)

            # We have a code, so use it to get and access token
            params = {
                'code': code,
                'grant_type': 'authorization_code',
                'client_id': app.config.get('OAUTH_CLIENT_ID'),
                'client_secret': app.config.get('OAUTH_CLIENT_SECRET'),
                'redirect_uri': app.config.get('LOGIN_URL'),
                'next': args.get('next')
            }

            response = requests.post(app.config.get('AUTH_SERVER') +
                                     '/oauth/access_token',
                                     data=params)

            access_data = response.json()

            response = requests.get(
                app.config.get('AUTH_SERVER') + '/api/user',
                params={'access_token': access_data['access_token']})

            user_data = response.json()
            user_data['user_id'] = user_data['id']
            user_data['name'] = user_data['name']
            user_data['subscribed'] = (
                'Court Costs' in user_data['services']) or app.config.get(
                    'ALL_SUBSCRIBED', False)

        db.upsert_user(user_data)
        session['user_id'] = user_data['user_id']

        redirect_uri = request.args.get('next', url_for('catch_all'))
        return redirect(redirect_uri)
    except Exception as e:
        print(e)
        raise InvalidUsage('Could not log in', status_code=500, error=e)
Пример #6
0
    def call_type_func(self):
        self.validation()

        if self.type in self.api_types:
            self.current_response = self.api_types[self.type]
            return self.current_response["func"]()
        else:
            raise InvalidUsage("Unknown request type")
Пример #7
0
 def message_new(self):
   # data example: {"type": "group_join", "object": {"text": "xzc", "from_id": 1, "peer_id": 1, "attachments": [], "id": 27, "out": 1, "is_hidden": false, "conversation_message_id": 27, "important": false, "fwd_messages": [], "random_id": 0, "date": 1532054458}, "group_id": 1}
   try:
     self.user_message_object = self.data["object"]
     self.user_message_text = self.user_message_object["text"]
   except Exception as e:
     raise InvalidUsage("Failed parse data message_new")
   else:
     response = self.do_message(self.user_message_text)
     return "ok"
Пример #8
0
def get_dxcc_from_clublog(callsign):
    config = Config.query.first()
    if not config:
        print("!!! Error: config not found")
        add_log(category="CONFIG", level="ERROR", message="Config not found")
        return

    clublog_api_key = config.clublog_api_key
    clublog_uri = "https://secure.clublog.org/dxcc?call={0}&api={1}&full=1".format(
        callsign, clublog_api_key)

    try:
        r = requests.get(clublog_uri)
    except:  # noqa: E722
        raise InvalidUsage("Error getting DXCC from ClubLog", status_code=500)

    if r.status_code != 200:
        raise InvalidUsage("Error getting DXCC from ClubLog",
                           status_code=r.status_code)

    return json.loads(r.content)
Пример #9
0
def waveform_json(username, soundslug):
    user = User.query.filter(User.name == username).first()
    if not user:
        raise InvalidUsage("User not found", status_code=404)
    sound = Sound.query.filter(Sound.slug == soundslug,
                               Sound.user_id == user.id).first()
    if not sound:
        raise InvalidUsage("Sound not found", status_code=404)

    if sound.private:
        if current_user:
            if sound.user_id != current_user.id:
                raise InvalidUsage("Sound not found", status_code=404)
        else:
            raise InvalidUsage("Sound not found", status_code=404)

    si = sound.sound_infos.first()
    if not si:
        return abort(404)
    wf = json.loads(si.waveform)
    wf["filename"] = sound.path_sound()
    wf["wf_png"] = sound.path_waveform()
    wf["title"] = sound.title
    return Response(json.dumps(wf), mimetype="application/json;charset=utf-8")
Пример #10
0
def get_dxcc_from_clublog_or_database(callsign):
    response = {}
    dxcc_database = None
    dxcc_clublog = get_dxcc_from_clublog(callsign)

    if not dxcc_clublog:
        # Trying fallback from database
        q = (DxccPrefixes.query.filter(DxccPrefixes.call == func.substring(
            callsign, 1, func.LENGTH(DxccPrefixes.call))).order_by(
                func.length(DxccPrefixes.call).asc()).limit(1).first())
        if q:
            dxcc_database = {
                "CQZ": int(q.cqz),
                "Continent": q.cont,
                "DXCC": q.adif,
                "Lat": q.lat,
                "Lon": q.long,
                "Name": q.entity,
                "PermKomi": False,
            }

    if not dxcc_clublog and not dxcc_database:
        # We have nothing at all :(
        raise InvalidUsage("Error while getting infos from clublog",
                           status_code=500)

    if dxcc_clublog or dxcc_database:
        response["status"] = "ok"
        if dxcc_clublog:
            response.update(dxcc_clublog)
            response["source"] = "clublog"
        else:
            response.update(dxcc_database)
            response["source"] = "database"

    return response
Пример #11
0
def new():
    form = NewReportForm()
    if request.method == "POST":
        try:
            if not form.validate() or form.file.name not in request.files:
                raise InvalidUsage("Invalid form data.", 400)
            raw_data = request.files[form.file.name].read()
            try:
                data = json.loads(raw_data)
            except Exception as ex:
                _save_invalid_ureport(db, raw_data, str(ex))
                raise InvalidUsage("Couldn't parse JSON data.", 400)

            try:
                ureport.validate(data)
            except Exception as exp:
                reporter = None
                if ("reporter" in data and "name" in data["reporter"]
                        and "version" in data["reporter"]):
                    reporter = "{0} {1}".format(data["reporter"]["name"],
                                                data["reporter"]["version"])

                _save_invalid_ureport(db,
                                      json.dumps(data, indent=2),
                                      str(exp),
                                      reporter=reporter)

                if ("os" in data and "name" in data["os"]
                        and data["os"]["name"] not in systems
                        and data["os"]["name"].lower() not in systems):
                    _save_unknown_opsys(db, data["os"])

                raise InvalidUsage("uReport data is invalid.", 400)

            report = data

            max_ureport_length = InvalidUReport.__lobs__["ureport"]

            if len(str(report)) > max_ureport_length:
                raise InvalidUsage(
                    "uReport may only be {0} bytes long".format(
                        max_ureport_length), 413)

            osr_id = None
            osr = None
            if report["os"]["name"] in systems:
                osr = (db.session.query(OpSysRelease).join(OpSys).filter(
                    OpSys.name == systems[report["os"]["name"]].nice_name
                ).filter(
                    OpSysRelease.version == report["os"]["version"]).first())

                if osr:
                    osr_id = osr.id
            try:
                dbreport = ureport.is_known(report,
                                            db,
                                            return_report=True,
                                            opsysrelease_id=osr_id)
            except Exception as e:
                logging.exception(e)
                dbreport = None

            known = bool(dbreport)
            fname = str(uuid.uuid4())
            fpath = os.path.join(paths["reports_incoming"], fname)
            with open(fpath, 'w') as file:
                file.write(raw_data)

            if request_wants_json():
                response = {'result': known}

                try:
                    report2 = ureport2(report)
                except FafError:
                    report2 = None

                if report2 is not None:
                    solution = find_solution(report2, db=db, osr=osr)
                    if solution is not None:
                        response["message"] = (
                            "Your problem seems to be caused by {0}\n\n"
                            "{1}".format(solution.cause, solution.note_text))

                        if solution.url:
                            response["message"] += (
                                "\n\nYou can get more information at {0}".
                                format(solution.url))

                        solution_dict = {
                            "cause": solution.cause,
                            "note": solution.note_text,
                            "url": solution.url
                        }
                        if not solution_dict["url"]:
                            del solution_dict["url"]
                        response["solutions"] = [solution_dict]
                        response["result"] = True

                    try:
                        problemplugin = problemtypes[report2["problem"]
                                                     ["type"]]
                        response["bthash"] = problemplugin.hash_ureport(
                            report2["problem"])
                    except Exception as e:
                        logging.exception(e)
                        pass

                if known:
                    url = url_for('reports.item',
                                  report_id=dbreport.id,
                                  _external=True)
                    parts = [{
                        "reporter": "ABRT Server",
                        "value": url,
                        "type": "url"
                    }]

                    bugs = (db.session.query(BzBug).join(ReportBz).filter(
                        ReportBz.bzbug_id == BzBug.id).filter(
                            ReportBz.report_id == dbreport.id).all())
                    for bug in bugs:
                        parts.append({
                            "reporter": "Bugzilla",
                            "value": bug.url,
                            "type": "url"
                        })

                    if 'message' not in response:
                        response['message'] = ''
                    else:
                        response['message'] += '\n\n'

                    response['message'] += "\n".join(
                        p["value"] for p in parts
                        if p["type"].lower() == "url")
                    response['reported_to'] = parts

                json_response = jsonify(response)
                json_response.status_code = 202
                return json_response
            else:
                flash("The uReport was saved successfully. Thank you.",
                      "success")
                return render_template("reports/new.html", form=form), 202

        except InvalidUsage as e:
            if request_wants_json():
                response = jsonify({"error": e.message})
                response.status_code = e.status_code
                return response
            else:
                flash(e.message, "danger")
                return render_template("reports/new.html",
                                       form=form), e.status_code

    return render_template("reports/new.html", form=form)
Пример #12
0
def new(url_fname=None):
    """
    Handle dump dir archive uploads
    """

    form = NewDumpDirForm()
    if request.method in ["POST", "PUT"]:
        try:
            if request.method == "POST":
                if not form.validate() or form.file.name not in request.files:
                    raise InvalidUsage("Invalid form data.", 400)

                archive_file = request.files[form.file.name]
                archive_fname = archive_file.filename

            if request.method == "PUT":
                archive_file = StringIO(request.stream.read())
                archive_fname = url_fname

            archive_file.seek(0, os.SEEK_END)
            archive_size = archive_file.tell()
            archive_file.seek(0)

            if not archive_size:
                raise InvalidUsage("Empty archive received", 400)

            if not check_filename(archive_fname):
                raise InvalidUsage("Wrong archive file name", 400)

            # sanitize input filename just to be sure
            archive_fname = secure_filename(archive_fname)

            if not os.path.exists(paths["dumpdir"]):
                raise InvalidUsage("That's embarrassing! We have some troubles"
                                   " with deployment. Please try again later.",
                                   500)

            count = 0
            try:
                count = sum(
                    1 for x in os.listdir(paths["dumpdir"])
                    if os.path.isfile(os.path.join(paths["dumpdir"], x)))

            except Exception as e:
                raise InvalidUsage("That's embarrassing! We have some troubles"
                                   " with storage. Please try again later.",
                                   500)

            if count >= int(config["dumpdir.cachedirectorycountquota"]):
                raise InvalidUsage("That's embarrassing! We have reached"
                                   " the limit of uploaded archives."
                                   " Please try again later.",
                                   500)

            if archive_size > int(config["dumpdir.maxdumpdirsize"]):
                raise InvalidUsage("Dump dir archive is too large", 413)

            used_space = 0.0
            try:
                used_space = sum(
                    float(os.path.getsize(x))
                    for x in map(lambda f: os.path.join(paths["dumpdir"], f),
                                 os.listdir(paths["dumpdir"]))
                    if os.path.isfile(x))
            except Exception as e:
                raise InvalidUsage("That's embarrasing! We have some"
                                   " troubles with disk space."
                                   " Please try again later.",
                                   500)

            quota = int(config["dumpdir.cachedirectorysizequota"])
            if (quota - archive_size) < used_space:
                raise InvalidUsage("That's embarrassing! We ran out"
                                   " of disk space."
                                   " Please try again later.",
                                   500)

            fpath = os.path.join(paths["dumpdir"], archive_fname)

            if os.path.exists(fpath):
                raise InvalidUsage("Dump dir archive already exists.", 409)

            with open(fpath, 'w') as dest:
                dest.write(archive_file.read())

            if request_wants_json():
                response = jsonify({"ok": "ok"})
                response.status_code = 201
                return response
            else:
                flash("Uploaded successfully.")
                return render_template("dumpdirs/new.html",
                                       form=form)

        except InvalidUsage as e:
            if e.status_code == 500:
                logger.error(e.message)
            elif e.status_code >= 400:
                logger.warning(e.message)

            if request_wants_json():
                response = jsonify({"error": e.message})
                response.status_code = e.status_code
                return response
            else:
                flash(e.message, "danger")
                return render_template("dumpdirs/new.html",
                                       form=form), e.status_code

    return render_template("dumpdirs/new.html",
                           form=form)
Пример #13
0
def adif_export_dl(username, logbook_slug):
    """ http://hamclubs.info/adif-validator/ """
    user = User.query.filter(User.name == username).first()
    if not user:
        raise InvalidUsage("User not found", 404)

    logbook = Logbook.query.filter(Logbook.user_id == user.id,
                                   Logbook.slug == logbook_slug).first()
    if not logbook or (current_user.id != user.id):
        raise InvalidUsage("Logbook not found", 404)

    logs = logbook.logs

    def a(k, v):
        v = str(v)
        return "<{0}:{1}>{2} ".format(k, len(v), v)

    def ab(k, t, v):
        v = str(v)
        return "<{0}:{1}:{2}>{3} ".format(k, len(v), t, v)

    def generate():
        yield "ADIF Export by AHRL\r\n"
        yield "\r\n"
        yield "<adif_ver:5>3.0.4\r\n"
        yield "<programid:4>AHRL\r\n"
        vers = "{0} git {1}".format(g.cfg["AHRL_VERSION_VER"],
                                    g.cfg["AHRL_VERSION_GIT"])
        yield a("programversion", vers) + "\r\n"
        ct = datetime.datetime.utcnow().strftime("%Y%m%d %H%M%S")
        yield a("created_timestamp", ct) + "\r\n"

        yield ab("app_ahrl_station_callsign", "S", user.callsign) + "\r\n"
        yield ab("app_ahrl_operator", "S", user.callsign) + "\r\n"
        yield ab("app_ahrl_logbook", "I", logbook.name) + "\r\n"
        yield ab("app_ahrl_logbook_swl", "B",
                 "Y" if logbook.swl else "N") + "\r\n"
        yield ab("app_ahrl_logbook_private", "B",
                 "N" if logbook.public else "Y") + "\r\n"

        yield "\r\n"
        yield "<eoh>\r\n\r\n"

        for log in logs:
            counter = 0
            for key in ADIF_FIELDS:
                if counter == 4:
                    counter = 0
                    yield "\r\n"

                value = getattr(log, key)
                if value:
                    if key == "swl" or key == "force_init":
                        if value == 1:
                            val = "Y"
                        elif value == 2:
                            val = "N"
                        else:
                            val = "Y"
                    elif key == "lat":
                        val = coordinates2adif(value, "Latitude")
                    elif key == "lon":
                        val = coordinates2adif(value, "Longitude")
                    elif key == "notes":
                        val = "".join([
                            i if (126 >= ord(i) >= 32) or (i == "\r") or
                            (i == "\n") else " " for i in value
                        ])
                    elif key == "iota":
                        if len(value) == 5:
                            val = "{0}-{1}".format(value[0:2], value[2:5])
                        else:
                            val = value
                    else:
                        val = value
                    yield a(key, val)
                    counter += 1

            yield "\r\n"
            # Manual ones
            if log.freq:
                yield a("freq", log.freq / 1000000.0)
            if log.freq_rx:
                yield a("freq", log.freq_rx / 1000000.0)
            if log.mode:
                yield a("mode", log.mode.mode)
            if log.time_on:
                yield a("qso_date", log.time_on.strftime("%Y%m%d"))
                yield a("time_on", log.time_on.strftime("%H%M%S"))
            if log.time_off:
                yield a("time_off", log.time_off.strftime("%H%M%S"))
            if log.klass:
                yield a("class", log.klass)
            if log.band:
                yield a("band", log.band.name)
            if log.comment:
                yield a("comment_intl", log.comment)
            yield "\r\n<eor>\r\n\r\n"

    return Response(
        stream_with_context(generate()),
        mimetype="text/plain",
        headers={
            "Content-Disposition":
            "attachment;filename=qsos-{0}.adi".format(user.name)
        },
    )