This repository was archived by the owner on Jun 7, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathviews.py
609 lines (517 loc) · 25.2 KB
/
views.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
from __future__ import unicode_literals
from django.http import Http404, JsonResponse, HttpResponse
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib.auth.decorators import permission_required
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
from django.core.cache import cache
from django.utils.translation import ugettext as _
from django.db.models import Q
from future.utils import iteritems
from eveonline.managers import EveManager
from eveonline.models import EveCharacter
from authentication.managers import AuthServicesInfo
from .models import ContactSet, StandingsRequest, StandingsRevocation, PilotStanding, CorpStanding
from .managers.standings import StandingsManager
from .managers.eveentity import EveEntityManager
from .helpers.evecharacter import EveCharacterHelper
from .helpers.writers import UnicodeWriter
from .helpers.helpers import auth_services_is_member
from .helpers.evecorporation import EveCorporation
import logging
logger = logging.getLogger(__name__)
@login_required
@permission_required('standingsrequests.request_standings')
def index_view(request):
logger.debug("Start index_view request")
characters = EveManager.get_characters_by_owner_id(request.user.id)
char_ids = [c.character_id for c in characters]
# Get all the unique corp IDs of non-member characters
corp_ids = set([int(c.corporation_id) for c in characters
if not StandingsManager.pilot_in_organisation(c.character_id)])
try:
contact_set = ContactSet.objects.latest()
except ContactSet.DoesNotExist:
return render(request, 'standings-requests/error.html', {
'error_message':
_('You must fetch contacts using the standings_update task before using the standings tool')
})
standings = contact_set.pilotstanding_set.filter(contactID__in=char_ids)
st_data = []
for c in characters:
try:
standing = standings.get(contactID=c.character_id).standing
except ObjectDoesNotExist:
standing = None
st_data.append({
'character': c,
'standing': standing,
'pendingRequest': StandingsRequest.pending_request(c.character_id),
'pendingRevocation': StandingsRevocation.pending_request(c.character_id),
'requestActioned': StandingsRequest.actioned_request(c.character_id),
'inOrganisation': StandingsManager.pilot_in_organisation(c.character_id),
})
standings = contact_set.corpstanding_set.filter(contactID__in=list(corp_ids))
corp_st_data = []
for c in corp_ids:
try:
standing = standings.get(contactID=c).standing
except ObjectDoesNotExist:
standing = None
corp_st_data.append({
'have_keys': sum([1 for a in EveCharacter.objects.filter(user=request.user).filter(corporation_id=c)
if EveManager.check_if_api_key_pair_exist(a.api_id)]),
'corp': EveCorporation.get_corp_by_id(c),
'standing': standing,
'pendingRequest': StandingsRequest.pending_request(c),
'pendingRevocation': StandingsRevocation.pending_request(c),
'requestActioned': StandingsRequest.actioned_request(c),
})
render_items = {'characters': st_data,
'corps': corp_st_data,
'authinfo': AuthServicesInfo.objects.get(user=request.user)}
return render(request, 'standings-requests/index.html', render_items)
@login_required
@permission_required('standingsrequests.request_standings')
def request_pilot_standings(request, character_id):
"""
For a user to request standings for their own pilots
"""
logger.debug("Standings request from user {0} for characterID {1}".format(request.user, character_id))
if EveManager.check_if_character_owned_by_user(character_id, request.user):
if not StandingsRequest.pending_request(character_id) and not StandingsRevocation.pending_request(character_id):
StandingsRequest.add_request(request.user, character_id, PilotStanding.get_contact_type(character_id))
else:
# Pending request, not allowed
logger.warn("Contact ID {0} already has a pending request".format(character_id))
else:
logger.warn("User {0} does not own Pilot ID {1}, forbidden".format(request.user, character_id))
return redirect('standings-requests:index')
@login_required
@permission_required('standingsrequests.request_standings')
def remove_pilot_standings(request, character_id):
"""
Handles both removing requests and removing existing standings
"""
logger.debug('remove_pilot_standings called by %s' % request.user)
if EveManager.check_if_character_owned_by_user(character_id, request.user):
if (not StandingsManager.pilot_in_organisation(character_id) and
(StandingsRequest.pending_request(character_id) or StandingsRequest.actioned_request(character_id)) and
not StandingsRevocation.pending_request(character_id)):
logger.debug('Removing standings requests for characterID {0} by user {1}'.format(character_id,
request.user))
StandingsRequest.remove_requests(character_id)
else:
standing = ContactSet.objects.latest().pilotstanding_set.filter(contactID=character_id)
if standing.exists() and standing[0].standing > 0:
# Manual revocation required
logger.debug('Creating standings revocation for characterID {0} by user {1}'.format(character_id,
request.user))
StandingsRevocation.add_revocation(character_id, PilotStanding.get_contact_type(character_id))
else:
logger.debug('No standings exist for characterID {0}'.format(character_id))
logger.debug('Cannot remove standings for pilot {0}'.format(character_id))
else:
logger.warn('User {0} tried to remove standings for characterID {1} but was not permitted'.format(
request.user, character_id))
return redirect('standings-requests:index')
@login_required
@permission_required('standingsrequests.request_standings')
def request_corp_standings(request, corp_id):
"""
For a user to request standings for their own corp
"""
logger.debug("Standings request from user {0} for corpID {1}".format(request.user, corp_id))
# Check the user has the required number of member keys for the corporation
if StandingsManager.all_corp_apis_recorded(corp_id, request.user):
if not StandingsRequest.pending_request(corp_id) and not StandingsRevocation.pending_request(corp_id):
StandingsRequest.add_request(request.user, corp_id, CorpStanding.get_contact_type(corp_id))
else:
# Pending request, not allowed
logger.warn("Contact ID {0} already has a pending request".format(corp_id))
else:
logger.warn("User {0} does not have enough keys for corpID {1}, forbidden".format(request.user, corp_id))
return redirect('standings-requests:index')
@login_required
@permission_required('standingsrequests.request_standings')
def remove_corp_standings(request, corp_id):
"""
Handles both removing corp requests and removing existing standings
"""
logger.debug('remove_corp_standings called by %s' % request.user)
# Need all corp APIs recorded to "own" the corp
st_req = get_object_or_404(StandingsRequest, contactID=corp_id)
if st_req.user == request.user:
if ((StandingsRequest.pending_request(corp_id) or StandingsRequest.actioned_request(corp_id)) and
not StandingsRevocation.pending_request(corp_id)):
logger.debug('Removing standings requests for corpID {0} by user {1}'.format(corp_id,
request.user))
StandingsRequest.remove_requests(corp_id)
else:
standing = ContactSet.objects.latest().corpstanding_set.filter(contactID=corp_id)
if standing.exists() and standing[0].standing > 0:
# Manual revocation required
logger.debug('Creating standings revocation for corpID {0} by user {1}'.format(corp_id,
request.user))
StandingsRevocation.add_revocation(corp_id, CorpStanding.get_contact_type(corp_id))
else:
logger.debug('No standings exist for corpID {0}'.format(corp_id))
logger.debug('Cannot remove standings for pilot {0}'.format(corp_id))
else:
logger.warn('User {0} tried to remove standings for corpID {1} but was not permitted'.format(
request.user, corp_id))
return redirect('standings-requests:index')
####################
# Management views #
####################
@login_required
@permission_required('standingsrequests.view')
def view_pilots_standings(request):
logger.debug('view_pilot_standings called by %s' % request.user)
try:
last_update = ContactSet.objects.latest().date
except ObjectDoesNotExist:
last_update = None
return render(request, 'standings-requests/view_pilots.html', {'lastUpdate': last_update})
@login_required
@permission_required('standingsrequests.view')
def view_pilots_standings_json(request):
logger.debug('view_pilot_standings_json called by %s' % request.user)
contacts = ContactSet.objects.latest()
def get_pilots():
pilots = []
for p in contacts.pilotstanding_set.all().order_by('-standing'):
char = EveManager.get_character_by_id(p.contactID)
main = None
is_member = False
if char:
try:
auth = AuthServicesInfo.objects.get(user=char.user)
main = EveManager.get_character_by_id(auth.main_char_id)
is_member = auth_services_is_member(auth)
except ObjectDoesNotExist:
pass
else:
# Wondering why this view is slow? Its doing API calls here probably.
char = EveCharacterHelper(p.contactID)
pilot = {
'character_id': p.contactID,
'character_name': p.name,
'corporation_id': char.corporation_id if char else None,
'corporation_name': char.corporation_name if char else None,
'corporation_ticker': char.corporation_ticker if char else None,
'alliance_id': char.alliance_id if char else None,
'alliance_name': char.alliance_name if char else None,
'api_key': True if len(char.api_id if char else "") > 0 else False,
'member': is_member,
'main_character_ticker': main.corporation_ticker if main else None,
'standing': p.standing,
'labels': [l.name for l in p.labels.all()]
}
try:
pilot['main_character_name'] = main.character_name if main else char.main_character.character_name
except AttributeError:
pilot['main_character_name'] = None
pilots.append(pilot)
return pilots
# Cache result for 10 minutes, with a large number of standings this view can be very CPU intensive
pilots = cache.get_or_set('standings_requests_view_pilots_standings_json', get_pilots, timeout=60*10)
return JsonResponse(pilots, safe=False)
@login_required
@permission_required('standingsrequests.download')
def download_pilot_standings(request):
logger.info('download_pilot_standings called by %s' % request.user)
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="standings.csv"'
writer = UnicodeWriter(response)
contacts = ContactSet.objects.latest()
writer.writerow([
'character_id',
'character_name',
'corporation_id',
'corporation_name',
'corporation_ticker',
'alliance_id',
'alliance_name',
'api_key',
'member',
'main_character_name',
'main_character_ticker',
'standing',
'labels',
])
for p in contacts.pilotstanding_set.all().order_by('-standing'):
char = EveManager.get_character_by_id(p.contactID)
main = ''
is_member = False
if char:
try:
auth = AuthServicesInfo.objects.get(user=char.user)
main = EveManager.get_character_by_id(auth.main_char_id)
is_member = auth_services_is_member(auth)
except ObjectDoesNotExist:
pass
else:
char = EveCharacterHelper(p.contactID)
try:
main_character_name = main.character_name if main else char.main_character.character_name
except AttributeError:
main_character_name = ''
pilot = [
p.contactID,
p.name,
char.corporation_id if char else '',
char.corporation_name if char else '',
char.corporation_ticker if char else '',
char.alliance_id if char else '',
char.alliance_name if char else '',
True if len(char.api_id if char else "") > 0 else False,
is_member,
main_character_name,
main.corporation_ticker if main else '',
p.standing,
', '.join([l.name for l in p.labels.all()])
]
writer.writerow([str(v) if v is not None else '' for v in pilot])
return response
@login_required
@permission_required('standingsrequests.view')
def view_groups_standings(request):
logger.debug('view_group_standings called by %s' % request.user)
try:
last_update = ContactSet.objects.latest().date
except ObjectDoesNotExist:
last_update = None
return render(request, 'standings-requests/view_groups.html', {'lastUpdate': last_update})
@login_required
@permission_required('standingsrequests.view')
def view_groups_standings_json(request):
logger.debug('view_pilot_standings_json called by %s' % request.user)
contacts = ContactSet.objects.latest()
corps = []
for p in contacts.corpstanding_set.all().order_by('-standing'):
corps.append({
'corporation_id': p.contactID,
'corporation_name': p.name,
'standing': p.standing,
'labels': [l.name for l in p.labels.all()]
})
alli = []
for p in contacts.alliancestanding_set.all().order_by('-standing'):
alli.append({
'alliance_id': p.contactID,
'alliance_name': p.name,
'standing': p.standing,
'labels': [l.name for l in p.labels.all()]
})
return JsonResponse({'corps': corps, 'alliances': alli}, safe=False)
###################
# Manage requests #
###################
@login_required
@permission_required('standingsrequests.affect_standings')
def manage_standings(request):
logger.debug('manage_standings called by %s' % request.user)
return render(request, 'standings-requests/manage.html')
@login_required
@permission_required('standingsrequests.affect_standings')
def manage_get_requests_json(request):
logger.debug('manage_get_requests_json called by %s' % request.user)
reqs = StandingsRequest.objects.filter(Q(actionBy=None) & Q(effective=False)).order_by('requestDate')
response = []
for r in reqs:
# Dont forget that contact requests aren't strictly ALWAYS pilots (at least can potentially be corps/alliances)
is_member = False
api_key = False
try:
auth = AuthServicesInfo.objects.get(user=r.user)
main = EveManager.get_character_by_id(auth.main_char_id)
is_member = auth_services_is_member(auth)
except ObjectDoesNotExist:
pass
pilot = None
corp = None
if PilotStanding.is_pilot(r.contactType):
pilot = EveManager.get_character_by_id(r.contactID)
if pilot:
api_key = EveManager.check_if_api_key_pair_exist(pilot.api_id)
else:
pilot = EveCharacterHelper(r.contactID)
elif CorpStanding.is_corp(r.contactType):
corp = EveCorporation.get_corp_by_id(r.contactID)
response.append({
'contact_id': r.contactID,
'contact_name': pilot.character_name if pilot else corp.corporation_name if corp else None,
'corporation_id': pilot.corporation_id if pilot else corp.corporation_id if corp else None,
'corporation_name': pilot.corporation_name if pilot else corp.corporation_name if corp else None,
'corporation_ticker': pilot.corporation_ticker if pilot else corp.ticker if corp else None,
'alliance_id': pilot.alliance_id if pilot else None,
'alliance_name': pilot.alliance_name if pilot else None,
'api_key': api_key if pilot else
StandingsManager.all_corp_apis_recorded(corp.corporation_id, r.user) if corp else False,
'member': is_member,
'main_character_name': main.character_name if main else None,
'main_character_ticker': main.corporation_ticker if main else None,
})
return JsonResponse(response, safe=False)
@login_required
@permission_required('standingsrequests.affect_standings')
def manage_requests_write(request, contact_id):
logger.debug('manage_requests_write called by %s' % request.user)
if request.method == "PUT":
reqs = StandingsRequest.objects.filter(contactID=contact_id)
actioned = 0
for r in reqs:
r.mark_standing_actioned(request.user)
actioned += 1
if actioned > 0:
return JsonResponse({}, status=204)
else:
return Http404
elif request.method == "DELETE":
StandingsRequest.remove_requests(contact_id)
# TODO: Notify user
# TODO: Error handling
return JsonResponse({}, status=204)
else:
return Http404
@login_required
@permission_required('standingsrequests.affect_standings')
def manage_get_revocations_json(request):
logger.debug('manage_get_revocations_json called by %s' % request.user)
reqs = StandingsRevocation.objects.filter(Q(actionBy=None) & Q(effective=False)).order_by('requestDate')
response = []
for r in reqs:
# Dont forget that contact requests aren't strictly ALWAYS pilots (at least can potentially be corps/alliances)
is_member = False
api_key = False
pilot = None
corp = None
corp_user = None
main = None
if PilotStanding.is_pilot(r.contactType):
pilot = EveManager.get_character_by_id(r.contactID)
if pilot:
api_key = EveManager.check_if_api_key_pair_exist(pilot.api_id)
else:
pilot = EveCharacterHelper(r.contactID)
elif CorpStanding.is_corp(r.contactType):
corp = EveCorporation.get_corp_by_id(r.contactID)
user_election = {}
# Figure out which user has the most APIs for this corp, if any
for c in EveCharacter.objects.filter(corporation_id=r.contactID):
# get_or_set type increment
user_election[c.user.pk] = 1 + user_election.get(c.user.pk, 0)
if user_election:
# Py2 compatible??
corp_user = User.objects.get(pk=max(user_election.keys(), key=(lambda key: user_election[key])))
if pilot or corp_user:
# Get member details if we found a user
try:
auth = AuthServicesInfo.objects.get(user=pilot.user if pilot else corp_user)
main = EveManager.get_character_by_id(auth.main_char_id)
is_member = auth_services_is_member(auth)
except ObjectDoesNotExist:
pass
revoke = {
'contact_id': r.contactID,
'contact_name': pilot.character_name if pilot else corp.corporation_name if corp else None,
'corporation_id': pilot.corporation_id if pilot else corp.corporation_id if corp else None,
'corporation_name': pilot.corporation_name if pilot else corp.corporation_name if corp else None,
'corporation_ticker': pilot.corporation_ticker if pilot else corp.ticker if corp else None,
'alliance_id': pilot.alliance_id if pilot else None,
'alliance_name': pilot.alliance_name if pilot else None,
'api_key': api_key if pilot else
StandingsManager.all_corp_apis_recorded(corp.corporation_id, corp_user) if corp and corp_user else False,
'member': is_member,
'main_character_name': main.character_name if main else None,
'main_character_ticker': main.corporation_ticker if main else None,
}
try:
revoke['main_character_name'] = main.character_name if main else pilot.main_character.character_name
except AttributeError:
revoke['main_character_name'] = None
response.append(revoke)
return JsonResponse(response, safe=False)
@login_required
@permission_required('standingsrequests.affect_standings')
def manage_revocations_write(request, contact_id):
logger.debug('manage_revocations_write called by %s' % request.user)
if request.method == "PUT":
reqs = StandingsRevocation.objects.filter(contactID=contact_id)
actioned = 0
for r in reqs:
r.mark_standing_actioned(request.user)
actioned += 1
if actioned > 0:
return JsonResponse({}, status=204)
else:
return Http404
elif request.method == "DELETE":
StandingsRevocation.objects.filter(contactID=contact_id).delete()
# TODO: Error handling
return JsonResponse({}, status=204)
else:
return Http404
@login_required
@permission_required('standingsrequests.affect_standings')
def manage_revocations_undo(request, contact_id):
logger.debug('manage_revocations_undo called by %s' % request.user)
if StandingsRevocation.objects.filter(contactID=contact_id).exists():
owner = EveEntityManager.get_owner_from_character_id(contact_id)
if owner is None:
return JsonResponse({'Success': False, 'Message': 'Cannot find an owner for that contact ID'}, status=404)
result = StandingsRevocation.undo_revocation(contact_id, owner)
if result:
return JsonResponse({}, status=204)
return JsonResponse({'Success': False, 'Message': 'Cannot find a revocation for that contact ID'}, status=404)
@login_required
@permission_required('standingsrequests.affect_standings')
def view_active_requests(request):
return render(request, 'standings-requests/requests.html')
@login_required
@permission_required('standingsrequests.affect_standings')
def view_active_requests_json(request):
reqs = StandingsRequest.objects.all().order_by('requestDate')
response = []
for r in reqs:
# Dont forget that contact requests aren't strictly ALWAYS pilots (at least can potentially be corps/alliances)
is_member = False
api_key = False
try:
auth = AuthServicesInfo.objects.get(user=r.user)
main = EveManager.get_character_by_id(auth.main_char_id)
is_member = auth_services_is_member(auth)
except ObjectDoesNotExist:
pass
pilot = None
corp = None
if PilotStanding.is_pilot(r.contactType):
pilot = EveManager.get_character_by_id(r.contactID)
if pilot:
api_key = EveManager.check_if_api_key_pair_exist(pilot.api_id)
else:
pilot = EveCharacterHelper(r.contactID)
elif CorpStanding.is_corp(r.contactType):
corp = EveCorporation.get_corp_by_id(r.contactID)
response.append({
'contact_id': r.contactID,
'contact_name': pilot.character_name if pilot else corp.corporation_name if corp else None,
'corporation_id': pilot.corporation_id if pilot else corp.corporation_id if corp else None,
'corporation_name': pilot.corporation_name if pilot else corp.corporation_name if corp else None,
'corporation_ticker': pilot.corporation_ticker if pilot else corp.ticker if corp else None,
'alliance_id': pilot.alliance_id if pilot else None,
'alliance_name': pilot.alliance_name if pilot else None,
'api_key': api_key if pilot else
StandingsManager.all_corp_apis_recorded(corp.corporation_id, r.user) if corp else False,
'member': is_member,
'main_character_name': main.character_name if main else None,
'main_character_ticker': main.corporation_ticker if main else None,
'actioned': r.actionBy is not None,
'effective': r.effective,
'is_corp': CorpStanding.is_corp(r.contactType),
'is_pilot': PilotStanding.is_pilot(r.contactType),
'action_by': r.actionBy.username if r.actionBy is not None else None,
})
return JsonResponse(response, safe=False)