Files @ 2d83b9633ce7
Branch filter:

Location: conntrackt/conntrackt/views.py

branko
CONNT-20: Moved out the formatter function to utils. Updated docs. Styling fixes. Added tests for the new mixin. Added tests for the formatter function. Switched to different import of models in utils in order to avoid circular imports.
   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
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
# -*- coding: utf-8 -*-
#
# Copyright (C) 2013 Branko Majic
#
# This file is part of Django Conntrackt.
#
# Django Conntrackt is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# Django Conntrackt is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# Django Conntrackt.  If not, see <http://www.gnu.org/licenses/>.
#


# Standard library imports.
from StringIO import StringIO
from zipfile import ZipFile, ZIP_DEFLATED
import json

# Django imports.
from django.contrib.auth.decorators import permission_required
from django.contrib import messages
from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse, reverse_lazy
from django.db.models import Q
from django.db.models.deletion import Collector
from django.http import HttpResponse
from django.shortcuts import render_to_response, get_object_or_404
from django.views.generic import TemplateView, DetailView, CreateView, UpdateView, DeleteView, View

# Third-party application imports.
from braces.views import MultiplePermissionsRequiredMixin, SetHeadlineMixin

# Application imports.
from .forms import ProjectForm, LocationForm, EntityForm, InterfaceForm, CommunicationForm
from .models import Project, Entity, Location, Interface, Communication
from .utils import generate_entity_iptables, generate_project_diagram


class RedirectToNextMixin(object):
    """
    View mixin that can be used for redirecting the user to URL defined through
    a GET parameter. The mixin is usable with Create/Update/Delete views that
    utilise the get_success_url() call.

    The mixin accepts the following class options:

        next_parameter - Name of the GET parameter that contains the redirect
        URL. Defaults to "next".
    """

    next_parameter = "next"

    def get_success_url(self):
        """
        Returns the success URL to which the user will be redirected.
        """

        return self.request.GET.get(self.next_parameter, super(RedirectToNextMixin, self).get_success_url())


class RelatedItemsMixin(object):
    """
    View mixin that adds related items of a referenced model object to context
    data in form of a nested list, including the reference model object as the
    first element of a list.

    The context data will be passed using the "related_items" key.

    This data can be used in the template by passing it through the
    unordered_list template tag.

    The reference object is accessed via "object" property of calling view
    (i.e. self.object).

    For more details on implementation, see:

    RelatedCollectorMixin.get_dependant_objects_representation method
    """

    def get_context_data(self, **kwargs):
        """
        Adds the related items of a reference model object to context data.

        Returns:
          Context data.
        """

        # Set the context using the parent class.
        context = super(RelatedItemsMixin, self).get_context_data(**kwargs)

        # Add to context the nested list of string representations of related
        # items.
        context["related_items"] = self.object.get_dependant_objects_representation()

        return context


class IndexView(MultiplePermissionsRequiredMixin, TemplateView):
    """
    Custom view used for rendering the index page.
    """

    template_name = 'conntrackt/index.html'

    # Required permissions.
    permissions = {
        "all": ("conntrackt.view",),
        }
    # Raise authorisation denied exception for unmet permissions.
    raise_exception = True

    def get_context_data(self, **kwargs):
        """
        Returns the context data that should be used for rendering of the
        template.

        Adds the 'projects' context object containing all of the projects
        available sorted aplhabetically by name.
        """

        # Set the context using the parent class.
        context = super(IndexView, self).get_context_data(**kwargs)

        # Store information about all projcts in context.
        context['projects'] = Project.objects.all().order_by('name')

        # Store information about all locations in context.
        context['locations'] = Location.objects.all().order_by('name')

        return context


class ProjectView(MultiplePermissionsRequiredMixin, DetailView):
    """
    Custom view for presenting the project information.
    """

    model = Project

    permissions = {
        "all": ("conntrackt.view",),
        }
    # Raise authorisation denied exception for unmet permissions.
    raise_exception = True

    def get_context_data(self, **kwargs):
        """
        Returns the context data that should be used for rendering of the
        template.

        Adds the 'location_entities' context object that contains tuples of the
        form '(location, entities)', where location is an instance of a
        Location, and entities is a query set of entities that belong to that
        particular location, and to related project.
        """

        # Set the context using the parent class.
        context = super(ProjectView, self).get_context_data(**kwargs)

        # Set-up an array that will contaion (location, entities) tuples.
        location_entities = []

        # Add the (location, entities) tuple for each location that has entities
        # belonging to the related project.
        for location in Location.objects.filter(entity__project=self.object).distinct().order_by("name"):
            entities = Entity.objects.filter(project=self.object, location=location)
            location_entities.append((location, entities))

        # Add the (location, entities) tuples to context.
        context['location_entities'] = location_entities

        # Finally return the context.
        return context


class EntityView(MultiplePermissionsRequiredMixin, DetailView):
    """
    Custom view for presenting entity information.
    """

    # Optimise the query to fetch the related data from reverse relationships.
    queryset = Entity.objects.all()
    queryset = queryset.prefetch_related('interface_set__destination_set__source__entity')
    queryset = queryset.prefetch_related('interface_set__destination_set__destination__entity')
    queryset = queryset.prefetch_related('interface_set__source_set__source__entity')
    queryset = queryset.prefetch_related('interface_set__source_set__destination__entity')

    # Required permissions.
    permissions = {
        "all": ("conntrackt.view",),
        }
    # Raise authorisation denied exception for unmet permissions.
    raise_exception = True

    def get_context_data(self, **kwargs):
        """
        Returns the context data that should be used for rendering of the
        template.

        Adds the 'entity_iptables' context object that contains full iptables
        rules generated for the entity.
        """

        # Call the parent class method.
        context = super(EntityView, self).get_context_data(**kwargs)

        # Add the rendered iptables rules to the context.
        context['entity_iptables'] = generate_entity_iptables(self.object)

        # Add the incoming and outgoing commmunication to the context.
        context["incoming_communications"] = self.object.incoming_communications()
        context["outgoing_communications"] = self.object.outgoing_communications()

        # Add the interfaces to the context.
        context["interfaces"] = self.object.interface_set.all().order_by("name")

        # Add project/location to the context.
        context["project"] = self.object.project
        context["location"] = self.object.location

        return context


@permission_required("conntrackt.view", raise_exception=True)
def entity_iptables(request, pk):
    """
    Custom view that returns response containing iptables rules generated for an
    entity.

    Makes sure to set the Content-Disposition of a response in order to
    signal the browser it should start download of this view's response
    immediately. Also sets the suggested filename for it.

    Arguments:

        pk - Primary key of the Entity object for which the rules should be
        generated.

    Returns:

        Response object that contains the iptables rules for specified entity.
    """

    # Fetch the entity, and construct the response with iptables rules as
    # content.
    entity = get_object_or_404(Entity, pk=pk)
    content = generate_entity_iptables(entity)
    response = HttpResponse(content, mimetype='text/plain')

    # Add the Content-Disposition information for the browser, telling the
    # browser to download the file with suggested filename.
    response['Content-Disposition'] = "attachment; filename=%s-iptables.conf" % entity.name.lower().replace(" ", "_")

    return response


@permission_required("conntrackt.view", raise_exception=True)
def project_iptables(request, project_id, location_id=None):
    """
    Custom view for obtaining iptables for all entities of a project or project
    location in a single ZIP file.

    Arguments:

        request - Request object.

        project_id - Unique ID of the project for whose entities the iptables
        rules should be generated.

        location_id - Optional unique ID of the project location for whose
        entities the iptables rules should be generated. Default is None, which
        means generate rules for _all_ entities in a project.

    Returns:

        Response object that contains the ZIP file and Content-Disposition
        information.
    """

    # Fetch the project.
    project = get_object_or_404(Project, pk=project_id)

    # Set-up a string IO object to which we'll write the ZIP file (in-memory).
    buff = StringIO()

    # Create a new ZIP file in-memory.
    zipped_iptables = ZipFile(buff, "w", ZIP_DEFLATED)

    # Create the response object, setting the mime type so browser could offer
    # to open the file with program as well.
    response = HttpResponse(mimetype='application/zip')

    # If specific location was specified, get the entities that are part of that
    # project location only, otherwise fetch all of the project's entities. Also
    # set-up the filename that will be suggested to the browser.
    if location_id:
        location = get_object_or_404(Location, pk=location_id)
        entities = project.entity_set.filter(location=location)
        filename = '%s-%s-iptables.zip' % (project.name.lower().replace(" ", "_"), location.name.lower().replace(" ", "_"))
    else:
        entities = project.entity_set.all()
        filename = '%s-iptables.zip' % (project.name.lower().replace(" ", "_"))

    # Render iptables rules for each entity, placing them in the ZIP archive.
    for entity in entities:
        entity_iptables = generate_entity_iptables(entity)
        zipped_iptables.writestr("%s-iptables.conf" % entity.name.lower().replace(" ", "_"), entity_iptables)

    # Close the archive, and flush the buffer.
    zipped_iptables.close()
    buff.flush()

    # Write the contents of our buffer (ZIP archive) to response content, and
    # close the IO string.
    response.write(buff.getvalue())
    buff.close()

    # Set the Content-Disposition so the browser would know it should download
    # the archive, and suggest the filename.
    response['Content-Disposition'] = 'attachment; filename="%s"' % filename

    # Finally return the response object.
    return response


class ProjectCreateView(RedirectToNextMixin, SetHeadlineMixin, MultiplePermissionsRequiredMixin, CreateView):
    """
    View for creating a new project.
    """

    model = Project
    form_class = ProjectForm
    headline = "Add new project"
    template_name = "conntrackt/create_form.html"

    # Required permissions.
    permissions = {
        "all": ("conntrackt.add_project",),
        }

    # Raise authorisation denied exception for unmet permissions.
    raise_exception = True


class ProjectUpdateView(RedirectToNextMixin, SetHeadlineMixin, MultiplePermissionsRequiredMixin, UpdateView):
    """
    View for modifying an existing project.
    """

    model = Project
    form_class = ProjectForm
    template_name = "conntrackt/update_form.html"

    # Required permissions.
    permissions = {
        "all": ("conntrackt.change_project",),
        }

    # Raise authorisation denied exception for unmet permissions.
    raise_exception = True

    def get_headline(self):
        """
        Set headline based on project name.
        """

        return "Update project %s" % self.object.name


class ProjectDeleteView(RelatedItemsMixin, RedirectToNextMixin, SetHeadlineMixin, MultiplePermissionsRequiredMixin, DeleteView):
    """
    View for deleting a project.
    """

    model = Project
    template_name = "conntrackt/delete_form.html"

    # Required permissions.
    permissions = {
        "all": ("conntrackt.delete_project",),
        }

    # Raise authorisation denied exception for unmet permissions.
    raise_exception = True

    success_url = reverse_lazy("index")

    def post(self, *args, **kwargs):
        """
        Add a success message that will be displayed to the user to confirm the
        project deletion.
        """

        messages.success(self.request, "Project %s has been removed." % self.get_object().name, extra_tags="alert alert-success")

        return super(ProjectDeleteView, self).post(*args, **kwargs)

    def get_headline(self):
        """
        Set headline based on project name.
        """

        return "Delete project %s" % self.object.name


class LocationCreateView(RedirectToNextMixin, SetHeadlineMixin, MultiplePermissionsRequiredMixin, CreateView):
    """
    View for creating a new location.
    """

    model = Location
    form_class = LocationForm
    headline = "Add new location"
    template_name = "conntrackt/create_form.html"

    # Required permissions.
    permissions = {
        "all": ("conntrackt.add_location",),
        }

    # Raise authorisation denied exception for unmet permissions.
    raise_exception = True

    success_url = reverse_lazy("index")


class LocationUpdateView(RedirectToNextMixin, SetHeadlineMixin, MultiplePermissionsRequiredMixin, UpdateView):
    """
    View for modifying an existing location.
    """

    model = Location
    form_class = LocationForm
    template_name = "conntrackt/update_form.html"

    # Required permissions.
    permissions = {
        "all": ("conntrackt.change_location",),
        }

    # Raise authorisation denied exception for unmet permissions.
    raise_exception = True

    success_url = reverse_lazy("index")

    def get_headline(self):
        """
        Set headline based on location name.
        """

        return "Update location %s" % self.object.name


class LocationDeleteView(RelatedItemsMixin, RedirectToNextMixin, SetHeadlineMixin, MultiplePermissionsRequiredMixin, DeleteView):
    """
    View for deleting a location.
    """

    model = Location
    template_name = "conntrackt/delete_form.html"

    # Required permissions.
    permissions = {
        "all": ("conntrackt.delete_location",),
        }

    # Raise authorisation denied exception for unmet permissions.
    raise_exception = True

    success_url = reverse_lazy("index")

    def post(self, *args, **kwargs):
        """
        Add a success message that will be displayed to the user to confirm the
        location deletion.
        """

        messages.success(self.request, "Location %s has been removed." % self.get_object().name, extra_tags="alert alert-success")

        return super(LocationDeleteView, self).post(*args, **kwargs)

    def get_headline(self):
        """
        Set headline based on location name.
        """

        return "Delete location %s" % self.object.name


class EntityCreateView(RedirectToNextMixin, SetHeadlineMixin, MultiplePermissionsRequiredMixin, CreateView):
    """
    View for creating a new entity.
    """

    model = Entity
    form_class = EntityForm
    headline = "Add new entity"
    template_name = "conntrackt/create_form.html"

    # Required permissions.
    permissions = {
        "all": ("conntrackt.add_entity",),
        }

    # Raise authorisation denied exception for unmet permissions.
    raise_exception = True

    def get_form(self, form_class):
        """
        Returns an instance of form that can be used by the view.

        The method will limit the project or location select inputs if request
        contained this information.
        """

        form = super(EntityCreateView, self).get_form(form_class)

        # Limit the project selection if required.
        project_id = self.request.GET.get("project", None)
        if project_id:
            form.fields["project"].queryset = Project.objects.filter(pk=project_id)
            form.fields["project"].widget.attrs["readonly"] = True

        # Limit the location selection if required.
        location_id = self.request.GET.get("location", None)
        if location_id:
            form.fields["location"].queryset = Location.objects.filter(pk=location_id)
            form.fields["location"].widget.attrs["readonly"] = True

        return form

    def get_initial(self):
        """
        Returns initial values that should be pre-selected (if they were
        specified through a GET parameter).
        """

        initial = super(EntityCreateView, self).get_initial()

        initial["project"] = self.request.GET.get("project", None)
        initial["location"] = self.request.GET.get("location", None)

        return initial


class EntityUpdateView(RedirectToNextMixin, SetHeadlineMixin, MultiplePermissionsRequiredMixin, UpdateView):
    """
    View for updating an existing entity.
    """

    model = Entity
    form_class = EntityForm
    template_name = "conntrackt/update_form.html"

    # Required permissions.
    permissions = {
        "all": ("conntrackt.change_entity",),
        }

    # Raise authorisation denied exception for unmet permissions.
    raise_exception = True

    def get_headline(self):
        """
        Set headline based on entity name.
        """

        return "Update entity %s" % self.object.name


class EntityDeleteView(RelatedItemsMixin, RedirectToNextMixin, SetHeadlineMixin, MultiplePermissionsRequiredMixin, DeleteView):
    """
    View for deleting an entity.
    """

    model = Entity
    template_name = "conntrackt/delete_form.html"

    # Required permissions.
    permissions = {
        "all": ("conntrackt.delete_entity",),
        }

    # Raise authorisation denied exception for unmet permissions.
    raise_exception = True

    def post(self, *args, **kwargs):
        """
        Add a success message that will be displayed to the user to confirm the
        entity deletion.
        """

        messages.success(self.request, "Entity %s has been removed." % self.get_object().name, extra_tags="alert alert-success")

        return super(EntityDeleteView, self).post(*args, **kwargs)

    def delete(self, *args, **kwargs):
        """
        Deletes the object. This method is overridden in order to obtain the
        project ID for success URL.

        @TODO: Fix this once Django 1.6 comes out with fix from ticket 19044.
        """

        self.success_url = reverse("project", args=(self.get_object().project.id,))

        return super(EntityDeleteView, self).delete(*args, **kwargs)

    def get_headline(self):
        """
        Set headline based on entity name.
        """

        return "Delete entity %s" % self.object.name


class InterfaceCreateView(RedirectToNextMixin, SetHeadlineMixin, MultiplePermissionsRequiredMixin, CreateView):
    """
    View for creating a new interface.
    """

    model = Interface
    form_class = InterfaceForm
    headline = "Add new interface"
    template_name = "conntrackt/create_form.html"

    # Required permissions
    permissions = {
        "all": ("conntrackt.add_interface",),
        }

    # Raise authorisation denied exception for unmet permissions.
    raise_exception = True

    def get_form(self, form_class):
        """
        Returns an instance of form that can be used by the view.

        The method will limit the entity select input if request contained this
        information.
        """

        form = super(InterfaceCreateView, self).get_form(form_class)

        # Limit the entity selection if required.
        entity_id = self.request.GET.get("entity", None)
        if entity_id:
            form.fields["entity"].queryset = Entity.objects.filter(pk=entity_id)
            form.fields["entity"].widget.attrs["readonly"] = True

        return form

    def get_initial(self):
        """
        Returns initial values that should be pre-selected (if they were
        specified through a GET parameter).
        """

        initial = super(InterfaceCreateView, self).get_initial()

        initial["entity"] = self.request.GET.get("entity", None)

        return initial

    def get_success_url(self):
        """
        Returns the URL to which the user should be redirected after an
        interface has been created.

        The URL in this case will be set to entity's details page.
        """

        return reverse("entity", args=(self.object.entity.pk,))


class InterfaceUpdateView(RedirectToNextMixin, SetHeadlineMixin, MultiplePermissionsRequiredMixin, UpdateView):
    """
    View for updating an existing interface.
    """

    model = Interface
    form_class = InterfaceForm
    template_name = "conntrackt/update_form.html"

    # Required permissions.
    permissions = {
        "all": ("conntrackt.change_interface",),
        }

    # Raise authorisation denied exception for unmet permissions.
    raise_exception = True

    def get_form(self, form_class):
        """
        Returns an instance of form that can be used by the view.

        The method will limit the entities that can be selected for the
        interface to the ones that belong to the same project as the currently
        set entity.
        """

        form = super(InterfaceUpdateView, self).get_form(form_class)

        # Limit the entities to same project.
        form.fields["entity"].queryset = Entity.objects.filter(project=self.object.entity.project)

        return form

    def get_success_url(self):
        """
        Returns the URL to which the user should be redirected after an
        interface has been updated.

        The URL in this case will be set to entity's details page.
        """

        return reverse("entity", args=(self.object.entity.pk,))

    def get_headline(self):
        """
        Set headline based on interface name.
        """

        return "Update interface %s" % self.object.name


class InterfaceDeleteView(RelatedItemsMixin, RedirectToNextMixin, SetHeadlineMixin, MultiplePermissionsRequiredMixin, DeleteView):
    """
    View for deleting an interface.
    """

    model = Interface
    template_name = "conntrackt/delete_form.html"

    # Required permissions.
    permissions = {
        "all": ("conntrackt.delete_interface",),
        }

    # Raise authorisation denied exception for unmet permissions.
    raise_exception = True

    def post(self, *args, **kwargs):
        """
        Add a success message that will be displayed to the user to confirm the
        interface deletion.
        """

        messages.success(self.request, "Interface %s has been removed." % self.get_object().name, extra_tags="alert alert-success")

        return super(InterfaceDeleteView, self).post(*args, **kwargs)

    def delete(self, *args, **kwargs):
        """
        Deletes the object. This method is overridden in order to obtain the
        entity ID for success URL.

        @TODO: Fix this once Django 1.6 comes out with fix from ticket 19044.
        """

        self.success_url = reverse("entity", args=(self.get_object().entity.id,))

        return super(InterfaceDeleteView, self).delete(*args, **kwargs)

    def get_headline(self):
        """
        Set headline based on interface name.
        """

        return "Delete interface %s" % self.object.name


class CommunicationCreateView(RedirectToNextMixin, SetHeadlineMixin, MultiplePermissionsRequiredMixin, CreateView):
    """
    View for creating a new communication.
    """

    model = Communication
    form_class = CommunicationForm
    headline = "Add new communication"
    template_name = "conntrackt/create_form.html"

    # Required permissions
    permissions = {
        "all": ("conntrackt.add_communication",),
        }

    # Raise authorisation denied exception for unmet permissions.
    raise_exception = True

    def get_form(self, form_class):
        """
        Returns an instance of form that can be used by the view.

        The method will limit the source and destination interface selection to
        interfaces belonging to the same project as provided entity ID (if any
        was provided).
        """

        form = super(CommunicationCreateView, self).get_form(form_class)

        # Limit the interface selection based on provided source entity,
        # destination entity, or project.
        entity_id = self.request.GET.get("from_entity", None) or self.request.GET.get("to_entity", None)
        project_id = self.request.GET.get("project", None)

        if project_id:
            form.fields["source"].queryset = Interface.objects.filter(entity__project=project_id)
            form.fields["destination"].queryset = Interface.objects.filter(entity__project=project_id)
        elif entity_id:
            entity = Entity.objects.get(pk=1)
            form.fields["source"].queryset = Interface.objects.filter(entity__project=entity.project)
            form.fields["destination"].queryset = Interface.objects.filter(entity__project=entity.project)

        return form

    def get_initial(self):
        """
        Returns initial values that should be pre-selected (if they were
        specified through a GET parameter).
        """

        initial = super(CommunicationCreateView, self).get_initial()

        # If source or destination entity were specified in request, fetch the
        # first interface from them and use it as initial source and destination.
        from_entity = self.request.GET.get("from_entity", None)
        to_entity = self.request.GET.get("to_entity", None)

        if from_entity:
            try:
                interface = Interface.objects.filter(entity=from_entity)[0]
                initial["source"] = interface.id
            except IndexError:
                pass

        if to_entity:
            try:
                interface = Interface.objects.filter(entity=to_entity)[0]
                initial["destination"] = interface.id
            except IndexError:
                pass

        return initial

    def get_success_url(self):
        """
        Returns the URL to which the user should be redirected after a
        communication has been created.

        The URL will either point to value provided via GET parameter "next", or
        to project page to which the communication belongs.
        """

        # We must set the success URL to something first.
        self.success_url = reverse("project", args=(self.object.source.entity.project.pk,))

        # This will override the URL if parameter "next" was provided (from
        # RedirectToNextMixin).
        success_url = super(CommunicationCreateView, self).get_success_url()

        return success_url


class CommunicationUpdateView(RedirectToNextMixin, SetHeadlineMixin, MultiplePermissionsRequiredMixin, UpdateView):
    """
    View for updating an existing communication.
    """

    model = Communication
    form_class = CommunicationForm
    template_name = "conntrackt/update_form.html"

    # Required permissions.
    permissions = {
        "all": ("conntrackt.change_communication",),
        }

    # Raise authorisation denied exception for unmet permissions.
    raise_exception = True

    def get_form(self, form_class):
        """
        Returns an instance of form that can be used by the view.

        The method will limit the source and destination interfaces that can be
        selected for the communication. Both will be limited to interfaces
        coming from entities that belong to the same project as current
        communication's source interface.
        """

        form = super(CommunicationUpdateView, self).get_form(form_class)

        project = self.object.source.entity.project

        form.fields["source"].queryset = Interface.objects.filter(entity__project=project)
        form.fields["destination"].queryset = Interface.objects.filter(entity__project=project)

        return form

    def get_success_url(self):
        """
        Returns the URL to which the user should be redirected after a
        communication has been created.

        The URL will either point to value provided via GET parameter "next", or
        to project page to which the communication belongs.
        """

        return self.request.GET.get("next", reverse("project", args=(self.object.source.entity.project.pk,)))

    def get_headline(self):
        """
        Set headline based on communication.
        """

        return "Update communication %s" % self.object


class CommunicationDeleteView(RelatedItemsMixin, RedirectToNextMixin, SetHeadlineMixin, MultiplePermissionsRequiredMixin, DeleteView):
    """
    View for deleting an communication.
    """

    model = Communication
    template_name = "conntrackt/delete_form.html"

    # Required permissions.
    permissions = {
        "all": ("conntrackt.delete_communication",),
        }

    # Raise authorisation denied exception for unmet permissions.
    raise_exception = True

    def post(self, *args, **kwargs):
        """
        Add a success message that will be displayed to the user to confirm the
        communication deletion.
        """

        messages.success(self.request, "Communication %s has been removed." % self.get_object(), extra_tags="alert alert-success")

        return super(CommunicationDeleteView, self).post(*args, **kwargs)

    def delete(self, *args, **kwargs):
        """
        Deletes the object. This method is overridden in order to obtain the
        entity ID for success URL.

        @TODO: Fix this once Django 1.6 comes out with fix from ticket 19044.
        """

        entity_id = self.request.GET.get("from_entity", None) or self.request.GET.get("to_entity", None) or self.get_object().source.entity.pk

        self.success_url = reverse("entity", args=(entity_id,))

        return super(CommunicationDeleteView, self).delete(*args, **kwargs)

    def get_headline(self):
        """
        Set headline based on communication.
        """

        return "Delete communication %s" % self.object


@permission_required("conntrackt.view", raise_exception=True)
def project_diagram(request, pk):
    """
    Custom view that returns response containing diagram of project
    communications.

    The diagram will include coloured entities, with directional lines
    connecting the source and destination end entities.

    The output format is SVG.

    Arguments:

        request - Request object.

        pk - Project ID for which the diagram should be generated.

    Returns:

        Response object that contains the project diagram rendered as SVG.
    """

    # Fetch the project.
    project = get_object_or_404(Project, pk=pk)

    # Generate the diagram.
    content = generate_project_diagram(project).create_svg()

    # Set the mime type.
    response = HttpResponse(content, mimetype='image/svg+xml')

    # Return the response object.
    return response


class SearchView(MultiplePermissionsRequiredMixin, TemplateView):
    """
    Custom view used for rendering the search (results) page.
    """

    template_name = 'conntrackt/search.html'

    # Required permissions.
    permissions = {
        "all": ("conntrackt.view",),
        }

    # Raise authorisation denied exception for unmet permissions.
    raise_exception = True

    def get_context_data(self, **kwargs):
        """
        Returns the context data that should be used for rendering of the
        template.

        Adds context objects:
          - 'entities', which is a list of entities that had the search term in
            their name or description.
          - 'projects', which is a list of entities that had the search term in
            their name or description.
          - 'search_term', which is a string of previous query that brought the
            user to page (if any). The term will be stripped from leading and
            trailing spaces/tabs.
        """

        # Set the context using the parent aclass.
        context = super(SearchView, self).get_context_data(**kwargs)

        # Retrieve the search term, and strip it if it was provided.
        search_term = self.request.GET.get("q", None)
        if search_term:
            search_term = search_term.strip()

        # Do not allow empty searches.
        if search_term == "":
            messages.error(self.request, "Search query is not allowed to be empty.", extra_tags="alert alert-error")
        # Set-up the context objects if search was sent. Otherwise empty search
        # page will be shown.
        elif search_term is not None:
            context['search_term'] = search_term
            context['entities'] = Entity.objects.search(search_term)
            context['projects'] = Project.objects.search(search_term)

        return context


class APISearchView(MultiplePermissionsRequiredMixin, View):
    """
    API view implementing search for entities and projects that match the
    provided search term.

    The output generated by the view uses JSON. The result will include a list
    of matched items, where each item is a dictionary with the following keys:

      - name (name of the matched item)
      - project (project to which the item belongs)
      - type (type of the matched item)
      - url (URL towards the matched item)
    """

    # Required permissions.
    permissions = {
        "all": ("conntrackt.view",),
        }

    # Raise authorisation denied exception for unmet permissions.
    raise_exception = True

    def get(self, request, search_term=""):
        """
        Implements response handling for a GET request.
        """

        # Retrieve the search term, and strip it if it was provided.
        if search_term:
            search_term = search_term.strip()

        # Set-up a list that will contain found items.
        items = []

        # Fetch the maximum number of items that should be returned.
        limit = int(request.GET.get("limit", 0))
        if limit < 0:
            raise ValidationError("Limit may not be a negative value.")

        # Don't perform search with empty search term.
        if search_term != "":

            # Run the search on entities and projects.
            entities = Entity.objects.search(search_term).select_related("project")
            projects = Project.objects.search(search_term)

            # If maximum number of items was provided, narrow-down the results.
            if limit > 0:
                entities = entities[:limit]
                projects = projects[:limit]

            # Add found entities.
            for entity in entities:
                items.append({"name": entity.name,
                              "project": entity.project.name,
                              "type": "entity",
                              "url": entity.get_absolute_url()})

            # Add found projects.
            for project in projects:
                items.append({"name": project.name,
                              "project": project.name,
                              "type": "project",
                              "url": project.get_absolute_url()})

        # Generate the JSON response.
        content = json.dumps(items)
        response = HttpResponse(content, mimetype="application/json")

        # Return the response.
        return response