def withParams(func):
    '''
        @param func function(
            'study'= db.Studies,
            'languages'= [db.Languages],
            'words'= [db.Words])
            -> flask response
        @return flask response
    '''
    params = ['study', 'languages', 'words']
    for p in params:
        if p not in flask.request.args:
            return 'GET parameters should be: ' + str(params)
    fetched = {}
    for p in params:
        try:
            val = flask.request.args[p]
            if p == 'study':
                fetched[p] = db.getSession().query(db.Studies).filter_by(Name=val).limit(1).one()
            else:
                val = val.split(',')
                if p == 'languages':
                    langs = []
                    for lIx in val:
                        langs.append(db.getSession().query(db.Languages).filter_by(LanguageIx=lIx).limit(1).one())
                    fetched[p] = langs
                elif p == 'words':
                    words = []
                    for wId in val:
                        where = sqlalchemy.func.concat(db.Words.IxElicitation, db.Words.IxMorphologicalInstance).like(wId)
                        words.append(db.getSession().query(db.Words).filter(where).limit(1).one())
                    fetched[p] = words
        except:
            return 'Could not fetch data for parameter: ' + p
    return func(**fetched)
Exemple #2
0
def getData():
    # Checking if global portion of data is requested:
    if 'global' in flask.request.args:
        return getGlobal()
    # Checking if study depandant portion of data is requested:
    if 'study' in flask.request.args:
        studyName = flask.request.args['study']
        if studyName == '':
            return 'You need to supply a value for that study parameter!'
        else:
            studyCount = db.getSession().query(db.Studies).filter_by(Name = studyName).limit(1).count()
            if studyCount == 1:
                return getStudy(studyName)
            else:
                return ("Couldn't find study: "+studyName)
    # Normal response in case of no get parameters:
    try:
        latest = db.getSession().query(db.EditImports).order_by(db.EditImports.Time.desc()).limit(1).one()
        dict = {
            'lastUpdate': latest.getTimeStampString(),
            'Description': 'Add a global parameter to fetch global data, and add a study parameter to fetch a study.'
        }
        return flask.jsonify(**dict)
    except sqlalchemy.orm.exc.NoResultFound:
        return flask.jsonify(**{})
def buildCSV():
    '''
        Build after the preimage of php/export/csv.php
        Expected GET parameters are:
        * study, containing the name of a study
        * languages, containing ',' delimited languageIds
        * words, containing ',' delimited wordIds
        Example route:
        export/csv?study=Slavic&languages=13111210507&words=10,20,30
    '''
    args = flask.request.args
    # Checking parameters:
    params = ['study', 'languages', 'words']
    for p in params:
        if p not in args:
            msg = "Missing parameter: '%s'! Parameters should be: %s" % (p, params)
            return msg, 400
    # Querying languages:
    lIds = {int(id) for id in args['languages'].split(',')}
    languages = db.getSession().query(db.Languages).filter_by(StudyName=args['study']).filter(db.Languages.LanguageIx.in_(lIds)).all()
    # Querying words:
    wIds = {int(id) for id in args['words'].split(',')}
    words = db.getSession().query(db.Words).filter_by(StudyName=args['study']).all()
    words = [w for w in words if int(str(w.IxElicitation) + str(w.IxMorphologicalInstance)) in wIds]

    def quote(x):  # Compossing csv:
        return '"' + x + '"'
    head = ['LanguageId', 'LanguageName', 'Latitude', 'Longitude',
            'WordId', 'WordModernName1', 'WordModernName2', 'WordProtoName1', 'WordProtoName2',
            'Phonetic', 'SpellingAltv1', 'SpellingAltv2', 'NotCognateWithMainWordInThisFamily']
    csv = [[quote(h) for h in head]]
    for l in languages:
        lPart = [str(l.LanguageIx), quote(l.ShortName), str(l.Latitude or ''), str(l.Longtitude or '')]
        for w in words:
            wPart = [str(w.IxElicitation) + str(w.IxMorphologicalInstance),
                     quote(w.FullRfcModernLg01), quote(w.FullRfcModernLg02),
                     quote(w.FullRfcProtoLg01), quote(w.FullRfcProtoLg02)]
            transcriptions = [t for t in w.Transcriptions if t.LanguageIx in lIds]
            for t in transcriptions:
                tPart = [quote(t.Phonetic), quote(t.SpellingAltv1), quote(t.SpellingAltv2), str(t.NotCognateWithMainWordInThisFamily)]
                csv.append(lPart + wPart + tPart)
    # Transform csv to string:
    csv = "\n".join([','.join(line) for line in csv])
    # filename to use:
    filename = 'Customexport_%s.csv' % datetime.datetime.utcnow().isoformat()
    # Build and return response:
    response = flask.make_response(csv)
    response.headers["Pragma"] = "public"
    response.headers["Expires"] = "0"
    response.headers["Cache-Control"] = "must-revalidate, post-check=0, pre-check=0"
    response.headers["Content-Type"] = "text/csv; charset=utf-8"
    response.headers["Content-Disposition"] = ('attachment;filename="%s"' % filename)
    response.headers["Content-Transfer-Encoding"] = "binary"
    return response
Exemple #4
0
 def _insert():
     for i in xrange(1, len(s['str'])+1):
         prefix = s['str'][:i]
         # Find first non inserted prefix:
         try:
             exists = db.getSession().query(db.ShortLinks).filter_by(Name = prefix).limit(1).one()
             continue
         except:
             entry = db.ShortLinks(Hash = s['hex'], Name = prefix, Target = s['url'])
             db.getSession().add(entry)
             db.getSession().commit()
             print 'Inserted!'
             return toShortUrlDict(entry)
Exemple #5
0
def initModels():
    """Initialize timebot DB tables and mappers"""
    engine = db.getEngine()
    meta = db.getMeta()
    session = db.getSession()

    tb_user = Table(
            'tb_user', meta,
            Column('id', Integer, primary_key=True, autoincrement=True),
            Column('company_id', None, ForeignKey('tb_company.id'), nullable=True),
            Column('jid', Unicode(50), unique=True, nullable=False),
            Column('name', Unicode(50)),
            Column('rate', Integer))

    tb_worktime = Table(
            'tb_time', meta,
            Column('id', Integer, primary_key=True),
            Column('user_id', None, ForeignKey('tb_user.id'), nullable=False),
            Column('start', DateTime, default=datetime.now),
            Column('stop', DateTime, nullable=True))

    tb_company = Table(
            'tb_company', meta,
            Column('id', Integer, primary_key=True),
            Column('name', Unicode(50), nullable=True))

    meta.create_all()

    mapper(TUser, tb_user, properties=dict(
            worktime=relation(TWorktime),
            company=relation(TCompany)))
    mapper(TWorktime, tb_worktime, properties=dict(
            user=relation(TUser)))
    mapper(TCompany, tb_company, properties=dict(
            users=relation(TUser)))
Exemple #6
0
def insert(url):
    # Transform a ShortLinks instance to a dict like it's returned by shorten:
    def toShortUrlDict(shortLink):
        return {
            'url': shortLink.Target,
            'hex': shortLink.Hash,
            'str': shortLink.Name
        }
    # Shortened data:
    s = shorten(url)
    # Helper to find prefix:
    def _insert():
        for i in xrange(1, len(s['str'])+1):
            prefix = s['str'][:i]
            # Find first non inserted prefix:
            try:
                exists = db.getSession().query(db.ShortLinks).filter_by(Name = prefix).limit(1).one()
                continue
            except:
                entry = db.ShortLinks(Hash = s['hex'], Name = prefix, Target = s['url'])
                db.getSession().add(entry)
                db.getSession().commit()
                print 'Inserted!'
                return toShortUrlDict(entry)
    # Return existing entry rather than creating a new one:
    try:
        exists = db.getSession().query(db.ShortLinks).filter_by(Hash = s['hex']).limit(1).one()
        return toShortUrlDict(exists)
    except:
        return _insert()
def dictAll(model):
    '''
        @param model (db.Model, SndCompModel)
        @return [{}] A list of Dicts
        Fetch all models and make them a list of ditcs.
    '''
    return [m.toDict() for m in db.getSession().query(model).all()]
Exemple #8
0
    def testAuth(self):

        sanicRequests.newSession()
        dSession = getSession()
        username = "******"
        password = "******"
        userData = {
            "username": username,
            "password": password,
            "email": "*****@*****.**",
            "isStaff": True,
            "isActive": True,
            "verified": True
        }

        deleteUser(username, dSession=dSession)
        token = sanicRequests.get("api/forms/token").json()
        userData.update(token)
        sanicRequests.post("api/auth/createUser", data=userData)

        login = {"ident": "testUser", "password": "******"}
        login.update(token)
        response = sanicRequests.post("api/auth/login", data=login)
        print("logged in", response.cookies.get("authenticated"))
        print("response", response.json())
def getSummary():
    tMap = {}#TranslationId -> Page_Translations.toDict()
    ts = db.getSession().query(db.Page_Translations).filter(
            sqlalchemy.or_(
            db.Page_Translations.Active == 1,
            db.Page_Translations.TranslationId == 1)
        ).all()
    for t in ts:
        tMap[str(t.TranslationId)] = t.toDict()
    return flask.jsonify(**tMap)
Exemple #10
0
def getGlobal():
    # Structure to fill up:
    data = {
        'studies': [s.Name for s in db.getSession().query(db.Studies).all()]
    ,   'global': {
            'soundPath': 'static/sound'
        ,   'shortLinks': {l.Name: l.Target for l in db.getSession().query(db.ShortLinks).all()}
        ,   'contributors': dictAll(db.Contributors)
        ,   'contributorCategories': dictAll(db.ContributorCategories)
        ,   'flagTooltip': dictAll(db.FlagTooltip)
        ,   'languageStatusTypes': dictAll(db.LanguageStatusTypes)
        ,   'meaningGroups': dictAll(db.MeaningGroups)
        ,   'transcrSuperscriptInfo': dictAll(db.TranscrSuperscriptInfo)
        ,   'transcrSuperscriptLenderLgs': dictAll(db.TranscrSuperscriptLenderLgs)
        ,   'wikipediaLinks': dictAll(db.WikipediaLinks)
        }
    }
    # Return stuff encoded as JSON:
    return flask.jsonify(**data)
Exemple #11
0
def upsertCorporation(eve, corporationID, session=None):
    try:
        if session == None:
            session = getSession()
            commitOnEnd = True
        else:
            commitOnEnd = False

        # Check if we already have the corp in the database
        query = session.query(Corporation).filter(
            Corporation.corporationID == corporationID)
        if query.count() > 0:
            dbCorp = query[0]
            # Don't update if it's been done within the last 6hrs
            if (dbCorp.lastUpdated +
                    datetime.timedelta(0, 21600)) > datetime.datetime.now():
                return True
        else:
            # Create the Corporation object
            dbCorp = Corporation()
            dbCorp.corporationID = corporationID

        # Call the XMLAPI
        corpSheet = eve.corp.CorporationSheet(corporationID=corporationID)

        # Update the object
        dbCorp.corporationName = corpSheet.corporationName
        dbCorp.ticker = corpSheet.ticker
        dbCorp.taxRate = corpSheet.taxRate
        dbCorp.memberCount = corpSheet.memberCount
        dbCorp.lastUpdated = datetime.datetime.now()
        if corpSheet.allianceID == 0:
            dbCorp.allianceID = None
        else:
            # Upsert the alliance
            if not upsertAlliance(eve=eve, allianceID=corpSheet.allianceID):
                apiLog(
                    "An error occurred upserting allianceID=%d, so we'll rollback and try later"
                    % corpSheet.allianceID)
                session.rollback()
                return False
            dbCorp.allianceID = corpSheet.allianceID

        # Commit the changes
        session.add(dbCorp)
        if commitOnEnd == True:
            session.commit()
        return True

    except Exception as e:
        apiLog(
            "Exception occurred doing public corp update on corporationID=%d: %s"
            % (corporationID, str(e)))
        session.rollback()
        return False
def getSummary():
    '''
        @return flask reply
        Provides a JSON encoded summary of available translations to the client.
    '''
    tMap = {}  # TranslationId -> Page_Translations.toDict()
    ts = db.getSession().query(db.Page_Translations).filter(sqlalchemy.or_(
        db.Page_Translations.Active == 1, db.Page_Translations.TranslationId == 1)).all()
    for t in ts:
        tMap[str(t.TranslationId)] = t.toDict()
    return flask.jsonify(**tMap)
Exemple #13
0
def addApi(user, keyID, vCode, name, session=getSession()):
    try:
        if session.query(Api).filter(Api.keyID == keyID, Api.vCode==vCode).count() > 0:
            return "This API Key is already in the database"

        # We NEED APIKeyInfo, AccountStatus, CharacterSheet and AssetList
        eveapi.set_user_agent("eveapi.py/1.3")
        eve = eveapi.EVEAPIConnection()
        try:
            keyInfo = eve.account.APIKeyInfo(keyID=keyID, vCode=vCode)
            if keyInfo.key.type == "Corporation":
                return "This is a corp API, it's need to be a Character or Account API"
        except eveapi.Error as e:
            return "This API key is invalid or expired"
        try:
            accStatus = eve.account.AccountStatus(keyID=keyID, vCode=vCode)
            apiChar = eve.char.CharacterSheet(keyID=keyID, vCode=vCode, characterID=keyInfo.key.characters[0].characterID)
            assetList = eve.char.AssetList(keyID=keyID, vCode=vCode, characterID=keyInfo.key.characters[0].characterID, flat=1)
            charInfo = eve.eve.CharacterInfo(keyID=keyID, vCode=vCode, characterID=keyInfo.key.characters[0].characterID)

        except eveapi.Error as e:
            return "Your API key doesn't have enough permissions, at minimum it needs to be an active key with AccountStatus and CharacterInfo"

        # Build the key object
        api = Api()
        api.userId = user.id
        api.keyID = keyID
        api.vCode = vCode
        api.accessMask = keyInfo.key.accessMask
        api.type = keyInfo.key.type
        api.paidUntil = datetime.datetime.fromtimestamp(accStatus.paidUntil)
        api.createDate = datetime.datetime.fromtimestamp(accStatus.createDate)
        api.logonCount = accStatus.logonCount
        api.logonMinutes = accStatus.logonMinutes
        api.name = name
        api.lastUpdated = datetime.datetime.now()
        api.added = datetime.datetime.now()

        session.add(api)
        session.commit()

        # Now update the api key
        updateApiKey(session=session, api=api)

        return api

    except eveapi.Error as e:
        session.rollback()
        return "An error occurred on the EVE API, it's probably not your fault, try again later"
    except Exception as e:
        session.rollback()
        return "An error occurred querying this key: %s" % str(e)
def getI18n(lngs):
    i18n = defaultdict(dict)
    for l in lngs:
        try:
            translation = db.getSession().query(db.Page_Translations).filter_by(BrowserMatch = l).limit(1).one()
            tDict = {}
            for s in translation.Page_StaticTranslation:
                tDict[s.Req] = s.Trans
            for d in translation.Page_DynamicTranslation:
                tDict[d.Category+d.Field] = d.Trans
            i18n[l]['translation'] = tDict
        except sqlalchemy.orm.exc.NoResultFound:
            pass
    return flask.jsonify(**i18n)
def chkTranslationId(func):
    if 'translationId' in flask.request.args:
        tId = flask.request.args['translationId']
        try:
            t = db.getSession().query(db.Page_Translations).filter_by(TranslationId = tId).limit(1).one()
            return func(t)
        except sqlalchemy.orm.exc.NoResultFound:
            return flask.jsonify(**{
                'msg': 'Specified translationId not found in database: '+tId
            })
    action = flask.request.args['action']
    return flask.jsonify(**{
        'msg': 'You need to specify a translationId for action='+action+'.'
        })
Exemple #16
0
def upsertCorporation(eve, corporationID, session=None):
    try:
        if session == None:
            session = getSession()
            commitOnEnd = True
        else:
            commitOnEnd = False

        # Check if we already have the corp in the database
        query = session.query(Corporation).filter(Corporation.corporationID == corporationID)
        if query.count() > 0:
            dbCorp = query[0]
            # Don't update if it's been done within the last 6hrs
            if (dbCorp.lastUpdated + datetime.timedelta(0, 21600)) > datetime.datetime.now():
                return True
        else:
            # Create the Corporation object
            dbCorp = Corporation()
            dbCorp.corporationID = corporationID

        # Call the XMLAPI
        corpSheet = eve.corp.CorporationSheet(corporationID=corporationID)

        # Update the object
        dbCorp.corporationName = corpSheet.corporationName
        dbCorp.ticker = corpSheet.ticker
        dbCorp.taxRate = corpSheet.taxRate
        dbCorp.memberCount = corpSheet.memberCount
        dbCorp.lastUpdated = datetime.datetime.now()
        if corpSheet.allianceID == 0:
            dbCorp.allianceID = None
        else:
            # Upsert the alliance
            if not upsertAlliance(eve=eve, allianceID=corpSheet.allianceID):
                apiLog("An error occurred upserting allianceID=%d, so we'll rollback and try later" % corpSheet.allianceID)
                session.rollback()
                return False
            dbCorp.allianceID = corpSheet.allianceID

        # Commit the changes
        session.add(dbCorp)
        if commitOnEnd == True:
            session.commit()
        return True

    except Exception as e:
        apiLog("Exception occurred doing public corp update on corporationID=%d: %s" % (corporationID, str(e)))
        session.rollback()
        return False
Exemple #17
0
def supercheck():
	session = getSession()
	supers = []

	#for x in session.query(Asset, InvType, Character, Corporation).join(InvType).join(Character).join(Corporation).filter(InvType.groupID.in_((659, 30))).order_by(InvType.groupID, InvType.typeID, Character.lastKnownLocation).all():
	for x in session.query(Asset, InvType, Character, Corporation).join(InvType).join(InvGroup).join(Character).join(Corporation).filter(InvGroup.categoryID == 6).filter(Asset.singleton == 1).order_by(InvType.groupID, InvType.typeID, Character.lastKnownLocation).all():
		sup = {}
		sup['ship'] = x.Asset
		sup['type'] = x.InvType
		sup['char'] = x.Character
		sup['corp'] = x.Corporation

		supers.append(sup)

	return render_template("viewship.html", config=config.auth, supers=supers)
Exemple #18
0
def upsertAlliance(eve, allianceID, session=None):
    try:
        if session == None:
            session = getSession()
            commitOnEnd = True
        else:
            commitOnEnd = False

        # Check if we already have the alliance in the database
        query = session.query(Alliance).filter(
            Alliance.allianceID == allianceID)
        if query.count() > 0:
            dbAlliance = query[0]
            # Don't update if it's been done within the last 6hrs
            if (dbAlliance.lastUpdated +
                    datetime.timedelta(0, 21600)) > datetime.datetime.now():
                return True
        else:
            # Create the Alliance object
            dbAlliance = Alliance()
            dbAlliance.allianceID = allianceID

        # Call the XMLAPI
        allianceList = eve.eve.AllianceList(version=1)
        indAllianceList = allianceList.alliances.IndexedBy("allianceID")
        apiAlliance = indAllianceList.Get(allianceID)

        # Update the object
        dbAlliance.allianceName = apiAlliance.name
        dbAlliance.ticker = apiAlliance.shortName
        dbAlliance.memberCount = apiAlliance.memberCount
        dbAlliance.startDate = datetime.datetime.fromtimestamp(
            apiAlliance.startDate)
        dbAlliance.lastUpdated = datetime.datetime.now()

        # Commit the changes
        session.add(dbAlliance)
        if commitOnEnd == True:
            session.commit()
        return True

    except Exception as e:
        apiLog(
            "Exception occurred doing public alliance update on allianceID=%d: %s"
            % (allianceID, str(e)))
        session.rollback()
        return False
def getStudy(studyName):
    '''
        @param studyName String
        @throws sqlalchemy.orm.exc.NoResultFound if studyName not found.
        Replies with a JSON encoded, study dependant chunk of the database.
    '''
    # Study to fetch stuff for:
    study = db.getSession().query(db.Studies).filter_by(Name=studyName).limit(1).one()

    def filterDicts(xs):  # Helper to remove StudyName from dicts
        ys = []
        for x in xs:
            d = x.toDict()
            d.pop('StudyName', None)
            ys.append(d)
        return ys
    # Structure to fill up:
    data = {
        'study': study.toDict(),
        'families': dictAll(db.Families),
        'regions': filterDicts(study.Regions),
        'regionLanguages': filterDicts(study.RegionLanguages),
        'languages': filterDicts(study.Languages),
        'words': filterDicts(study.Words),
        'meaningGroupMembers': [m.toDict() for m in study.MeaningGroupMembers],
        'transcriptions': filterDicts(study.Transcriptions),
        'defaults': {
            'language': None,
            'word': None,
            'languages': [{'LanguageIx': l.LanguageIx} for l in study.DefaultMultipleLanguages],
            'words': [{'IxElicitation': w.IxElicitation, 'IxMorphologicalInstance': w.IxMorphologicalInstance} for w in study.DefaultMultipleWords],
            'excludeMap': [{'LanguageIx': l.LanguageIx} for l in study.DefaultLanguagesExcludeMap]}}
    # Single defaults:
    if len(study.DefaultLanguages) > 0:
        l = study.DefaultLanguages[0]
        data['defaults']['language'] = {'LanguageIx': l.LanguageIx}
    if len(study.DefaultWords) > 0:
        w = study.DefaultWords[0]
        data['defaults']['word'] = {'IxElicitation': w.IxElicitation, 'IxMorphologicalInstance': w.IxMorphologicalInstance}
    # Handling dummies:
    dummies = db.getDummyTranscriptions(study.Name)
    if len(dummies):
        data['transcriptions'] += dummies
    # Return stuff encoded as JSON:
    return flask.jsonify(**data)
def getI18n(lngs):
    '''
        @param lngs [String]
        @return flask reply
        Returns the JSON encoded data for translation that can be consumed by i18n client side.
    '''
    i18n = defaultdict(dict)
    for l in lngs:
        try:
            translation = db.getSession().query(db.Page_Translations).filter_by(BrowserMatch=l).limit(1).one()
            tDict = {}
            for s in translation.Page_StaticTranslation:
                tDict[s.Req] = s.Trans
            for d in translation.Page_DynamicTranslation:
                tDict[d.Category + d.Field] = d.Trans
            i18n[l]['translation'] = tDict
        except sqlalchemy.orm.exc.NoResultFound:
            pass
    return flask.jsonify(**i18n)
Exemple #21
0
def upsertAlliance(eve, allianceID, session=None):
    try:
        if session == None:
            session = getSession()
            commitOnEnd = True
        else:
            commitOnEnd = False

        # Check if we already have the alliance in the database
        query = session.query(Alliance).filter(Alliance.allianceID == allianceID)
        if query.count() > 0:
            dbAlliance = query[0]
            # Don't update if it's been done within the last 6hrs
            if (dbAlliance.lastUpdated + datetime.timedelta(0, 21600)) > datetime.datetime.now():
                return True
        else:
            # Create the Alliance object
            dbAlliance = Alliance()
            dbAlliance.allianceID = allianceID

        # Call the XMLAPI
        allianceList = eve.eve.AllianceList(version=1)
        indAllianceList = allianceList.alliances.IndexedBy("allianceID")
        apiAlliance = indAllianceList.Get(allianceID)

        # Update the object
        dbAlliance.allianceName = apiAlliance.name
        dbAlliance.ticker = apiAlliance.shortName
        dbAlliance.memberCount = apiAlliance.memberCount
        dbAlliance.startDate = datetime.datetime.fromtimestamp(apiAlliance.startDate)
        dbAlliance.lastUpdated = datetime.datetime.now()

        # Commit the changes
        session.add(dbAlliance)
        if commitOnEnd == True:
            session.commit()
        return True

    except Exception as e:
        apiLog("Exception occurred doing public alliance update on allianceID=%d: %s" % (allianceID, str(e)))
        session.rollback()
        return False
Exemple #22
0
    def testCreateUser(self):

        app = createApp()
        username = "******"
        password = "******"
        userData = {
            "username": username,
            "password": password,
            "email": "*****@*****.**",
            "isStaff": True,
            "isActive": True,
            "verified": True
        }

        deleteUser(username)
        request, response = app.test_client.post("/api/auth/createUser",
                                                 data=userData)
        dSession = getSession()
        self.assertTrue(userExists(username, dSession), "user exist")
        dSession.close()
Exemple #23
0
    def testManageUser(self):

        dSession = getSession(env)
        username = "******"
        password = "******"
        userData = {
            "username": username,
            "password": password,
            "email": "*****@*****.**",
            "isStaff": True,
            "isActive": True,
            "verified": True
        }

        deleteUser(username, dSession)
        createUser(userData, dSession)
        self.assertTrue(userExists(username, dSession),
                        "this user should exist")
        deleteUser(username, dSession)
        self.assertFalse(userExists(username, dSession),
                         "this user should not exist")
def chkTranslationId(func):
    '''
        @param func Page_Translation -> flask reply
        @return flask reply
        Check the existence of a translationId parameter.
        If the parameter exists and the corresponding instance of Page_Translations
        can be fetched, the given func is called and it's result returned.
        Otherwise a JSON encoded error message is returned.
    '''
    if 'translationId' in flask.request.args:
        tId = flask.request.args['translationId']
        try:
            t = db.getSession().query(db.Page_Translations).filter_by(TranslationId=tId).limit(1).one()
            return func(t)
        except sqlalchemy.orm.exc.NoResultFound:
            return flask.jsonify(**{
                'msg': 'Specified translationId not found in database: ' + tId
            })
    action = flask.request.args['action']
    return flask.jsonify(**{
        'msg': ('You need to specify a translationId for action=%s.' % action)})
Exemple #25
0
def supercheck():
    session = getSession()
    supers = []

    #for x in session.query(Asset, InvType, Character, Corporation).join(InvType).join(Character).join(Corporation).filter(InvType.groupID.in_((659, 30))).order_by(InvType.groupID, InvType.typeID, Character.lastKnownLocation).all():
    for x in session.query(
            Asset, InvType, Character,
            Corporation).join(InvType).join(InvGroup).join(Character).join(
                Corporation).filter(InvGroup.categoryID == 6).filter(
                    Asset.singleton == 1).order_by(
                        InvType.groupID, InvType.typeID,
                        Character.lastKnownLocation).all():
        sup = {}
        sup['ship'] = x.Asset
        sup['type'] = x.InvType
        sup['char'] = x.Character
        sup['corp'] = x.Corporation

        supers.append(sup)

    return render_template("viewship.html", config=config.auth, supers=supers)
def singleTextFile():
    '''
        Build after the preimage of php/export/singleTextFile.php
        Expected GET parameters are:
        * word, only containing digits of a wordId
        * language, only containing digits of a languageId
        * study, containing the name of a study
        * n, number of Phonetic entry to use, starts at 0
        Example route:
        /export/singleTextFile?word=7660&language=11111230301&study=Germanic&n=0
    '''
    args = flask.request.args
    # Checking parameters:
    params = ['word', 'language', 'study', 'n']
    for p in params:
        if p not in args:
            msg = "Missing parameter: '%s'! Parameters should be: %s" % (p, params)
            return msg, 400
    # Getting data to respond with:
    where = sqlalchemy.func.concat(
        db.Transcriptions.LanguageIx,
        db.Transcriptions.IxElicitation,
        db.Transcriptions.IxMorphologicalInstance).like(args['language'] + args['word'])
    transcriptions = db.getSession().query(db.Transcriptions).filter_by(StudyName=args['study']).filter(where).all()
    # Picking the element:
    n = int(args['n'])
    if n < 0:
        return "Parameter 'n' must be >= 0!", 400
    if n > len(transcriptions):
        return ("Parameter 'n' cannot be >= %s for this query." % len(transcriptions)), 400
    transcription = transcriptions[n].toDict()
    # Building and returning response:
    name = "transcription.txt"
    if len(transcription['soundPaths']) > 0:
        path = transcription['soundPaths'][0]
        name = os.path.basename(path).replace('.ogg', '.txt').replace('.mp3', '.txt')
    response = flask.make_response(transcription['Phonetic'])
    response.headers["Content-Type"] = 'text/plain; charset=utf-8'
    response.headers["Content-Disposition"] = "attachment; filename=%s" % name
    return response
Exemple #27
0
    def testCreateUser(self):

        sanicRequests.newSession()
        dSession = getSession()
        username = "******"
        password = "******"
        userData = {
            "username": username,
            "password": password,
            "email": "*****@*****.**",
            "isStaff": True,
            "isActive": True,
            "verified": True
        }

        deleteUser(username)
        response = sanicRequests.get("api/auth/createUser")
        userData.update(response.json())
        print(userData)
        sanicRequests.post("api/auth/createUser", data=userData)
        self.assertTrue(userExists(username, dSession), "user should exist")
        dSession.close()
Exemple #28
0
def addApi(user, keyID, vCode, name, session=getSession()):
    try:
        if session.query(Api).filter(Api.keyID == keyID, Api.vCode
                                     == vCode).count() > 0:
            return "This API Key is already in the database"

        # We NEED APIKeyInfo, AccountStatus, CharacterSheet and AssetList
        eveapi.set_user_agent("eveapi.py/1.3")
        eve = eveapi.EVEAPIConnection()
        try:
            keyInfo = eve.account.APIKeyInfo(keyID=keyID, vCode=vCode)
            if keyInfo.key.type == "Corporation":
                return "This is a corp API, it's need to be a Character or Account API"
        except eveapi.Error as e:
            return "This API key is invalid or expired"
        try:
            accStatus = eve.account.AccountStatus(keyID=keyID, vCode=vCode)
            apiChar = eve.char.CharacterSheet(
                keyID=keyID,
                vCode=vCode,
                characterID=keyInfo.key.characters[0].characterID)
            assetList = eve.char.AssetList(
                keyID=keyID,
                vCode=vCode,
                characterID=keyInfo.key.characters[0].characterID,
                flat=1)
            charInfo = eve.eve.CharacterInfo(
                keyID=keyID,
                vCode=vCode,
                characterID=keyInfo.key.characters[0].characterID)

        except eveapi.Error as e:
            return "Your API key doesn't have enough permissions, at minimum it needs to be an active key with AccountStatus and CharacterInfo"

        # Build the key object
        api = Api()
        api.userId = user.id
        api.keyID = keyID
        api.vCode = vCode
        api.accessMask = keyInfo.key.accessMask
        api.type = keyInfo.key.type
        api.paidUntil = datetime.datetime.fromtimestamp(accStatus.paidUntil)
        api.createDate = datetime.datetime.fromtimestamp(accStatus.createDate)
        api.logonCount = accStatus.logonCount
        api.logonMinutes = accStatus.logonMinutes
        api.name = name
        api.lastUpdated = datetime.datetime.now()
        api.added = datetime.datetime.now()

        session.add(api)
        session.commit()

        # Now update the api key
        updateApiKey(session=session, api=api)

        return api

    except eveapi.Error as e:
        session.rollback()
        return "An error occurred on the EVE API, it's probably not your fault, try again later"
    except Exception as e:
        session.rollback()
        return "An error occurred querying this key: %s" % str(e)
Exemple #29
0
def calculateTags(dbUser, session=None):
    # Create a session if one didn't already exist
    if session == None:
        session = getSession()
        commitOnEnd = True
    else:
        commitOnEnd = False

    # Get the config
    config = getConfig()

    # Get a set of the current tags
    currTags = map(lambda x: x.tag, session.query(Tag).filter(Tag.userId == dbUser.id).all())
    currTags = frozenset(currTags)
    newTags = []

    # Grab Ship Groups
    for x in session.query(Asset, InvGroup.groupName).join(InvType).join(InvGroup).join(Character).join(Api)\
    .filter(InvGroup.categoryID == 6,\
    Api.userId == dbUser.id).group_by(InvGroup.groupID).all():
        newTags.append("owns:%s" % x.groupName)

    # Grab Ship Types
    for x in session.query(Asset, InvType.typeName).join(InvType).join(InvGroup).join(Character).join(Api)\
    .filter(InvGroup.categoryID == 6,\
    Api.userId == dbUser.id).group_by(InvType.typeID).all():
        newTags.append("owns:%s" % x.typeName)

    # Check membership on chars for a few things
    for x in session.query(Character, Corporation.corporationID, Corporation.allianceID).join(Corporation).join(Api).join(User).filter(User.id == dbUser.id).all():
        # Check if the character meets any of the membership requirements
        for test in config.auth.members:
            if test.type not in ["alliance", "corporation"]:
                continue

            if test.type == "alliance" and x.allianceID != test.id:
                continue
            if test.type == "corporation" and x.corporationID != test.id:
                continue

            # Grab Skills
            for skill in session.query(Skill, InvType.typeName).join(InvType).filter(Skill.characterID == x.Character.characterID).all():
                newTags.append("has:%s" % skill.typeName)
                if skill.Skill.level == 5 and skill.Skill.skillpoints >= 1280000:
                    newTags.append("has:%s 5" % skill.typeName)

            # Grab Implant sets excluding supercap pilots
            #for x in session.query(Implant).join(InvType)


    # Purge old sets
    for x in frozenset(currTags).difference(newTags):
        session.delete(session.query(Tag).filter(Tag.userId == dbUser.id, Tag.tag == x).first())

    # Add new sets
    for x in frozenset(newTags).difference(currTags):
        newTag = Tag()
        newTag.userId = dbUser.id
        newTag.tag = x
        session.add(newTag)

    # Commit the session as it was created within this method
    if commitOnEnd == True:
        session.commit()
Exemple #30
0
def updateApiKey(api, session=getSession()):
    eveapi.set_user_agent("eveapi.py/1.3")
    eve = eveapi.EVEAPIConnection()

    # Open our main rollback try
    try:
        # Check that the API is still active...
        try:
            keyinfo = eve.account.APIKeyInfo(keyID=api.keyID, vCode=api.vCode)
        except eveapi.Error as e:
            # ...and delete the api if it isn't
            if e.code == 403:
                apiLog("\tDeleting API ID %d as it has been deleted or expired" % api.id)
                session.delete(api)
                session.commit()
            else:
                apiLog("The XMLAPI returned an error [%d] checking API ID %d, lets try again later" % (e.code, api.id))
            return
        except Exception as e:
            apiLog("Generic Exception checking API ID %d: %s" % (api.id, str(e)))
            return

        # Grab AccountStatus too
        accStatus = eve.account.AccountStatus(keyID=api.keyID, vCode=api.vCode)

        # Update the key info
        api.accessMask = keyinfo.key.accessMask
        api.type = keyinfo.key.type
        api.paidUntil = datetime.datetime.fromtimestamp(accStatus.paidUntil)
        api.createDate = datetime.datetime.fromtimestamp(accStatus.createDate)
        api.logonCount = accStatus.logonCount
        api.logonMinutes = accStatus.logonMinutes
        api.lastUpdated = datetime.datetime.now()
        if keyinfo.key.expires == "":
            api.expires = None
        else:
            api.expires = datetime.datetime.fromtimestamp(keyinfo.key.expires)

        key = keyinfo.key

        # Purge characters from database that aren't on the API
        for dbChar in api.characters:
            if dbChar.characterID not in map(lambda x: x.characterID, key.characters):
                apiLog("Deleted character as they were no longer on the API characterID=%d, characterName=%s" % (dbChar.characterID, dbChar.characterName))
                session.delete(dbChar)

        # Add or update characters from the API into the database
        for apiChar in key.characters:
            if apiChar.characterID not in map(lambda x: x.characterID, api.characters):
                dbChar = Character()
                dbChar.characterID = apiChar.characterID
                dbChar.apiId = api.id
                session.add(dbChar)
            else:
                for dbChar in api.characters:
                    if dbChar.characterID == apiChar.characterID:
                        # Suppresed this check as it doesn't make logical sense to limit it this far down stream
                        # Check its not been updated within the last 119 mins
                        #if (dbChar.lastUpdated + datetime.timedelta(0, 7140)) > datetime.datetime.now():
                        #    return
                        break

            # Get the CharacterSheet
            charSheet = eve.char.CharacterSheet(keyID=api.keyID, vCode=api.vCode, characterID=apiChar.characterID)
            charInfo = eve.eve.CharacterInfo(keyID=api.keyID, vCode=api.vCode, characterID=apiChar.characterID)

            # Upsert the corporation
            if not upsertCorporation(eve=eve, corporationID=charSheet.corporationID):
                apiLog("An error occurred upserting corporationID=%d, so we'll rollback and try later" % charSheet.corporationID)
                session.rollback()
                return

            # Update the characters values
            dbChar.characterName = apiChar.characterName
            dbChar.corporationID = apiChar.corporationID
            dbChar.factionID = apiChar.factionID
            dbChar.balance = charSheet.balance
            dbChar.cloneJumpDate = datetime.datetime.fromtimestamp(charSheet.cloneJumpDate)
            dbChar.jumpActivation = datetime.datetime.fromtimestamp(charSheet.jumpActivation)
            dbChar.jumpFatigue = datetime.datetime.fromtimestamp(charSheet.jumpFatigue)
            dbChar.jumpLastUpdate = datetime.datetime.fromtimestamp(charSheet.jumpLastUpdate)
            dbChar.DoB = datetime.datetime.fromtimestamp(charSheet.DoB)
            dbChar.remoteStationDate = datetime.datetime.fromtimestamp(charSheet.remoteStationDate)
            dbChar.homeStationID = charSheet.homeStationID
            dbChar.shipTypeID = charInfo.shipTypeID
            dbChar.shipName = charInfo.shipName
            dbChar.lastKnownLocation = charInfo.lastKnownLocation
            dbChar.lastUpdated = datetime.datetime.now()

            # Get the Asset List
            assetList = eve.char.AssetList(keyID=api.keyID, vCode=api.vCode, characterID=apiChar.characterID, flat=1)
            apiAssetsById = assetList.assets.IndexedBy("itemID")

            # Purge assets from the database that aren't on the API
            for dbAsset in session.query(Asset).filter(Asset.characterID == apiChar.characterID).all():
                try:
                    apiAssetsById.Get(dbAsset.itemID)
                except:
                    session.delete(dbAsset)

            # Add or update assets from the API into the database
            dbAssets = session.query(Asset).filter(Asset.characterID == apiChar.characterID).all()
            dbAssetsDict = {}
            for dbAsset in dbAssets:
                dbAssetsDict[dbAsset.itemID] = dbAsset
            newAssets = []
            dbAssetSet = frozenset(frozenset(map(lambda x: x.itemID, dbAssets)))
            for apiAsset in assetList.assets:
                if apiAsset.itemID not in dbAssetSet:
                    dbAsset = Asset()
                    dbAsset.itemID = apiAsset.itemID
                    dbAsset.characterID = apiChar.characterID
                    newAssets.append(dbAsset)
                else:
                    dbAsset = dbAssetsDict[apiAsset.itemID]

                # Update the asset values
                dbAsset.locationID = apiAsset.locationID
                dbAsset.typeID = apiAsset.typeID
                dbAsset.quantity = apiAsset.quantity
                dbAsset.flag = apiAsset.flag
                dbAsset.singleton = apiAsset.singleton

            # Add the assets to the session
            session.add_all(newAssets)

            # Add or update skills from the API into the database
            newSkills = []
            dbSkillsDict = {}
            for dbSkill in dbChar.skills:
                dbSkillsDict[dbSkill.typeID] = dbSkill
            dbSkillSet = frozenset(map(lambda x: "%d:%d" % (x.characterID, x.typeID), dbChar.skills))
            for apiSkill in charSheet.skills:
                if "%d:%d" % (apiChar.characterID, apiSkill.typeID) not in dbSkillSet:
                    dbSkill = Skill()
                    dbSkill.characterID = apiChar.characterID
                    dbSkill.typeID = apiSkill.typeID
                    newSkills.append(dbSkill)
                else:
                    dbSkill = dbSkillsDict[apiSkill.typeID]

                # Update the skills values
                dbSkill.level = apiSkill.level
                dbSkill.skillpoints = apiSkill.skillpoints

            # Add the skills to the session
            session.add_all(newSkills)


            # Purge jump clones from the database that aren't on the API
            jumpClonesById = charSheet.jumpClones.IndexedBy("jumpCloneID")
            for dbJumpClone in session.query(JumpClone).filter(JumpClone.characterID == dbChar.characterID).all():
                try:
                    jumpClonesById.Get(dbJumpClone.jumpCloneID)
                except:
                    session.delete(dbJumpClone)

            # Add or update jump clones from the API into the database
            newJumpClones = []
            dbJumpClonesDict = {}
            dbJumpClones = session.query(JumpClone).filter(JumpClone.characterID == dbChar.characterID).all()
            for x in dbJumpClones:
                dbJumpClonesDict[x.jumpCloneID] = x
            dbJumpCloneSet = frozenset(map(lambda x: x.jumpCloneID, dbJumpClones))
            for apiJumpClone in charSheet.jumpClones:
                if apiJumpClone.jumpCloneID not in dbJumpCloneSet:
                    dbJumpClone = JumpClone()
                    dbJumpClone.jumpCloneID = apiJumpClone.jumpCloneID
                    dbJumpClone.characterID = charSheet.characterID
                    newJumpClones.append(dbJumpClone)
                else:
                    dbJumpClone = dbJumpClonesDict[apiJumpClone.jumpCloneID]

                # Update the values
                dbJumpClone.cloneName = apiJumpClone.cloneName
                dbJumpClone.locationID = apiJumpClone.locationID
                dbJumpClone.typeID = apiJumpClone.typeID

            # Add the new jump clones to the session
            session.add_all(newJumpClones)

            # Handle current implants
            apiCurrImplants = frozenset(map(lambda x: x.typeID, charSheet.implants))
            for x in session.query(Implant).filter(Implant.characterID == dbChar.characterID).filter(Implant.jumpCloneID == None).all():
                if x.typeID not in apiCurrImplants:
                    session.delete(x)

            dbImplantSet = frozenset(map(lambda x: x.typeID, session.query(Implant).filter(Implant.characterID == dbChar.characterID).filter(Implant.jumpCloneID == None).all()))
            for x in charSheet.implants:
                if x.typeID not in dbImplantSet:
                    dbImplant = Implant()
                    dbImplant.characterID = dbChar.characterID
                    dbImplant.jumpCloneID = None
                    dbImplant.typeID = x.typeID
                    session.add(dbImplant)

            # Handle Jump Clone implants
            apiJCImplants = frozenset(map(lambda x: "%d:%d" % (x.jumpCloneID, x.typeID), charSheet.jumpCloneImplants))
            for x in session.query(Implant).filter(Implant.characterID == dbChar.characterID).filter(Implant.jumpCloneID != None).all():
                if "%d:%d" % (x.jumpCloneID, x.typeID) not in apiJCImplants:
                    session.delete(x)

            dbImplantSet = frozenset(map(lambda x: "%d:%d" % (x.jumpCloneID, x.typeID), session.query(Implant).filter(Implant.characterID == dbChar.characterID).filter(Implant.jumpCloneID != None).all()))
            for x in charSheet.jumpCloneImplants:
                if "%d:%d" % (x.jumpCloneID, x.typeID) not in dbImplantSet:
                    dbImplant = Implant()
                    dbImplant.characterID = dbChar.characterID
                    dbImplant.jumpCloneID = x.jumpCloneID
                    dbImplant.typeID = x.typeID
                    session.add(dbImplant)


            # Log line
            apiLog("\tUpdated characterID=%d, characterName='%s'" % (dbChar.characterID, dbChar.characterName))


        # Commit all of the updates to the database
        session.commit()

    # Exceptions for our main rollback try
    except eveapi.Error as e:
        if e.code == 403:
            session.rollback()
            session.delete(api)
            session.commit()
            apiLog("\tDeleted API as it has lost permissions we need, into the trash you go")
        else:
            apiLog("\tXMLAPI returned the following error: [%d] '%s'" % (e.code, e.message))
        session.rollback()
Exemple #31
0
 def __init__(self):
     """TWorktimeManager constructor
     Inits session"""
     self.session = db.getSession()
Exemple #32
0
def dictAll(model):
    return [m.toDict() for m in db.getSession().query(model).all()]
def getFamily(name):  # May throw!
    family = db.getSession().query(db.Families).filter_by(FamilyNm=name).limit(1).one()
    if family.ProjectActive:
        return family
    raise RuntimeError("Family {} is not marked as active.".format(name))
Exemple #34
0
def updateApiKey(api, session=getSession()):
    eveapi.set_user_agent("eveapi.py/1.3")
    eve = eveapi.EVEAPIConnection()

    # Open our main rollback try
    try:
        # Check that the API is still active...
        try:
            keyinfo = eve.account.APIKeyInfo(keyID=api.keyID, vCode=api.vCode)
        except eveapi.Error as e:
            # ...and delete the api if it isn't
            if e.code == 403:
                apiLog(
                    "\tDeleting API ID %d as it has been deleted or expired" %
                    api.id)
                session.delete(api)
                session.commit()
            else:
                apiLog(
                    "The XMLAPI returned an error [%d] checking API ID %d, lets try again later"
                    % (e.code, api.id))
            return
        except Exception as e:
            apiLog("Generic Exception checking API ID %d: %s" %
                   (api.id, str(e)))
            return

        # Grab AccountStatus too
        accStatus = eve.account.AccountStatus(keyID=api.keyID, vCode=api.vCode)

        # Update the key info
        api.accessMask = keyinfo.key.accessMask
        api.type = keyinfo.key.type
        api.paidUntil = datetime.datetime.fromtimestamp(accStatus.paidUntil)
        api.createDate = datetime.datetime.fromtimestamp(accStatus.createDate)
        api.logonCount = accStatus.logonCount
        api.logonMinutes = accStatus.logonMinutes
        api.lastUpdated = datetime.datetime.now()
        if keyinfo.key.expires == "":
            api.expires = None
        else:
            api.expires = datetime.datetime.fromtimestamp(keyinfo.key.expires)

        key = keyinfo.key

        # Purge characters from database that aren't on the API
        for dbChar in api.characters:
            if dbChar.characterID not in map(lambda x: x.characterID,
                                             key.characters):
                apiLog(
                    "Deleted character as they were no longer on the API characterID=%d, characterName=%s"
                    % (dbChar.characterID, dbChar.characterName))
                session.delete(dbChar)

        # Add or update characters from the API into the database
        for apiChar in key.characters:
            if apiChar.characterID not in map(lambda x: x.characterID,
                                              api.characters):
                dbChar = Character()
                dbChar.characterID = apiChar.characterID
                dbChar.apiId = api.id
                session.add(dbChar)
            else:
                for dbChar in api.characters:
                    if dbChar.characterID == apiChar.characterID:
                        # Suppresed this check as it doesn't make logical sense to limit it this far down stream
                        # Check its not been updated within the last 119 mins
                        #if (dbChar.lastUpdated + datetime.timedelta(0, 7140)) > datetime.datetime.now():
                        #    return
                        break

            # Get the CharacterSheet
            charSheet = eve.char.CharacterSheet(
                keyID=api.keyID,
                vCode=api.vCode,
                characterID=apiChar.characterID)
            charInfo = eve.eve.CharacterInfo(keyID=api.keyID,
                                             vCode=api.vCode,
                                             characterID=apiChar.characterID)

            # Upsert the corporation
            if not upsertCorporation(eve=eve,
                                     corporationID=charSheet.corporationID):
                apiLog(
                    "An error occurred upserting corporationID=%d, so we'll rollback and try later"
                    % charSheet.corporationID)
                session.rollback()
                return

            # Update the characters values
            dbChar.characterName = apiChar.characterName
            dbChar.corporationID = apiChar.corporationID
            dbChar.factionID = apiChar.factionID
            dbChar.balance = charSheet.balance
            dbChar.cloneJumpDate = datetime.datetime.fromtimestamp(
                charSheet.cloneJumpDate)
            dbChar.jumpActivation = datetime.datetime.fromtimestamp(
                charSheet.jumpActivation)
            dbChar.jumpFatigue = datetime.datetime.fromtimestamp(
                charSheet.jumpFatigue)
            dbChar.jumpLastUpdate = datetime.datetime.fromtimestamp(
                charSheet.jumpLastUpdate)
            dbChar.DoB = datetime.datetime.fromtimestamp(charSheet.DoB)
            dbChar.remoteStationDate = datetime.datetime.fromtimestamp(
                charSheet.remoteStationDate)
            dbChar.homeStationID = charSheet.homeStationID
            dbChar.shipTypeID = charInfo.shipTypeID
            dbChar.shipName = charInfo.shipName
            dbChar.lastKnownLocation = charInfo.lastKnownLocation
            dbChar.lastUpdated = datetime.datetime.now()

            # Get the Asset List
            assetList = eve.char.AssetList(keyID=api.keyID,
                                           vCode=api.vCode,
                                           characterID=apiChar.characterID,
                                           flat=1)
            apiAssetsById = assetList.assets.IndexedBy("itemID")

            # Purge assets from the database that aren't on the API
            for dbAsset in session.query(Asset).filter(
                    Asset.characterID == apiChar.characterID).all():
                try:
                    apiAssetsById.Get(dbAsset.itemID)
                except:
                    session.delete(dbAsset)

            # Add or update assets from the API into the database
            dbAssets = session.query(Asset).filter(
                Asset.characterID == apiChar.characterID).all()
            dbAssetsDict = {}
            for dbAsset in dbAssets:
                dbAssetsDict[dbAsset.itemID] = dbAsset
            newAssets = []
            dbAssetSet = frozenset(frozenset(map(lambda x: x.itemID,
                                                 dbAssets)))
            for apiAsset in assetList.assets:
                if apiAsset.itemID not in dbAssetSet:
                    dbAsset = Asset()
                    dbAsset.itemID = apiAsset.itemID
                    dbAsset.characterID = apiChar.characterID
                    newAssets.append(dbAsset)
                else:
                    dbAsset = dbAssetsDict[apiAsset.itemID]

                # Update the asset values
                dbAsset.locationID = apiAsset.locationID
                dbAsset.typeID = apiAsset.typeID
                dbAsset.quantity = apiAsset.quantity
                dbAsset.flag = apiAsset.flag
                dbAsset.singleton = apiAsset.singleton

            # Add the assets to the session
            session.add_all(newAssets)

            # Add or update skills from the API into the database
            newSkills = []
            dbSkillsDict = {}
            for dbSkill in dbChar.skills:
                dbSkillsDict[dbSkill.typeID] = dbSkill
            dbSkillSet = frozenset(
                map(lambda x: "%d:%d" % (x.characterID, x.typeID),
                    dbChar.skills))
            for apiSkill in charSheet.skills:
                if "%d:%d" % (apiChar.characterID,
                              apiSkill.typeID) not in dbSkillSet:
                    dbSkill = Skill()
                    dbSkill.characterID = apiChar.characterID
                    dbSkill.typeID = apiSkill.typeID
                    newSkills.append(dbSkill)
                else:
                    dbSkill = dbSkillsDict[apiSkill.typeID]

                # Update the skills values
                dbSkill.level = apiSkill.level
                dbSkill.skillpoints = apiSkill.skillpoints

            # Add the skills to the session
            session.add_all(newSkills)

            # Purge jump clones from the database that aren't on the API
            jumpClonesById = charSheet.jumpClones.IndexedBy("jumpCloneID")
            for dbJumpClone in session.query(JumpClone).filter(
                    JumpClone.characterID == dbChar.characterID).all():
                try:
                    jumpClonesById.Get(dbJumpClone.jumpCloneID)
                except:
                    session.delete(dbJumpClone)

            # Add or update jump clones from the API into the database
            newJumpClones = []
            dbJumpClonesDict = {}
            dbJumpClones = session.query(JumpClone).filter(
                JumpClone.characterID == dbChar.characterID).all()
            for x in dbJumpClones:
                dbJumpClonesDict[x.jumpCloneID] = x
            dbJumpCloneSet = frozenset(
                map(lambda x: x.jumpCloneID, dbJumpClones))
            for apiJumpClone in charSheet.jumpClones:
                if apiJumpClone.jumpCloneID not in dbJumpCloneSet:
                    dbJumpClone = JumpClone()
                    dbJumpClone.jumpCloneID = apiJumpClone.jumpCloneID
                    dbJumpClone.characterID = charSheet.characterID
                    newJumpClones.append(dbJumpClone)
                else:
                    dbJumpClone = dbJumpClonesDict[apiJumpClone.jumpCloneID]

                # Update the values
                dbJumpClone.cloneName = apiJumpClone.cloneName
                dbJumpClone.locationID = apiJumpClone.locationID
                dbJumpClone.typeID = apiJumpClone.typeID

            # Add the new jump clones to the session
            session.add_all(newJumpClones)

            # Handle current implants
            apiCurrImplants = frozenset(
                map(lambda x: x.typeID, charSheet.implants))
            for x in session.query(Implant).filter(
                    Implant.characterID == dbChar.characterID).filter(
                        Implant.jumpCloneID == None).all():
                if x.typeID not in apiCurrImplants:
                    session.delete(x)

            dbImplantSet = frozenset(
                map(
                    lambda x: x.typeID,
                    session.query(Implant).filter(
                        Implant.characterID == dbChar.characterID).filter(
                            Implant.jumpCloneID == None).all()))
            for x in charSheet.implants:
                if x.typeID not in dbImplantSet:
                    dbImplant = Implant()
                    dbImplant.characterID = dbChar.characterID
                    dbImplant.jumpCloneID = None
                    dbImplant.typeID = x.typeID
                    session.add(dbImplant)

            # Handle Jump Clone implants
            apiJCImplants = frozenset(
                map(lambda x: "%d:%d" % (x.jumpCloneID, x.typeID),
                    charSheet.jumpCloneImplants))
            for x in session.query(Implant).filter(
                    Implant.characterID == dbChar.characterID).filter(
                        Implant.jumpCloneID != None).all():
                if "%d:%d" % (x.jumpCloneID, x.typeID) not in apiJCImplants:
                    session.delete(x)

            dbImplantSet = frozenset(
                map(
                    lambda x: "%d:%d" % (x.jumpCloneID, x.typeID),
                    session.query(Implant).filter(
                        Implant.characterID == dbChar.characterID).filter(
                            Implant.jumpCloneID != None).all()))
            for x in charSheet.jumpCloneImplants:
                if "%d:%d" % (x.jumpCloneID, x.typeID) not in dbImplantSet:
                    dbImplant = Implant()
                    dbImplant.characterID = dbChar.characterID
                    dbImplant.jumpCloneID = x.jumpCloneID
                    dbImplant.typeID = x.typeID
                    session.add(dbImplant)

            # Log line
            apiLog("\tUpdated characterID=%d, characterName='%s'" %
                   (dbChar.characterID, dbChar.characterName))

        # Commit all of the updates to the database
        session.commit()

    # Exceptions for our main rollback try
    except eveapi.Error as e:
        if e.code == 403:
            session.rollback()
            session.delete(api)
            session.commit()
            apiLog(
                "\tDeleted API as it has lost permissions we need, into the trash you go"
            )
        else:
            apiLog("\tXMLAPI returned the following error: [%d] '%s'" %
                   (e.code, e.message))
        session.rollback()
Exemple #35
0
def calculateTags(dbUser, session=None):
    # Create a session if one didn't already exist
    if session == None:
        session = getSession()
        commitOnEnd = True
    else:
        commitOnEnd = False

    # Get the config
    config = getConfig()

    # Get a set of the current tags
    currTags = map(lambda x: x.tag,
                   session.query(Tag).filter(Tag.userId == dbUser.id).all())
    currTags = frozenset(currTags)
    newTags = []

    # Grab Ship Groups
    for x in session.query(Asset, InvGroup.groupName).join(InvType).join(InvGroup).join(Character).join(Api)\
    .filter(InvGroup.categoryID == 6,\
    Api.userId == dbUser.id).group_by(InvGroup.groupID).all():
        newTags.append("owns:%s" % x.groupName)

    # Grab Ship Types
    for x in session.query(Asset, InvType.typeName).join(InvType).join(InvGroup).join(Character).join(Api)\
    .filter(InvGroup.categoryID == 6,\
    Api.userId == dbUser.id).group_by(InvType.typeID).all():
        newTags.append("owns:%s" % x.typeName)

    # Check membership on chars for a few things
    for x in session.query(
            Character, Corporation.corporationID,
            Corporation.allianceID).join(Corporation).join(Api).join(
                User).filter(User.id == dbUser.id).all():
        # Check if the character meets any of the membership requirements
        for test in config.auth.members:
            if test.type not in ["alliance", "corporation"]:
                continue

            if test.type == "alliance" and x.allianceID != test.id:
                continue
            if test.type == "corporation" and x.corporationID != test.id:
                continue

            # Grab Skills
            for skill in session.query(
                    Skill, InvType.typeName).join(InvType).filter(
                        Skill.characterID == x.Character.characterID).all():
                newTags.append("has:%s" % skill.typeName)
                if skill.Skill.level == 5 and skill.Skill.skillpoints >= 1280000:
                    newTags.append("has:%s 5" % skill.typeName)

            # Grab Implant sets excluding supercap pilots
            #for x in session.query(Implant).join(InvType)

    # Purge old sets
    for x in frozenset(currTags).difference(newTags):
        session.delete(
            session.query(Tag).filter(Tag.userId == dbUser.id,
                                      Tag.tag == x).first())

    # Add new sets
    for x in frozenset(newTags).difference(currTags):
        newTag = Tag()
        newTag.userId = dbUser.id
        newTag.tag = x
        session.add(newTag)

    # Commit the session as it was created within this method
    if commitOnEnd == True:
        session.commit()
Exemple #36
0
import sys

from flask import Flask, Request, render_template
from flask.ext.login import LoginManager, UserMixin, login_required

from config import getConfig
from db import getSession
from models import *
from ships import *
from dispfuncs import *

# Setup
config = getConfig()
session = getSession()

reload(sys)
sys.setdefaultencoding("utf-8")
app = Flask(__name__)
login_manager = LoginManager()
login_manager.init_app(app)

# Jinja functions
app.jinja_env.globals.update(fitModHtml=fitModHtml)


@app.route("/")
def index():
    return render_template("index.html", config=config.auth)


@app.route("/viewship/<int:itemID>")
Exemple #37
0
import sys

from flask import Flask, Request, render_template
from flask.ext.login import LoginManager, UserMixin, login_required

from config import getConfig
from db import getSession
from models import *
from ships import *
from dispfuncs import *

# Setup
config = getConfig()
session = getSession()

reload(sys)
sys.setdefaultencoding("utf-8")
app = Flask(__name__)
login_manager = LoginManager()
login_manager.init_app(app)

# Jinja functions
app.jinja_env.globals.update(fitModHtml=fitModHtml)

@app.route("/")
def index():
	return render_template("index.html", config=config.auth)


@app.route("/viewship/<int:itemID>")
def viewship(itemID):
Exemple #38
0
import networkx
import numpy.linalg
import pylab
n = 100
m = 500
g = networkx.gnm_random_graph(n, m)
l = networkx.generalized_laplacian(g)
e = numpy.linalg.eigvals(l)
max(e), min(e)
pylab.hist(e, bins=10)
pylab.xlim(0, 2)
pylab.show()

import networkx as nx
import db
s = db.getSession()
def makeGraph(session):
    g = nx.DiGraph()
    for src, dest in session.query(db.Anchor.source, db.Anchor.destination):
        g.add_edge(src, dest)
    return g


def islowfrequency(anchor):
    return anchor.frequency < 2


def rel(anchor, other):
    return 0.0