Пример #1
0
def get_corp(corporationID):
    """
     corporationID: int
     :Corporation Object
    """
    try:
        return Corporation.objects.get(corporationID=corporationID)
    except Corporation.DoesNotExist:
        conn = api.eveapi.EVEAPIConnection()
        api_corp = conn.corp.CorporationSheet(corporationID=corporationID)
        LOG.info("Adding new Corporation: "+ str(api_corp.corporationName))
        corp = Corporation(corporationID   = api_corp.corporationID,
                           corporationName = str(api_corp.corporationName),
                           ticker          = api_corp.ticker,
                           ceoID           = api_corp.ceoID,
                           ceoName         = api_corp.ceoName,
                           stationID       = api_corp.stationID,
                           stationName     = api_corp.stationName,
                           description     = fix_description(api_corp.description),
                           taxRate         = api_corp.taxRate,
                           )
        if api_corp.allianceID:
            corp.alliance = get_alliance(api_corp.allianceID)
        corp.save()
        return corp
Пример #2
0
def get_corp(corporationID):
    """
     corporationID: int
     :Corporation Object
    """
    try:
        return Corporation.objects.get(corporationID=corporationID)
    except Corporation.DoesNotExist:
        conn = api.eveapi.EVEAPIConnection()
        api_corp = conn.corp.CorporationSheet(corporationID=corporationID)
        LOG.info("Adding new Corporation: " + str(api_corp.corporationName))
        corp = Corporation(
            corporationID=api_corp.corporationID,
            corporationName=str(api_corp.corporationName),
            ticker=api_corp.ticker,
            ceoID=api_corp.ceoID,
            ceoName=api_corp.ceoName,
            stationID=api_corp.stationID,
            stationName=api_corp.stationName,
            description=fix_description(api_corp.description),
            taxRate=api_corp.taxRate,
        )
        if api_corp.allianceID:
            corp.alliance = get_alliance(api_corp.allianceID)
        corp.save()
        return corp
Пример #3
0
def corp(request):
    try:
        corp = Corporation.objects.mine()
        corp.description = SHOWINFO_PATTERN.sub(r'/hr/members/\1/',
                                                corp.description)
        corp.memberCount = corp.members.all().count()
    except Corporation.DoesNotExist:
        corp = Corporation(corporationName='No Corporation info')

    return render_to_response('ecm/corp/corp.html', {'corp': corp},
                              Ctx(request))
Пример #4
0
def handle_contact(request):
    
    if request.method == 'POST':
        public_info = Corporation.objects.mine().get_public_info()
        
        try:
            corp_info = json.loads(request.body)
            ecm_url = corp_info['ecm_url']
            corporationID = corp_info['corporationID']
            corporationName = corp_info['corporationName']
            ticker = corp_info['ticker']
            public_key = corp_info['public_key']
            key_fingerprint = corp_info['key_fingerprint']
            try:
                alliance = Alliance.objects.get(allianceID = corp_info['alliance'])
            except Alliance.DoesNotExist:
                alliance = Alliance()
                alliance.allianceID = corp_info['alliance']
                alliancesApi = api.connect().eve.AllianceList()
                for a in alliancesApi.alliances:
                    if a.allianceID == corp_info['alliance']:
                        alliance.shortName = a.shortName
                        alliance.name = a.name
                        alliance.save()
                        break
            new_request = False
            if Corporation.objects.filter(corporationID=corporationID).exists():
                corp = Corporation.objects.get(corporationID=corporationID)
                if not corp.key_fingerprint:
                    # This corp was created by some internal task but we don't know their 
                    # public info yet.
                    corp.corporationName = corporationName
                    corp.ticker = ticker
                    corp.alliance = alliance
                    corp.ecm_url = ecm_url
                    corp.public_key = public_key
                    corp.key_fingerprint = key_fingerprint
                    corp.is_trusted = False
                    new_request = True
                else:
                    if corp.key_fingerprint != key_fingerprint:
                        # tentative of hack? return an error
                        LOG.error(WRONG_FINGERPRINT_MSG % (corporationName, corporationID))
                        raise ValueError('wrong key_fingerprint')
            else:
                # create the corp in our db
                corp = Corporation(corporationID=corporationID,
                                   corporationName=corporationName,
                                   ticker=ticker,
                                   alliance=alliance,
                                   ecm_url=ecm_url,
                                   public_key=public_key,
                                   key_fingerprint=key_fingerprint,
                                   is_trusted=False,
                                   )
                new_request = True
                
            if new_request:
                corp.save()
                # notify the admins that a new corp tried to contact us
                subject = ugettext('%s wants to exchange data with us') % corp.corporationName
                ctx_dict = {
                    'host_name': settings.EXTERNAL_HOST_NAME,
                    'use_https': settings.USE_HTTPS,
                    'corp': corp,
                }
                txt_content = render_to_string('ecm/corp/email/notify_contact.txt', 
                                               ctx_dict, Ctx(request))
                html_content = render_to_string('ecm/corp/email/notify_contact.html', 
                                                ctx_dict, Ctx(request))
                mail_admins(subject, txt_content, html_message=html_content)
            
            # if everything went well, return back our public info
            return HttpResponse(json.dumps(public_info))
            
        except (ValueError, KeyError), e:
            # invalid field value
            return HttpResponseBadRequest(str(e))
Пример #5
0
def handle_contact(request):

    if request.method == 'POST':
        public_info = Corporation.objects.mine().get_public_info()

        try:
            corp_info = json.loads(request.body)
            ecm_url = corp_info['ecm_url']
            corporationID = corp_info['corporationID']
            corporationName = corp_info['corporationName']
            ticker = corp_info['ticker']
            public_key = corp_info['public_key']
            key_fingerprint = corp_info['key_fingerprint']
            try:
                alliance = Alliance.objects.get(
                    allianceID=corp_info['alliance'])
            except Alliance.DoesNotExist:
                alliance = Alliance()
                alliance.allianceID = corp_info['alliance']
                alliancesApi = api.connect().eve.AllianceList()
                for a in alliancesApi.alliances:
                    if a.allianceID == corp_info['alliance']:
                        alliance.shortName = a.shortName
                        alliance.name = a.name
                        alliance.save()
                        break
            new_request = False
            if Corporation.objects.filter(
                    corporationID=corporationID).exists():
                corp = Corporation.objects.get(corporationID=corporationID)
                if not corp.key_fingerprint:
                    # This corp was created by some internal task but we don't know their
                    # public info yet.
                    corp.corporationName = corporationName
                    corp.ticker = ticker
                    corp.alliance = alliance
                    corp.ecm_url = ecm_url
                    corp.public_key = public_key
                    corp.key_fingerprint = key_fingerprint
                    corp.is_trusted = False
                    new_request = True
                else:
                    if corp.key_fingerprint != key_fingerprint:
                        # tentative of hack? return an error
                        LOG.error(WRONG_FINGERPRINT_MSG %
                                  (corporationName, corporationID))
                        raise ValueError('wrong key_fingerprint')
            else:
                # create the corp in our db
                corp = Corporation(
                    corporationID=corporationID,
                    corporationName=corporationName,
                    ticker=ticker,
                    alliance=alliance,
                    ecm_url=ecm_url,
                    public_key=public_key,
                    key_fingerprint=key_fingerprint,
                    is_trusted=False,
                )
                new_request = True

            if new_request:
                corp.save()
                # notify the admins that a new corp tried to contact us
                subject = ugettext(
                    '%s wants to exchange data with us') % corp.corporationName
                ctx_dict = {
                    'host_name': settings.EXTERNAL_HOST_NAME,
                    'use_https': settings.USE_HTTPS,
                    'corp': corp,
                }
                txt_content = render_to_string(
                    'ecm/corp/email/notify_contact.txt', ctx_dict,
                    Ctx(request))
                html_content = render_to_string(
                    'ecm/corp/email/notify_contact.html', ctx_dict,
                    Ctx(request))
                mail_admins(subject, txt_content, html_message=html_content)

            # if everything went well, return back our public info
            return HttpResponse(json.dumps(public_info))

        except (ValueError, KeyError), e:
            # invalid field value
            return HttpResponseBadRequest(str(e))
Пример #6
0
def update_corp_info(corpApi, currentTime):
    try:
        try:
            try:
                alliance = Alliance.objects.get(allianceID = corpApi.allianceID)
            except Alliance.DoesNotExist:
                LOG.info("Adding new Alliance: "+ corpApi.allianceName)
                alliance = Alliance()
                alliance.allianceID = corpApi.allianceID
                alliance.name = corpApi.allianceName
                alliancesApi = api.connect().eve.AllianceList()
                for a in alliancesApi.alliances:
                    if a.allianceID == corpApi.allianceID:
                        alliance.shortName = a.shortName
                        alliance.save()
                        break
        except api.Error:
            LOG.exception("Failed to fetch AllianceList.xml.aspx from EVE API server")
            corp = Corporation.objects.mine()
            alliance = None
    except:
        alliance = None

    description = fix_description(corpApi.description)

    # reset all other corps
    Corporation.objects.exclude(corporationID=corpApi.corporationID).update(is_my_corp=False)

    try:
        # try to retrieve the db stored corp info
        corp = Corporation.objects.get(corporationID=corpApi.corporationID)
        corp.is_my_corp      = True
        corp.corporationID   = corpApi.corporationID
        corp.corporationName = corpApi.corporationName
        corp.ticker          = corpApi.ticker
        corp.ceoID           = corpApi.ceoID
        corp.ceoName         = corpApi.ceoName
        corp.stationID       = corpApi.stationID
        corp.stationName     = corpApi.stationName
        corp.alliance        = alliance
        corp.description     = description
        corp.taxRate         = corpApi.taxRate
        corp.memberLimit     = corpApi.memberLimit
    except Corporation.DoesNotExist:
        LOG.debug('First scan, creating corp...')
        # no corp parsed yet
        corp = Corporation(is_my_corp      = True,
                           corporationID   = corpApi.corporationID,
                           corporationName = corpApi.corporationName,
                           ticker          = corpApi.ticker,
                           ceoID           = corpApi.ceoID,
                           ceoName         = corpApi.ceoName,
                           stationID       = corpApi.stationID,
                           stationName     = corpApi.stationName,
                           description     = description,
                           alliance        = alliance,
                           taxRate         = corpApi.taxRate,
                           memberLimit     = corpApi.memberLimit
                           )
    
    if settings.USE_HTTPS:
        corp.ecm_url = 'https://' + settings.EXTERNAL_HOST_NAME
    else:
        corp.ecm_url = 'http://' + settings.EXTERNAL_HOST_NAME
    
    if not (corp.private_key and corp.public_key and corp.key_fingerprint):
        # as this is the first time, we must generate the RSA keypair of our own corp
        LOG.debug('Generating RSA key pair...')
        corp.private_key = crypto.generate_rsa_keypair()
        corp.public_key = crypto.extract_public_key(corp.private_key)
        corp.key_fingerprint = crypto.key_fingerprint(corp.public_key) 
        LOG.info('Generated RSA key pair for corporation ID %d.' % corpApi.corporationID)

    corp.save()
    # we store the update time of the table
    UpdateDate.mark_updated(model=Corporation, date=currentTime)

    return corp
Пример #7
0
def journal_data(request):
    try:
        params = extract_datatable_params(request)
        REQ = request.GET if request.method == 'GET' else request.POST
        params.walletID = int(REQ.get('walletID', 0))
        params.entryTypeID = int(REQ.get('entryTypeID', 0))
        params.amount = request.GET.get('amount', None)
        params.comparator = request.GET.get('comparator', 'gt')
        params.from_date = timezone.make_aware(
            datetime.strptime(REQ.get('from_date', None), DATE_PATTERN),
            timezone.get_current_timezone())
        params.to_date = timezone.make_aware(
            datetime.strptime(REQ.get('to_date', None), DATE_PATTERN),
            timezone.get_current_timezone())
    except:
        return HttpResponseBadRequest()

    orderBy = journal_cols[params.column]
    if not params.asc: orderBy = "-" + orderBy
    query = JournalEntry.objects.select_related(
        depth=1).all().order_by(orderBy)

    if params.search or params.walletID or params.entryTypeID or params.amount or (
            params.from_date and params.to_date):
        total_entries = query.count()
        search_args = Q()

        if params.search:
            search_args |= Q(ownerName1__icontains=params.search)
            search_args |= Q(ownerName2__icontains=params.search)
            search_args |= Q(argName1__icontains=params.search)
            search_args |= Q(reason__icontains=params.search)
            if is_number(params.search):
                search_args |= Q(amount__gte=params.search)
        if params.walletID:
            search_args &= Q(wallet=params.walletID)
        if params.entryTypeID:
            search_args &= Q(type=params.entryTypeID)
        # Add query amount
        if params.amount:
            comparator_map = {
                'gt': Q(amount__gt=params.amount),
                'lt': Q(amount__lt=params.amount),
                'gte': Q(amount__gte=params.amount),
                'lte': Q(amount__lte=params.amount),
                'eq': Q(amount=params.amount),
                'neq': Q(amount__lt=params.amount, amount__gt=params.amount),
            }
            search_args &= comparator_map[params.comparator]

        # Add query dates
        if params.from_date and params.to_date:
            # + 24 hours on the to date
            search_args &= Q(date__range=(params.from_date,
                                          params.to_date + timedelta(days=1)))

        query = query.filter(search_args)
        filtered_entries = query.count()
    else:
        total_entries = filtered_entries = query.count()

    query = query[params.first_id:params.last_id]
    entries = []

    # to improve performance
    try:
        corp = Corporation.objects.mine()
    except Corporation.DoesNotExist:
        corp = Corporation(corporationID=0)
    members = Member.objects.all()
    other_entries = JournalEntry.objects.select_related().all()

    for entry in query:

        try:
            owner1 = members.get(characterID=entry.ownerID1).permalink
        except Member.DoesNotExist:
            owner1 = entry.ownerName1
        try:
            owner2 = members.get(characterID=entry.ownerID2).permalink
        except Member.DoesNotExist:
            owner2 = entry.ownerName2

        if entry.type_id == EntryType.BOUNTY_PRIZES:
            rats = [s.split(':') for s in entry.reason.split(',') if ':' in s]
            rat_list = []
            for rat_id, rat_count in rats:
                rat_list.append(
                    '%s x%s' %
                    (Type.objects.get(typeID=rat_id).typeName, rat_count))
            reason = '|'.join(rat_list)
            if reason:
                reason = (u'Killed Rats in %s|' % entry.argName1) + reason
        elif entry.type_id == EntryType.PLAYER_DONATION:
            reason = entry.reason[len('DESC: '):]
            if reason:
                reason = u'Description|' + reason
        elif entry.type_id == EntryType.CORP_WITHDRAWAL:
            reason = entry.reason[len('DESC: '):].strip('\n\t\'" ')
            reason = (u'Cash transfer by %s|' % entry.argName1) + reason
            try:
                if int(entry.ownerID1) == corp.corporationID and int(
                        entry.ownerID2) == corp.corporationID:
                    related_entry = other_entries.filter(
                        refID=entry.refID).exclude(id=entry.id)[0]
                    owner2 = related_entry.wallet.corp_wallets.get(
                        corp=corp).name
            except:
                pass
        else:
            reason = entry.reason

        wallet_name = entry.wallet.corp_wallets.get(corp=corp).name

        entries.append([
            print_time_min(entry.date),
            wallet_name,
            entry.type.refTypeName,
            owner1,
            owner2,
            print_float(entry.amount, force_sign=True),
            print_float(entry.balance),
            reason,
        ])

    return datatable_ajax_data(entries, params.sEcho, total_entries,
                               filtered_entries)