ekkli-maps / maps / views.py

import logging
import datetime
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User, AnonymousUser
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.utils import simplejson
from google.appengine.api import channel
from common.gravatar import get_uri
from common.models import UserChannel
from django.template.context import RequestContext
from filetransfers.api import prepare_upload
from maps.forms import StoryForm, UserProfileForm, OpinionForm
from maps.models import Map, Story, Answer, Opinion, Approval, GroupProfile, StoryType, MapTemplate, UserProfile
from xml.etree import ElementTree as et
from django.utils.translation import ugettext as _
from upload.forms import UploadForm


def dthandler(obj):
    return obj.isoformat() if isinstance(obj, datetime.datetime) else None


@login_required 
def dashboard(request):
    user = request.user
    return render_to_response('dashboard.html', locals())


def create_map(request, group_profile, map_template,release_name=None,deliverable_name=None):
    map = Map()
    name = request.POST.get("name", _("Untitled"))
    if release_name:
        map.title = "%s - %s - %s" % (release_name,deliverable_name,name)
    else:
        map.title = name
    map.group_profile = group_profile
    map.initiator = request.user
    map.release=release_name
    map.save()
    if map_template:
        template_entries = map_template.template_entries.all()
        for entry in template_entries:
            story = Story()
            story.title = entry.title
            story.by = request.user
            story.map = map
            story.story_type = entry.story_type
            story.save()
    return map


@login_required
def map(request, map_id=None):
    # if no id given, create a new map, using the default template of the current user's group
    if map_id:
        map = Map.objects.get(id=map_id)
    else:
        user = request.user

        user_profile = user.profile.all()[0]
        group_profile = user_profile.group_profile

        if "template" in request.POST and request.POST["template"] != "-1":
            map_template = MapTemplate.objects.get(id=request.POST["template"])
        else:
#            map_template = group_profile.default_template
            map_template = None

        map = create_map(request,group_profile, map_template)
#        return HttpResponseRedirect(reverse("view_map", map_id=map.id))
        return HttpResponseRedirect("/map/%d/" % map.id)

    title = map.title
    return render_to_response('map.html', locals(), context_instance=RequestContext(request))


def get_map_data(request, map_id):
    try:
        map = Map.objects.get(id=map_id).to_dict()
    except:
        map = {}

    stories_dict = [story.to_dict() for story in Story.objects.filter(map=map_id).order_by('ordinal')]
    answer_dict = [answer.to_dict() for answer in Answer.objects.filter(map=map_id)]
    opinions_dict = [opinion.to_dict() for opinion in Opinion.objects.filter(map=map_id)]
    approvals_dict = [approvals.to_dict() for approvals in Approval.objects.filter(map=map_id)]
    result = {
        "map": map,
        "stories": stories_dict,
        "answers": answer_dict,
        "opinions": opinions_dict,
        "approvals": approvals_dict,
        }
    resp = HttpResponse(simplejson.dumps(result, default=dthandler))
    resp["Access-Control-Allow-Origin"] = "*"
    resp["Access-Control-Allow-Headers"] = "Content-type"
    return resp


def get_map_svg(request, map_id):
    map = Map.objects.get(id=map_id)
    stories = map.stories.all().order_by('ordinal')
    doc = et.Element('svg', width='300', height='40', version='1.1', xmlns='http://www.w3.org/2000/svg')
    pg = et.SubElement(doc, "g", id="map_parent", transform="scale(0.3 0.3)")
    g = et.SubElement(pg, "g", id="map", transform="translate(0 55)")
    et.SubElement(g, 'path',
                  style="fill:none;stroke:#0644A3;stroke-width:10;stroke-linecap:round;stroke-linejoin:miter;stroke-opacity:1;stroke-miterlimit:4;stroke-dasharray:none"
                  ,
                  d="M60 0 l%d 0" % ((len(stories)-1)*100),
                  stroke="black",

                  id="path2924")
    x = 60
    for story in stories:
        params = {
            "cx": str(x),
            "cy": '0',
            "r": '15',
            "fill": 'white',
            "stroke": 'black',
            "stroke-width": '5'
        }
        if story.is_approved:
            params["style"] = "fill:#1dc43a;fill-opacity:1"
        elif story.is_overdue():
            params["style"] = "fill:red;fill-opacity:1"
        et.SubElement(g, 'circle', attrib=params)
        text = et.SubElement(g, 'text', id="story-text-277",
                             style="font-size:16px;font-style:normal;font-weight:normal;fill:#000000;fill-opacity:1;stroke:none;font-family:Bitstream Vera Sans",
                             x=str(x - 30),
                             y="-50")
        y = -40
        s = story.title
        arr = s.split(" ")
        for s in arr[:2]:
            ts = et.SubElement(text, 'tspan', id="story-text-277",
                               style="text-align:center;text-anchor:middle;font-weight:bold;-inkscape-font-specification:Bitstream Vera Sans Bold;fill:#000080",
                               x=str(x),
                               y=str(y))
            ts.text = s
            y = y+15
        x = x + 100
    svg_str = et.tostring(doc)
    return HttpResponse(svg_str, content_type="image/svg+xml")


def message_handler(request):
    client_id = request.user.email
    map_updated = False

    if request.POST:
        # GET THE PARAMETERS
        json = request.POST.get("model_json", "{}")
        entity_type = request.POST.get("entity_type", "story")
        method = request.POST.get("method", "create")
        cid = request.POST.get("cid", "")

        logging.info(json)

        json_model = simplejson.loads(json)

        if not json_model.get("story_type_id", None) and json_model.get("story_type_name", None):
            story_type = get_object_or_404(StoryType, name=json_model["story_type_name"])
            json_model["story_type_id"] = story_type.id

        # if received entity id, look it up, else create new

        ret_dict = {}

        if entity_type == "story":


            if method == "delete":
                story = get_object_or_404(Story, id=json_model["id"])
                ret_dict = story.to_dict()
                answers = story.answers.all()
                answers.delete()
                story.delete()
            else:
                if "id" in json_model:
                    story = get_object_or_404(Story, id=json_model["id"])
                else:
                    story = Story()
                story.title = json_model["title"]
                story.map_id = json_model["map_id"]
                story.story_type_id = json_model["story_type_id"]
                if "content" in json_model:
                    story.content = json_model["content"]
                if "image_url" in json_model:
                    story.image_url = json_model["image_url"]
                if "schedule_date" in json_model and json_model["schedule_date"] != "":
                    if "T" in json_model["schedule_date"]:
                        json_model["schedule_date"] = json_model["schedule_date"][:json_model["schedule_date"].find("T")]
                    story.schedule_date = json_model["schedule_date"]
                else:
                    story.schedule_date = None
                story.by_id = request.user.id
                if "ordinal" in json_model and json_model["ordinal"]:
                    story.ordinal = json_model["ordinal"]
                if "is_approved" in json_model:
                    story.is_approved = json_model["is_approved"]
                story.save()
                map_updated = True
                ret_dict = story.to_dict()
        elif entity_type == "answer":

            if method == "delete":
                answer = get_object_or_404(Answer, id=json_model["id"])
                ret_dict = answer.to_dict()
                answer.delete()
            else:
                if "id" in json_model:
                    answer = get_object_or_404(Answer, id=json_model["id"])
                else:
                    answer = Answer()
                answer.map_id = json_model["map_id"]
                answer.story_id = json_model["story_id"]
                answer.answer_type = json_model["answer_type"]
                answer.text = json_model.get("text", None)
                answer.by_id = request.user.id
                answer.web_link = json_model.get("web_link", None)
                answer.media_link = json_model.get("media_link", None)
                answer.save()
                map_updated = True
                ret_dict = answer.to_dict()

        ret_dict["entity_type"] = entity_type
        ret_dict["method"] = method
        ret_dict["cid"] = cid
        json = simplejson.dumps(ret_dict, default=dthandler)

        logging.info("%" * 100)
        if map_updated:
            map = get_object_or_404(Map, id=json_model["map_id"])
            logging.info("Updating map %s" % map.title)
            map.save()
            logging.info("%" * 100)

        # SEND THE MESSAGE TO ALL THE CONNECTED USERS
        logging.info("*" * 80)
        logging.info("Sending to users: " + json)
        logging.info("z" * 80)
        user_channels = UserChannel.objects.filter(connected = True)
        logging.info("There are %d connected users" % len(user_channels))
        for user_channel in user_channels:
            logging.info("Sending message to user: " + user_channel.client_id)
            channel.send_message(user_channel.client_id, json)
            # REPLY TO THE USER REQUEST
    return HttpResponse('success')


@login_required()
def get_maps(request):
    mapsRaw = [map.to_dict() for map in Map.objects.all().order_by("-last_update")]
    maps = simplejson.dumps(mapsRaw, default=dthandler)
    return HttpResponse(maps)


@login_required()
def get_groups(request):
    mapsRaw = [group.to_dict() for group in GroupProfile.objects.all()]
    groups = simplejson.dumps(mapsRaw)
    return HttpResponse(groups)


def dialog_html(request):
    templates = MapTemplate.objects.all()
    return render_to_response('dialog_html.html', locals())


def user_picture(request, user_id):
    profile = UserProfile.objects.get(user=user_id)
    if profile.file:
        url = profile.file
    else:
        user = get_object_or_404(User, id=user_id)
        url = get_uri(user.email)
    return HttpResponseRedirect(url)

def add_story(request,map_id):
    profile = request.user.get_profile()
    if request.POST:
#        if not profile.avatar:
        profile.avatar = request.POST.get('img')
        profile.save()


    return render_to_response('story.html',locals(), context_instance=RequestContext(request))


def get_user_img(request):
    profile = request.user.get_profile()
    return HttpResponse(profile.avatar,content_type="image/JPG")

def edit_user_profile_dialog(request):

    profile = get_object_or_404(UserProfile, user=request.user)
    if request.POST:

        file_url = request.POST.get('file',None)
        if file_url:
            profile.file=file_url
            profile.save()
        return HttpResponse('succeeded')
    else:

        form = UserProfileForm(instance=profile)
        upload_form = UploadForm()
        view_url = reverse("upload.views.upload_handler")
        upload_url, upload_data = prepare_upload(request, view_url)

        return render_to_response('edit_user_profile_dialog.html', locals())

def do_story_dialog(request, d):
    upload_form = UploadForm()
    view_url = reverse("upload.views.upload_handler")
    upload_url, upload_data = prepare_upload(request, view_url)
    d.update(locals())
    return render_to_response('add_story_dialog.html', d)

def add_story_dialog(request, map_id):
    story_id = -1
    form = StoryForm()
    return do_story_dialog(request, locals())


def edit_story_dialog(request, map_id, story_id):
    story = get_object_or_404(Story, id=story_id)
    form = StoryForm(instance=story)
    return do_story_dialog(request, locals())

def do_opinion_dialog(request, d):
    upload_form = UploadForm()
    view_url = reverse("upload.views.upload_handler")
    upload_url, upload_data = prepare_upload(request, view_url)
    d.update(locals())
    return render_to_response('add_opinion_dialog.html', d)

def add_opinion_dialog(request, map_id):
    opinion_id = -1
    form = OpinionForm()
    return do_opinion_dialog(request, locals())


def edit_opinion_dialog(request, map_id, opinion_id):
    opinion = get_object_or_404(Opinion, id=opinion_id)
    form = OpinionForm(instance=opinion)
    return do_opinion_dialog(request, locals())
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.