views.py 60.8 KB
Newer Older
Janez K's avatar
Janez K committed
1 2 3 4 5 6 7 8 9 10 11
# helperji, context stvari
from django.shortcuts import render, get_object_or_404, redirect
from django.http import Http404, HttpResponse
from django.contrib import messages
from django.core import serializers
from django.utils import simplejson
from workflows.urls import *
from workflows.helpers import *
import workflows.interaction_views
import workflows.visualization_views
import sys
12
import traceback
Janez K's avatar
Janez K committed
13
from django.views.decorators.cache import never_cache
Janez K's avatar
Janez K committed
14

Janez K's avatar
Janez K committed
15 16
from jsonview.decorators import json_view

Janez K's avatar
Janez K committed
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
# modeli
from workflows.models import *
from django.contrib.auth.models import User

from workflows.utils import *

# auth fore
from django.contrib.auth.decorators import login_required

#settings
from mothra.settings import DEBUG, FILES_FOLDER

#ostalo
import os

32
import json
Janez K's avatar
Janez K committed
33
from django.db.models import Max
34

35 36 37 38
from workflows import module_importer
def setattr_local(name, value, package):
    setattr(sys.modules[__name__], name, value)
module_importer.import_all_packages_libs("views",setattr_local)
39

Janez K's avatar
Janez K committed
40 41 42 43 44 45 46 47 48 49 50 51 52
@login_required
def get_category(request):
    if request.is_ajax() or DEBUG:
        c = get_object_or_404(Category, pk=request.POST['category_id'])
        if (c.user==request.user):
            return render(request, 'category.html', {'category':c})
        else:
            return HttpResponse(status=400)
    else:
        return HttpResponse(status=400)

@login_required
def index(request):
53 54 55 56
    try:
        if request.user.userprofile.active_workflow is None:
            return redirect('new workflow')
    except:
Janez K's avatar
Janez K committed
57 58 59 60 61 62 63 64 65 66 67 68 69
        return redirect('new workflow')
    categories = Category.objects.all()
    user_categories = request.user.categories.all()
    user_widgets = request.user.widgets.filter(category=None)
    return render(request, 'index.html', {'categories':categories,'user':request.user,'user_categories':user_categories,'user_widgets':user_widgets})

@login_required
def new_workflow(request):
    w = Workflow()
    w.user = request.user
    w.save()
    request.user.userprofile.active_workflow = w
    request.user.userprofile.save()
70
    return redirect('editor')
Janez K's avatar
Janez K committed
71

Janez K's avatar
Janez K committed
72 73 74 75 76 77 78
@login_required
def open_workflow(request,workflow_id):
    w = get_object_or_404(Workflow, pk=workflow_id)
    if w.user == request.user:
        request.user.userprofile.active_workflow = w
        request.user.userprofile.save()
    else:
Janez K's avatar
Janez K committed
79
        return HttpResponse(status=400)
80
    return redirect('editor')
Janez K's avatar
Janez K committed
81

Janez K's avatar
Janez K committed
82 83
@login_required
def widget_progress(request):
Janez K's avatar
Janez K committed
84
    w = get_object_or_404(Widget, pk=request.POST['widget_id'])
Janez K's avatar
Janez K committed
85 86 87 88 89 90
    if w.running:
        return HttpResponse(w.progress)
    else:
        if w.progress==100:
            return HttpResponse("100")
        return HttpResponse("-1")
Janez K's avatar
Janez K committed
91

Janez K's avatar
Janez K committed
92 93 94 95 96 97 98 99 100
@login_required
def add_widget(request):
    if request.is_ajax() or DEBUG:
        if request.POST.has_key("abstractwidget_id"):
            aw = get_object_or_404(AbstractWidget, pk=request.POST['abstractwidget_id'])
            workflow = get_object_or_404(Workflow, pk=request.POST['active_workflow'])
            if (workflow.user==request.user):
                w = Widget()
                w.workflow = workflow
Janez K's avatar
Janez K committed
101 102
                w.x = int(request.POST['scrollLeft'].split(".")[0])+50
                y = int(request.POST['scrollTop'].split(".")[0])+50
Janez K's avatar
Janez K committed
103 104 105 106 107 108 109
                while workflow.widgets.filter(y=y,x=w.x).count()>0:
                    y = y + 100
                w.y = y
                w.name = aw.name
                w.abstract_widget = aw
                w.type = 'regular'
                w.save()
110 111
                inputOrder = 0
                paramOrder = 0
Janez K's avatar
Janez K committed
112
                for i in aw.inputs.all():
dejan's avatar
dejan committed
113 114
                    print(i.short_name)
                    print(aw.inputs.all())
Janez K's avatar
Janez K committed
115 116 117 118 119 120 121 122 123
                    j = Input()
                    j.name = i.name
                    j.short_name = i.short_name
                    j.description = i.description
                    j.variable = i.variable
                    j.widget = w
                    j.required = i.required
                    j.parameter = i.parameter
                    j.value = None
124 125 126 127 128 129
                    if (i.parameter):
                        paramOrder += 1
                        j.order = paramOrder
                    else:
                        inputOrder += 1
                        j.order = inputOrder
Janez K's avatar
Janez K committed
130 131 132 133 134 135 136 137 138 139 140 141
                    if not i.multi:
                        j.value = i.default
                    j.parameter_type = i.parameter_type
                    if i.multi:
                        j.multi_id = i.id
                    j.save()
                    for k in i.options.all():
                        o = Option()
                        o.name = k.name
                        o.value = k.value
                        o.input = j
                        o.save()
142
                outputOrder = 0
Janez K's avatar
Janez K committed
143 144 145 146 147 148 149
                for i in aw.outputs.all():
                    j = Output()
                    j.name = i.name
                    j.short_name = i.short_name
                    j.description = i.description
                    j.variable = i.variable
                    j.widget = w
150 151
                    outputOrder += 1
                    j.order = outputOrder
Janez K's avatar
Janez K committed
152
                    j.save()
153 154
                w.defered_outputs = w.outputs.defer("value").all()
                w.defered_inputs = w.inputs.defer("value").all()
Janez K's avatar
Janez K committed
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
                return render(request, 'widgets.html', {'widgets':[w,]})
            else:
                return HttpResponse(status=400)
        else:
            aw = get_object_or_404(Widget, pk=request.POST['copywidget_id'])
            if aw.type == 'regular':
                workflow = get_object_or_404(Workflow, pk=request.POST['active_workflow'])
                if (workflow.user==request.user):
                    w = Widget()
                    w.workflow = workflow
                    w.x = int(request.POST['scrollLeft'])+50
                    y = int(request.POST['scrollTop'])+50
                    while workflow.widgets.filter(y=y,x=w.x).count()>0:
                        y = y + 100
                    w.y = y
                    w.name = aw.name
                    w.abstract_widget = aw.abstract_widget
                    w.type = aw.type
                    w.save()
                    for i in aw.inputs.all():
                        j = Input()
                        j.name = i.name
                        j.short_name = i.short_name
                        j.description = i.description
                        j.variable = i.variable
                        j.widget = w
                        j.required = i.required
                        j.parameter = i.parameter
Janez K's avatar
Janez K committed
183
                        j.parameter_type = i.parameter_type
Janez K's avatar
Janez K committed
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
                        j.value = i.value
                        j.multi_id = i.multi_id
                        j.save()
                        for k in i.options.all():
                            o = Option()
                            o.name = k.name
                            o.value = k.value
                            o.input = j
                            o.save()
                    for i in aw.outputs.all():
                        j = Output()
                        j.name = i.name
                        j.short_name = i.short_name
                        j.description = i.description
                        j.variable = i.variable
                        j.widget = w
                        j.save()
201 202
                    w.defered_outputs = w.outputs.defer("value").all()
                    w.defered_inputs = w.inputs.defer("value").all()
Janez K's avatar
Janez K committed
203
                    return render(request, 'widgets.html', {'widgets':[w,]})
Janez K's avatar
Janez K committed
204 205 206 207 208
            elif aw.type=='subprocess':
                workflow = get_object_or_404(Workflow, pk=request.POST['active_workflow'])
                if (workflow.user==request.user):
                    widget_conversion = {}
                    input_conversion = {}
Janez K's avatar
Janez K committed
209
                    output_conversion = {}
Janez K's avatar
Janez K committed
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
                    w = Widget()
                    w.workflow = workflow
                    w.x = int(request.POST['scrollLeft'])+50
                    y = int(request.POST['scrollTop'])+50
                    while workflow.widgets.filter(y=y,x=w.x).count()>0:
                        y = y + 100
                    w.y = y
                    w.name = aw.name
                    w.abstract_widget = aw.abstract_widget
                    w.type = aw.type
                    w.save()
                    widget_conversion[aw.pk]=w.pk
                    for i in aw.inputs.all():
                        j = Input()
                        j.name = i.name
                        j.short_name = i.short_name
                        j.description = i.description
                        j.variable = i.variable
                        j.widget = w
                        j.required = i.required
                        j.parameter = i.parameter
Janez K's avatar
Janez K committed
231
                        j.parameter_type = i.parameter_type
Janez K's avatar
Janez K committed
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
                        j.value = i.value
                        j.multi_id = i.multi_id
                        j.save()
                        input_conversion[i.pk]=j.pk
                        for k in i.options.all():
                            o = Option()
                            o.name = k.name
                            o.value = k.value
                            o.input = j
                            o.save()
                    for i in aw.outputs.all():
                        j = Output()
                        j.name = i.name
                        j.short_name = i.short_name
                        j.description = i.description
                        j.variable = i.variable
                        j.widget = w
                        j.save()
                        output_conversion[i.pk]=j.pk
Janez K's avatar
Janez K committed
251
                    workflows.models.copy_workflow(aw.workflow_link, request.user, widget_conversion,input_conversion,output_conversion,w)
252 253
                    w.defered_outputs = w.outputs.defer("value").all()
                    w.defered_inputs = w.inputs.defer("value").all()
Janez K's avatar
Janez K committed
254
                    return render(request, 'widgets.html', {'widgets':[w,]})
Janez K's avatar
Janez K committed
255 256 257 258
            else:
                return HttpResponse(status=400)
    else:
        return HttpResponse(status=400)
Janez K's avatar
Janez K committed
259

Janez K's avatar
Janez K committed
260 261 262 263 264 265 266 267 268 269 270 271 272
@login_required
def save_position(request):
    if request.is_ajax() or DEBUG:
        w = get_object_or_404(Widget, pk=request.POST['widget_id'])
        if (w.workflow.user==request.user):
            w.x = request.POST['x']
            w.y = request.POST['y']
            w.save()
            return HttpResponse("Ok!")
        else:
            return HttpResponse(status=400)
    else:
        return HttpResponse(status=400)
Janez K's avatar
Janez K committed
273

Janez K's avatar
Janez K committed
274 275 276 277 278 279 280 281 282 283 284
@login_required
def add_connection(request):
    if request.is_ajax() or DEBUG:
        deleted = -1
        added = -1
        refresh = -1
        refreshworkflow = -1
        success = False
        mimetype = 'application/javascript'
        message = ""
        previousExists=False
285 286 287 288
        i = Input.objects.defer("value").get(pk=request.POST['input_id'])
        #i = get_object_or_404(Input, pk=request.POST['input_id'])
        o = Output.objects.defer("value").get(pk=request.POST['output_id'])
        #o = get_object_or_404(Output, pk=request.POST['output_id'])
Janez K's avatar
Janez K committed
289 290 291 292
        if (i.widget.workflow==o.widget.workflow and i.widget.workflow.user == request.user):
            if Connection.objects.filter(input=i).exists():
                previousExists=True
                new_c = Connection.objects.get(input=i)
293
                oldOutput = Output.objects.defer("value").get(pk=new_c.output_id)
Janez K's avatar
Janez K committed
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
                deleted=new_c.id
            else:
                new_c = Connection()
            new_c.input = i
            new_c.output = o
            new_c.workflow = i.widget.workflow
            new_c.save()
            if not checkForCycles(i.widget,i.widget):
                if previousExists:
                    new_c.output=oldOutput
                    new_c.save()
                else:
                    new_c.delete()
                success = False
                message = "Adding this connection would result in a cycle in the workflow."
                data = simplejson.dumps({'message':message,'success':success,'deleted':deleted,'added':added,'input_id':request.POST['input_id'],'output_id':request.POST['output_id']})
                return HttpResponse(data,mimetype)
            added = new_c.id
            new_c.input.widget.unfinish()
            if deleted==-1:
                if new_c.input.multi_id != 0:
                    i = new_c.input
                    j = Input()
Janez K's avatar
Janez K committed
317
                    m = i.widget.inputs.aggregate(Max('order'))
Janez K's avatar
Janez K committed
318 319 320 321 322 323 324 325 326 327
                    j.name = i.name
                    j.short_name = i.short_name
                    j.description = i.description
                    j.variable = i.variable
                    j.widget = i.widget
                    j.required = i.required
                    j.parameter = i.parameter
                    j.value = None
                    j.parameter_type = i.parameter_type
                    j.multi_id = i.multi_id
Janez K's avatar
Janez K committed
328
                    j.order = m['order__max']+1
Janez K's avatar
Janez K committed
329 330 331 332 333 334 335 336 337 338 339 340 341
                    j.save()
                    refresh = i.widget.id
                    refreshworkflow = i.widget.workflow.id
            success = True
            message = "Connection added."
            data = simplejson.dumps({'message':message,'success':success,'deleted':deleted,'added':added,'input_id':request.POST['input_id'],'output_id':request.POST['output_id'],'refresh':refresh,'refreshworkflow':refreshworkflow})
            return HttpResponse(data,mimetype)
        else:
            message = "Cannot connect widgets from different workflows."
            data = simplejson.dumps({'message':message,'success':success,'deleted':deleted,'added':added,'input_id':request.POST['input_id'],'output_id':request.POST['output_id'],'refresh':refresh},)
            return HttpResponse(data,mimetype)
    else:
        return HttpResponse(status=400)
Janez K's avatar
Janez K committed
342

Janez K's avatar
Janez K committed
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
@login_required
def delete_connection(request):
    if request.is_ajax() or DEBUG:
        c = get_object_or_404(Connection, pk=request.POST['connection_id'])
        if (c.input.widget.workflow.user!=request.user):
            return HttpResponse(status=400)
        c.input.widget.unfinish()
        mimetype = 'application/javascript'
        refresh = -1
        refreshworkflow = -1
        already_deleted=False
        if c.input.multi_id != 0:
            #pogledamo kok jih je s tem idjem, ce je vec k en, tega pobrisemo
            if c.input.widget.inputs.filter(multi_id=c.input.multi_id).count()>1:
                refresh = c.input.widget.id
                refreshworkflow = c.input.widget.workflow.id
                c.input.delete()
                already_deleted=True
        if not already_deleted:
            c.delete()
        data = simplejson.dumps({'refresh':refresh,'refreshworkflow':refreshworkflow})
        return HttpResponse(data,mimetype)
    else:
        return HttpResponse(status=400)

@login_required
def delete_widget(request):
    if request.is_ajax() or DEBUG:
        w = get_object_or_404(Widget, pk=request.POST['widget_id'])
        w.unfinish()
Janez K's avatar
Janez K committed
373
        mimetype = 'application/javascript'
Janez K's avatar
Janez K committed
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
        refresh = []
        delete_tab = -1
        if (w.workflow.user!=request.user):
            return HttpResponse(status=400)
        connections = Connection.objects.filter(output__widget=w).filter(input__multi_id__gt=0)
        for c in connections:
            if c.input.widget.inputs.filter(multi_id=c.input.multi_id).count()>1:
                refresh.append((c.input.widget.id,c.input.widget.workflow.id))
                c.input.delete()
        if w.type=='subprocess':
            delete_tab = w.workflow_link.id
        w.delete()
        data = simplejson.dumps({'refresh':list(set(refresh)),'delete_tab':delete_tab})
        return HttpResponse(data,mimetype)
    else:
        return HttpResponse(status=400)

391 392 393 394 395 396 397 398 399 400 401
@login_required
def delete_workflow(request):
    if request.is_ajax() or DEBUG:
        w = get_object_or_404(Workflow, pk=request.GET['workflow_id'])
        if (w.user!=request.user):
            return HttpResponse(status=400)
        w.delete()
        return HttpResponse("Ok")
    else:
        return HttpResponse(status=400)

Janez K's avatar
Janez K committed
402 403 404 405 406 407 408 409 410 411 412 413 414 415
@login_required
def add_subprocess(request):
    if request.is_ajax() or DEBUG:
        workflow = get_object_or_404(Workflow, pk=request.POST['active_workflow'])
        if (workflow.user==request.user):
            new_w = Workflow()
            new_w.name = "Untitled widget"
            new_w.user = request.user
            w = Widget()
            w.workflow = workflow
            w.workflow_link = new_w
            w.x = int(request.POST['scrollLeft'])+50
            y = int(request.POST['scrollTop'])+50
            while workflow.widgets.filter(y=y,x=w.x).count()>0:
Janez K's avatar
Janez K committed
416
                y = y + 100
Janez K's avatar
Janez K committed
417 418 419 420 421 422
            w.y=y
            w.name = "Untitled widget"
            w.type = 'subprocess'
            w.save()
            new_w.widget = w
            new_w.save()
423 424
            w.defered_outputs = w.outputs.defer("value").all()
            w.defered_inputs = w.inputs.defer("value").all()
Janez K's avatar
Janez K committed
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
            return render(request, 'widgets.html', {'widgets':[w,]})
        else:
            return HttpResponse(status=400)
    else:
        return HttpResponse(status=400)

@login_required
def get_subprocess(request):
    if request.is_ajax() or DEBUG:
        widget = get_object_or_404(Widget, pk=request.POST['widget_id'])
        data = simplejson.dumps({'workflow_link':widget.workflow_link.pk,'workflow_name':widget.workflow_link.name})
        mimetype = 'application/javascript'
        return HttpResponse(data,mimetype)
    else:
        return HttpResponse(status=400)

@login_required
def add_for(request):
    success = False
    mimetype = 'application/javascript'
    message = ""
    if request.is_ajax() or DEBUG:
        workflow = get_object_or_404(Workflow, pk=request.POST['active_workflow'])
        if (workflow.user==request.user):
            if workflow.widget==None:
                message = 'The for widgets can only be put in a subprocess.'
                data = simplejson.dumps({'message':message,'success':success})
                return HttpResponse(data,mimetype)
            elif workflow.widgets.filter(type='for_input').count()>0:
                message = 'This subprocess already has a for loop. Try deleting it and adding it again.'
                data = simplejson.dumps({'message':message,'success':success})
Janez K's avatar
Janez K committed
456
                return HttpResponse(data,mimetype)
Janez K's avatar
Janez K committed
457
            else:
dejan's avatar
dejan committed
458
                print(workflow)
Janez K's avatar
Janez K committed
459 460 461 462 463 464 465 466 467 468 469
                for_input = Widget()
                for_input.workflow = workflow
                for_input.x=int(request.POST['scrollLeft'])+50
                y=int(request.POST['scrollTop'])+50
                while workflow.widgets.filter(y=y,x=for_input.x).count()>0:
                    y = y + 100
                for_input.y=y
                for_input.name = 'For input'
                for_input.type = 'for_input'
                for_input.save()
                output = Output()
dejan's avatar
dejan committed
470
                output.name = 'For input' # subproces inner input
Janez K's avatar
Janez K committed
471 472 473 474 475 476
                output.short_name = 'for'
                output.variable = 'For'
                output.widget = for_input
                output.save()
                input = Input()
                input.widget = workflow.widget
dejan's avatar
dejan committed
477
                input.name = 'For input' # subproces input
Janez K's avatar
Janez K committed
478 479 480 481 482 483
                input.short_name = 'for'
                input.variable = 'For'
                input.inner_output = output
                input.save()
                output.outer_input = input
                output.save()
Janez K's avatar
Janez K committed
484

Janez K's avatar
Janez K committed
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
                widget = Widget()
                widget.workflow = workflow
                widget.x=int(request.POST['scrollLeft'])+200
                widget.y=int(request.POST['scrollTop'])+50
                widget.name = 'For output'
                widget.type = 'for_output'
                widget.save()
                input = Input()
                input.name = 'For output'
                input.short_name = 'for'
                input.variable = 'For'
                input.widget = widget
                input.save()
                output = Output()
                output.widget = workflow.widget
                output.name = 'For output'
                output.short_name = 'for'
                output.variable = 'For'
                output.inner_input = input
                output.save()
                input.outer_output = output
                input.save()
507 508 509
                for_input.defered_outputs = for_input.outputs.defer("value").all()
                for_input.defered_inputs = for_input.inputs.defer("value").all()
                widget.defered_outputs = widget.outputs.defer("value").all()
Janez K's avatar
Janez K committed
510 511
                widget.defered_inputs = widget.inputs.defer("value").all()
                return render(request, 'widgets.html', {'widgets':[for_input,widget]})
Janez K's avatar
Janez K committed
512 513 514
        else:
            return HttpResponse(status=400)
    else:
Janez K's avatar
Janez K committed
515 516
        return HttpResponse(status=400)

dejan's avatar
dejan committed
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
@login_required
def add_cv(request):
    success = False
    mimetype = 'application/javascript'
    message = ""
    if request.is_ajax() or DEBUG:
        workflow = get_object_or_404(Workflow, pk=request.POST['active_workflow'])
        if (workflow.user==request.user):
            """Check if the workflow is from the user that has send the request"""
            if workflow.widget==None:
                message = 'The for widgets can only be put in a subprocess.'
                data = simplejson.dumps({'message':message,'success':success})
                return HttpResponse(data,mimetype)
            elif workflow.widgets.filter(type='for_input').count()>0:
                message = 'This subprocess already has a for loop. Try deleting it and adding it again.'
                data = simplejson.dumps({'message':message,'success':success})
                return HttpResponse(data,mimetype)
            elif workflow.widgets.filter(type='cv_input').count()>0:
                message = 'This subprocess already has cross validation. Try deleting it and adding it again.'
                data = simplejson.dumps({'message':message,'success':success})
                return HttpResponse(data,mimetype)
            else:
                # input: data
                cv_input_data = Widget()
                cv_input_data.workflow = workflow
                cv_input_data.x=int(request.POST['scrollLeft'])+50
                y=int(request.POST['scrollTop'])+50
                while workflow.widgets.filter(y=y,x=cv_input_data.x).count()>0:
                    y = y + 100
                cv_input_data.y=y
                cv_input_data.name = 'cv input'
                cv_input_data.type = 'cv_input'
                cv_input_data.save()

                output = Output()
                output.name = 'cv input data'
                output.short_name = 'trn' # subproces inner input
554 555
                output.variable = 'TRAIN'
                output.order = 1
dejan's avatar
dejan committed
556 557 558 559 560 561 562 563
                output.widget = cv_input_data
                output.save()
                input = Input()
                input.widget = workflow.widget
                input.name = 'cv input data'
                input.short_name = 'dat'  # subproces input
                input.variable = 'CVD'
                input.inner_output = output
564
                input.order = 1
dejan's avatar
dejan committed
565 566 567 568 569 570 571 572
                input.save()
                output.outer_input = input
                output.save()


                output = Output()
                output.name = 'cv input data'
                output.short_name = 'tst' # subproces inner input
573 574
                output.variable = 'TEST'
                output.order = 2
dejan's avatar
dejan committed
575 576 577 578 579 580 581 582
                output.widget = cv_input_data
                output.save()
                input = Input()
                input.widget = workflow.widget
                input.name = 'cv input folds'
                input.short_name = 'cvf'
                input.variable = 'CVF'
                input.inner_output = output
583
                input.order = 2
dejan's avatar
dejan committed
584 585 586 587 588 589 590
                input.save()
                output.outer_input = input
                output.save()

                output = Output()
                output.name = 'cv input data'
                output.short_name = 'sed' # subproces inner input
591 592
                output.variable = 'SEED'
                output.order = 3
dejan's avatar
dejan committed
593 594 595 596 597 598 599
                output.widget = cv_input_data
                output.save()
                input = Input()
                input.widget = workflow.widget
                input.name = 'cv input seed'
                input.short_name = 'sed'
                input.variable = 'CVS'
600
                input.order = 3
dejan's avatar
dejan committed
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
                input.inner_output = output
                input.save()
                output.outer_input = input
                output.save()

                # output
                widget = Widget()
                widget.workflow = workflow
                widget.x=int(request.POST['scrollLeft'])+200
                widget.y=int(request.POST['scrollTop'])+50
                widget.name = 'cv output'
                widget.type = 'cv_output'
                widget.save()
                input = Input()
                input.name = 'cv output'
                input.short_name = 'res'
                input.variable = 'Res'
                input.widget = widget
                input.save()
                output = Output()
                output.widget = workflow.widget
                output.name = 'cv output'
                output.short_name = 'res'
                output.variable = 'Res'
                output.inner_input = input
                output.save()
                input.outer_output = output
                input.save()
                cv_input_data.defered_outputs = cv_input_data.outputs.defer("value").all()
                cv_input_data.defered_inputs = cv_input_data.inputs.defer("value").all()
                widget.defered_outputs = widget.outputs.defer("value").all()
                widget.defered_inputs = widget.inputs.defer("value").all()
                return render(request, 'widgets.html', {'widgets':[cv_input_data,widget]})
        else:
            return HttpResponse(status=400)
    else:
        return HttpResponse(status=400)
Janez K's avatar
Janez K committed
638

Janez K's avatar
Janez K committed
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
@login_required
def add_input(request):
    success = False
    mimetype = 'application/javascript'
    message = ""
    if request.is_ajax() or DEBUG:
        workflow = get_object_or_404(Workflow, pk=request.POST['active_workflow'])
        if (workflow.user==request.user):
            if workflow.widget==None:
                message = 'The input widget can only be put in a subprocess.'
                data = simplejson.dumps({'message':message,'success':success})
                return HttpResponse(data,mimetype)
            else:
                widget = Widget()
                widget.workflow = workflow
                widget.x=int(request.POST['scrollLeft'])+50
                y = int(request.POST['scrollTop'])+50
                while workflow.widgets.filter(y=y,x=widget.x).count()>0:
Janez K's avatar
Janez K committed
657
                    y = y + 100
Janez K's avatar
Janez K committed
658 659 660 661
                widget.y=y
                widget.name = 'Input'
                widget.type = 'input'
                widget.save()
662
                variable_name = 'Input'+str(widget.pk)
Janez K's avatar
Janez K committed
663 664 665
                output = Output()
                output.name = 'Input'
                output.short_name = 'inp'
666
                output.variable = variable_name
Janez K's avatar
Janez K committed
667 668 669 670 671 672
                output.widget = widget
                output.save()
                input = Input()
                input.widget = workflow.widget
                input.name = 'Input'
                input.short_name = 'inp'
673
                input.variable = variable_name
Janez K's avatar
Janez K committed
674 675 676 677
                input.inner_output = output
                input.save()
                output.outer_input = input
                output.save()
678 679
                widget.defered_outputs = widget.outputs.defer("value").all()
                widget.defered_inputs = widget.inputs.defer("value").all()
Janez K's avatar
Janez K committed
680 681 682 683 684
                return render(request, 'widgets.html', {'widgets':[widget,]})
        else:
            return HttpResponse(status=400)
    else:
        return HttpResponse(status=400)
Janez K's avatar
Janez K committed
685

Janez K's avatar
Janez K committed
686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708
@login_required
def add_output(request):
    success = False
    mimetype = 'application/javascript'
    message = ""
    if request.is_ajax() or DEBUG:
        workflow = get_object_or_404(Workflow, pk=request.POST['active_workflow'])
        if (workflow.user==request.user):
            if workflow.widget==None:
                message = 'The output widget can only be put in a subprocess.'
                data = simplejson.dumps({'message':message,'success':success})
                return HttpResponse(data,mimetype)
            else:
                widget = Widget()
                widget.workflow = workflow
                widget.x=int(request.POST['scrollLeft'])+50
                y = int(request.POST['scrollTop'])+50
                while workflow.widgets.filter(y=y,x=widget.x).count()>0:
                    y = y + 100
                widget.y=y
                widget.name = 'Output'
                widget.type = 'output'
                widget.save()
709
                variable_name = 'Output'+str(widget.pk)
Janez K's avatar
Janez K committed
710 711 712
                input = Input()
                input.name = 'Output'
                input.short_name = 'out'
713
                input.variable = variable_name
Janez K's avatar
Janez K committed
714 715 716 717 718 719
                input.widget = widget
                input.save()
                output = Output()
                output.widget = workflow.widget
                output.name = 'Output'
                output.short_name = 'out'
720
                output.variable = variable_name
Janez K's avatar
Janez K committed
721 722 723 724
                output.inner_input = input
                output.save()
                input.outer_output = output
                input.save()
725 726
                widget.defered_outputs = widget.outputs.defer("value").all()
                widget.defered_inputs = widget.inputs.defer("value").all()
Janez K's avatar
Janez K committed
727 728 729 730
                return render(request, 'widgets.html', {'widgets':[widget,]})
        else:
            return HttpResponse(status=400)
    else:
Janez K's avatar
Janez K committed
731 732
        return HttpResponse(status=400)

Janez K's avatar
Janez K committed
733 734 735 736 737
@login_required
def synchronize_widgets(request):
    if request.is_ajax() or DEBUG:
        w = get_object_or_404(Workflow,pk=request.POST['workflow_id'])
        if (w.user==request.user):
738
            widgets = w.widgets.all()
Janez K's avatar
Janez K committed
739 740
            defered_outputs = list(Output.objects.defer("value").filter(widget__workflow=w))
            defered_inputs = list(Input.objects.defer("value").filter(widget__workflow=w))
741
            for w in widgets:
Janez K's avatar
Janez K committed
742 743
                w.defered_outputs = filter(lambda e: e.widget_id == w.id,defered_outputs)
                w.defered_inputs = filter(lambda e: e.widget_id == w.id,defered_inputs)
744
            return render(request, 'widgets.html', {'widgets':widgets})
Janez K's avatar
Janez K committed
745 746 747 748
        else:
            return HttpResponse(status=400)
    else:
        return HttpResponse(status=400)
Janez K's avatar
Janez K committed
749

Janez K's avatar
Janez K committed
750 751 752 753 754 755 756 757 758 759 760 761
@login_required
def synchronize_connections(request):
    if request.is_ajax() or DEBUG:
        mimetype = 'application/javascript'
        w = get_object_or_404(Workflow,pk=request.POST['workflow_id'])
        if (w.user==request.user):
            c = Connection.objects.filter(input__widget__workflow=w)
            data = serializers.serialize('json', c)
            return HttpResponse(data,mimetype)
        else:
            return HttpResponse(status=400)
    else:
Janez K's avatar
Janez K committed
762 763
        return HttpResponse(status=400)

Janez K's avatar
Janez K committed
764 765 766 767 768
@login_required
def get_widget(request):
    if request.is_ajax() or DEBUG:
        w = get_object_or_404(Widget, pk=request.POST['widget_id'])
        if (w.workflow.user==request.user):
769 770
            w.defered_outputs = w.outputs.defer("value").all()
            w.defered_inputs = w.inputs.defer("value").all()
Janez K's avatar
Janez K committed
771 772 773 774 775
            return render(request, 'widgets.html', {'widgets':[w,]})
        else:
            return HttpResponse(status=400)
    else:
        return HttpResponse(status=400)
Janez K's avatar
Janez K committed
776

Janez K's avatar
Janez K committed
777 778 779 780 781 782 783 784 785 786
@login_required
def get_parameters(request):
    if request.is_ajax() or DEBUG:
        w = get_object_or_404(Widget, pk=request.POST['widget_id'])
        if (w.workflow.user==request.user):
            return render(request, 'parameters.html', {'widget':w,'parameters':w.inputs.filter(parameter=True)})
        else:
            return HttpResponse(status=400)
    else:
        return HttpResponse(status=400)
Janez K's avatar
Janez K committed
787

Janez K's avatar
Janez K committed
788 789 790 791 792 793 794 795 796 797 798 799 800
@login_required
def save_parameter(request):
    if request.is_ajax() or DEBUG:
        input = get_object_or_404(Input, pk=request.POST['input_id'])
        if (input.widget.workflow.user==request.user):
            input.value = request.POST['value']
            input.save()
            input.widget.unfinish()
            return HttpResponse(status=200)
        else:
            return HttpResponse(status=400)
    else:
        return HttpResponse(status=400)
801 802 803 804 805 806 807 808 809

@login_required
def get_configuration(request):
    if request.is_ajax() or DEBUG:
        w = get_object_or_404(Widget, pk=request.POST['widget_id'])
        if (w.workflow.user==request.user):
            inputs = w.inputs.filter(parameter=False);
            parameters = w.inputs.filter(parameter=True);
            outputs = w.outputs.all();
Janez K's avatar
Janez K committed
810 811 812 813 814
            benchmark_exists = False
            for o in outputs:
                if o.variable=='clowdflows_elapsed':
                    benchmark_exists = True
            return render(request, 'configuration.html', {'widget':w,'inputs': inputs, 'parameters':parameters, 'outputs':outputs, 'benchmark_exists':benchmark_exists})
815 816 817 818
        else:
            return HttpResponse(status=400)
    else:
        return HttpResponse(status=400)
Janez K's avatar
Janez K committed
819

820
@login_required
821
def save_configuration(request):
822
    if request.is_ajax() or DEBUG:
823 824 825 826 827 828 829
        widget = get_object_or_404(Widget, pk=request.POST['widgetId'])
        if (widget.workflow.user==request.user):
            inputs =  request.POST.getlist('inputs')
            params =  request.POST.getlist('params')
            outputs = request.POST.getlist('outputs')
            changed = False
            reordered = False
830
            deletedConnections = []
831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851
            for (id, input) in enumerate(inputs):
                inp = get_object_or_404(Input, pk=input)
                id += 1
                if (inp.widget.workflow.user!=request.user):
                    return HttpResponse(status=400)
                if (inp.parameter):
                    inp.parameter = False
                    changed = True
                    inp.save()
                if (inp.order != id):
                    inp.order = id
                    reordered = True
                    inp.save()
            for (id, input) in enumerate(params):
                inp = get_object_or_404(Input, pk=input)
                id += 1
                if (inp.widget.workflow.user!=request.user):
                    return HttpResponse(status=400)
                if (not inp.parameter):
                    #need to be careful if connections are set up to this input and need to be removed
                    for c in Connection.objects.filter(input=inp):
852
                        deletedConnections.append(c.id)
853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
                        c.delete()
                    inp.parameter = True
                    changed = True
                    inp.save()
                if (inp.order != id):
                    inp.order = id
                    reordered = True
                    inp.save()
            for (id, output) in enumerate(outputs):
                out = get_object_or_404(Output, pk = output)
                id += 1
                if (out.widget.workflow.user!=request.user):
                    return HttpResponse(status=400)
                if (out.order != id):
                    out.order = id
                    reordered = True
                    out.save()
Janez K's avatar
Janez K committed
870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886
            if request.POST.get('benchmark')=='true':
                if widget.outputs.filter(variable='clowdflows_elapsed').count()==0:
                    new_o = Output()
                    new_o.widget = widget
                    new_o.variable = 'clowdflows_elapsed'
                    new_o.name = 'Elapsed time'
                    new_o.short_name = 'bmk'
                    new_o.order=99
                    new_o.save()
                changed = True
                reordered = True
            if request.POST.get('benchmark')=='false':
                o = widget.outputs.filter(variable='clowdflows_elapsed')
                if len(o)>0:
                    o.delete()
                changed = True
                reordered = True
887 888 889
            if (changed):
                widget.unfinish()

890
            data = simplejson.dumps({'changed':changed,'reordered':reordered, 'deletedConnections':deletedConnections})
891 892
            mimetype = 'application/javascript'
            return HttpResponse(data, mimetype)
893 894 895 896 897
        else:
            return HttpResponse(status=400)
    else:
        return HttpResponse(status=400)

Janez K's avatar
Janez K committed
898 899 900 901 902 903 904 905 906 907 908 909 910 911 912
@login_required
def save_designation(request):
    if request.is_ajax() or DEBUG:
        for key in request.POST:
            input = get_object_or_404(AbstractInput, pk=key)
            if request.POST[key] == "input":
                input.parameter=False
                input.save()
            elif request.POST[key] == "parameter":
                input.parameter=True
                if input.parameter_type!="checkbox":
                    input.parameter_type="text"
                input.save()
        return HttpResponse(status=200)
    else:
Janez K's avatar
Janez K committed
913 914
        return HttpResponse(status=400)

Janez K's avatar
Janez K committed
915 916 917 918 919 920 921 922 923
@login_required
def get_parameters(request):
    if request.is_ajax() or DEBUG:
        w = get_object_or_404(Widget, pk=request.POST['widget_id'])
        if (w.workflow.user==request.user):
            return render(request, 'parameters.html', {'widget':w,'parameters':w.inputs.filter(parameter=True)})
        else:
            return HttpResponse(status=400)
    else:
Janez K's avatar
Janez K committed
924 925
        return HttpResponse(status=400)

Janez K's avatar
Janez K committed
926 927 928 929 930 931 932 933 934
@login_required
def get_rename_dialog(request):
    if request.is_ajax() or DEBUG:
        w = get_object_or_404(Widget, pk=request.POST['widget_id'])
        if (w.workflow.user==request.user):
            return render(request, 'rename.html', {'widget':w})
        else:
            return HttpResponse(status=400)
    else:
Janez K's avatar
Janez K committed
935
        return HttpResponse(status=400)
Janez K's avatar
Janez K committed
936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952

@login_required
def rename_widget(request):
    if request.is_ajax() or DEBUG:
        w = get_object_or_404(Widget, pk=request.POST['widget_id'])
        if (w.workflow.user==request.user):
            w.rename(request.POST['new_name'])
            mimetype = 'application/javascript'
            workflow_link = True
            workflow_link_id = 0
            rename_inputs = []
            rename_outputs = []
            if w.type=='input':
                rename_inputs.append(w.outputs.all()[0].outer_input.id)
                rename_outputs.append(w.outputs.all()[0].id)
            if w.type=='output':
                rename_outputs.append(w.inputs.all()[0].outer_output.id)
953
                rename_inputs.append(w.inputs.all()[0].id)
Janez K's avatar
Janez K committed
954 955 956 957 958 959 960 961 962 963
            try:
                workflow_link_id = w.workflow_link.id
            except Workflow.DoesNotExist:
                workflow_link = False
            data = simplejson.dumps({'workflow_link':workflow_link,'workflow_link_id':workflow_link_id,'rename_inputs':rename_inputs,'rename_outputs':rename_outputs})
            return HttpResponse(data,mimetype)
        else:
            return HttpResponse(status=400)
    else:
        return HttpResponse(status=400)
Janez K's avatar
Janez K committed
964

Janez K's avatar
Janez K committed
965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982
@login_required
def rename_workflow(request):
    if request.is_ajax() or DEBUG:
        w = get_object_or_404(Workflow, pk=request.POST['workflow_id'])
        if (w.user==request.user):
            w.rename(request.POST['new_name'])
            w.description = request.POST['description']
            if request.POST['public']=="true":
                w.public=True
            else:
                w.public=False
            w.save()
            mimetype = 'application/javascript'
            data = simplejson.dumps({'workflow_id':w.id})
            return HttpResponse(data,mimetype)
        else:
            return HttpResponse(status=400)
    else:
Janez K's avatar
Janez K committed
983 984
        return HttpResponse(status=400)

Janez K's avatar
Janez K committed
985 986 987 988 989 990
@login_required
def run_widget(request):
    if request.is_ajax() or DEBUG:
        w = get_object_or_404(Widget, pk=request.POST['widget_id'])
        if (w.workflow.user==request.user):
            try:
991
                # find all required inputs
Janez K's avatar
Janez K committed
992 993
                multi_satisfied = {}
                for inp in w.inputs.filter(required=True,parameter=False):
994
                    if inp.connections.count()==0:
Janez K's avatar
Janez K committed
995 996 997 998 999 1000 1001 1002 1003
                        if inp.multi_id == 0:
                            raise Exception("The input "+str(inp)+" must have something connected to it in order to run.")
                        else:
                            multi_satisfied[inp.multi_id] = (str(inp),multi_satisfied.get(inp.multi_id,False))
                    elif inp.multi_id != 0:
                        multi_satisfied[inp.multi_id] = (str(inp),True)
                for mid in multi_satisfied.keys():
                    if multi_satisfied[mid][1]==False:
                        raise Exception("The input "+multi_satisfied[mid][0]+" must have something connected to it in order to run.")
Janez K's avatar
Janez K committed
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
                if w.type == 'for_input' or w.type == 'for_output':
                    raise Exception("You can't run for loops like this. Please run the containing widget.")
                output_dict = w.run(False)
                mimetype = 'application/javascript'
                if not w.abstract_widget is None:
                    if w.abstract_widget.interactive:
                        w.interaction_waiting = True
                        w.save()
                        data = simplejson.dumps({'status':'interactive','message':'Widget '+w.name+' needs your attention.','widget_id':w.id})
                    elif w.abstract_widget.visualization_view!='':
                        data = simplejson.dumps({'status':'visualize','message':'Visualizing widget '+w.name+'.','widget_id':w.id})
                    else:
                        data = simplejson.dumps({'status':'ok','message':'Widget '+w.name+' executed successfully.'})
                else:
                    data = simplejson.dumps({'status':'ok','message':'Widget '+w.name+' executed successfully.'})
1019
            except Exception,e:
Janez K's avatar
Janez K committed
1020 1021 1022 1023 1024
                mimetype = 'application/javascript'
                w.error = True
                w.running = False
                w.finished = False
                w.save()
1025

1026 1027
                print traceback.format_exc(e)

Janez K's avatar
Janez K committed
1028 1029 1030 1031
                #raise
                for o in w.outputs.all():
                    o.value=None
                    o.save()
Janez K's avatar
Janez K committed
1032
                data = simplejson.dumps({'status':'error','message':'Error occurred when trying to execute widget '+w.name+': '+str(type(e))+' '+str(e)})
Janez K's avatar
Janez K committed
1033 1034 1035 1036 1037
            return HttpResponse(data,mimetype)
        else:
            return HttpResponse(status=400)
    else:
        return HttpResponse(status=400)
Janez K's avatar
Janez K committed
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
@login_required
def run_tree(request):
    if request.is_ajax() or DEBUG:
        w = get_object_or_404(Widget, pk=request.POST['widget_id'])
        if (w.workflow.user==request.user):
            try:
                if w.type == 'for_input' or w.type == 'for_output':
                    raise Exception("You can't run for loops like this. Please run the containing widget.")
                output_dict = w.run(False)
                mimetype = 'application/javascript'
                if not w.abstract_widget is None:
                    if w.abstract_widget.interactive:
                        w.interaction_waiting = True
                        w.save()
                        data = simplejson.dumps({'status':'interactive','message':'Widget '+w.name+' needs your attention.','widget_id':w.id})
                    elif w.abstract_widget.visualization_view!='':
                        data = simplejson.dumps({'status':'visualize','message':'Visualizing widget '+w.name+'.','widget_id':w.id})
                    else:
                        data = simplejson.dumps({'status':'ok','message':'Widget '+w.name+' executed successfully.'})
                else:
                    data = simplejson.dumps({'status':'ok','message':'Widget '+w.name+' executed successfully.'})
            except Exception, e:
                mimetype = 'application/javascript'
                w.error = True
                w.running = False
                w.finished = False
                w.save()
1066
                print traceback.format_exc(e)
Janez K's avatar
Janez K committed
1067
                #raise
1068 1069 1070
                for o in w.outputs.all():
                    o.value=None
                    o.save()
Janez K's avatar
Janez K committed
1071
                data = simplejson.dumps({'status':'error','message':'Error occurred when trying to execute widget '+w.name+': '+str(type(e))+' '+str(e)})
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
            return HttpResponse(data,mimetype)
        else:
            return HttpResponse(status=400)
    else:
        return HttpResponse(status=400)


@login_required
def reset_widget(request):
    if request.is_ajax() or DEBUG:
        w = get_object_or_404(Widget, pk=request.POST['widget_id'])
        if (w.workflow.user==request.user):
            try:
Janez K's avatar
Janez K committed
1085
                w.reset_descendants()
1086 1087 1088 1089 1090 1091 1092 1093
                data = simplejson.dumps({'status':'ok','message':'Widget '+w.name+' reset successfully.'})
                mimetype = 'application/javascript'
            except Exception, e:
                mimetype = 'application/javascript'
                w.error = True
                w.running = False
                w.finished = False
                w.save()
1094 1095
                print traceback.format_exc(e)

Janez K's avatar
Janez K committed
1096
                #raise
1097 1098 1099
                for o in w.outputs.all():
                    o.value=None
                    o.save()
1100

Janez K's avatar
Janez K committed
1101
                data = simplejson.dumps({'status':'error','message':'Error occurred when trying to reset the widget '+w.name+': '+str(type(e))+' '+str(e)})
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 1133 1134 1135 1136 1137
            return HttpResponse(data,mimetype)
        else:
            return HttpResponse(status=400)
    else:
        return HttpResponse(status=400)

@login_required
def reset_workflow(request):
    if request.is_ajax() or DEBUG:
        workflow = get_object_or_404(Workflow, pk=request.POST['workflow_id'])
        resetWidget = []
        for w in workflow.widgets.all():
            w.reset(False)
            resetWidget.append(w.pk)
        mimetype = 'application/javascript'
        data = simplejson.dumps({'resetWidget':resetWidget})
        return HttpResponse(data,mimetype)
    else:
        return HttpResponse(status=400)

@login_required
def get_executed_status(request):
    if request.is_ajax() or DEBUG:
        workflow = get_object_or_404(Workflow, pk=request.POST['workflow_id'])
        executedStatus = {}
        for w in workflow.widgets.all():
            if w.error or w.running or not w.finished:
                executedStatus[w.pk] = False
            else:
                executedStatus[w.pk] = True
        mimetype = 'application/javascript'
        data = simplejson.dumps({'executedStatus':executedStatus})
        return HttpResponse(data,mimetype)
    else:
        return HttpResponse(status=400)

Janez K's avatar
Janez K committed
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
@login_required
def visualize_widget(request):
    if request.is_ajax() or DEBUG:
        w = get_object_or_404(Widget, pk=request.POST['widget_id'])
        if (w.workflow.user==request.user):
            output_dict = {}
            for o in w.outputs.all():
                output_dict[o.variable]=o.value
            input_dict = {}
            for i in w.inputs.all():
                if not i.parameter:
                    if i.connections.count() > 0:
                        i.value = i.connections.all()[0].output.value
                        i.save()
                    else:
                        i.value = None
                        i.save()
                if i.multi_id == 0:
                    input_dict[i.variable]=i.value
                else:
                    if not i.variable in input_dict:
                        input_dict[i.variable]=[]
                    if not i.value == None:
                        input_dict[i.variable].append(i.value)
            view_to_call = getattr(workflows.visualization_views,w.abstract_widget.visualization_view)
Janez K's avatar
Janez K committed
1163
            return view_to_call(request, input_dict, output_dict, w)
Janez K's avatar
Janez K committed
1164 1165 1166
        else:
            return HttpResponse(status=400)
    else:
Janez K's avatar
Janez K committed
1167 1168
        return HttpResponse(status=400)

Janez K's avatar
Janez K committed
1169 1170 1171 1172 1173 1174
@login_required
def widget_results(request):
    def cap(s):
        """
        Caps the display size of long strings.
        """
Janez K's avatar
Janez K committed
1175
        if type(s) in [unicode, str] and len(s) > 300:
Janez K's avatar
Janez K committed
1176 1177 1178 1179
            return s[:300] + '\n...\''
        return s
    if request.is_ajax() or DEBUG:
        w = get_object_or_404(Widget, pk=request.POST['widget_id'])
1180
        if request.user == w.workflow.user:
Janez K's avatar
Janez K committed
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
            import pprint
            input_dict = {}
            output_dict = {}
            for i in w.inputs.all():
                if not i.parameter:
                    if i.connections.count() > 0:
                        i.value = i.connections.all()[0].output.value
                        i.save()
                    else:
                        i.value = None
                        i.save()
                if i.multi_id == 0:
                    input_dict[i.variable] = cap(pprint.pformat(i.value))
                else:
                    if not i.variable in input_dict:
                        input_dict[i.variable]=[]
                    if not i.value == None:
                        input_dict[i.variable].append(cap(pprint.pformat(i.value)))
            for o in w.outputs.all():
                output_dict[o.variable] = cap(pprint.pformat(o.value))
            return render(request, 'visualizations/result_viewer.html', {'widget':w,'input_dict':input_dict,'output_dict':output_dict})
        else:
            return HttpResponse(status=400)
    else:
        return HttpResponse(status=400)
Janez K's avatar
Janez K committed
1206

Janez K's avatar
Janez K committed
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
@login_required
def documentation(request):
    if request.is_ajax() or DEBUG:
        w = get_object_or_404(Widget, pk=request.POST['widget_id'])
        if (w.workflow.user==request.user):
            return render(request, 'visualizations/documentation.html', {'widget':w})
        else:
            return HttpResponse(status=400)
    else:
        return HttpResponse(status=400)
Janez K's avatar
Janez K committed
1217

Janez K's avatar
Janez K committed
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
@login_required
def get_designate_dialogs(request):
    if request.is_ajax() or DEBUG:
        c = get_object_or_404(Category, pk=request.POST['category_id'])
        if (c.user==request.user):
            return render(request, 'designation.html', {'category':c})
        else:
            return HttpResponse(status=400)
    else:
        return HttpResponse(status=400)

@login_required
def get_unfinished(request):
    #iscemo vse unfinished katerih predhodniki so finished
    if request.is_ajax() or DEBUG:
        workflow = get_object_or_404(Workflow, pk=request.POST['workflow_id'])
        if (workflow.user==request.user):
            unfinished_list = workflow.get_ready_to_run()
            mimetype = 'application/javascript'
            data = simplejson.dumps({'ready_to_run':unfinished_list})
Janez K's avatar
Janez K committed
1238
            return HttpResponse(data,mimetype)
Janez K's avatar
Janez K committed
1239 1240 1241
        else:
            return HttpResponse(status=400)
    else:
Janez K's avatar
Janez K committed
1242 1243
        return HttpResponse(status=400)

Janez K's avatar
Janez K committed
1244 1245 1246 1247 1248 1249 1250 1251 1252

@login_required
def unfinish_visualizations(request):
    if request.is_ajax() or DEBUG:
        workflow = get_object_or_404(Workflow, pk=request.POST['workflow_id'])
        unfinished_list = []
        for w in workflow.widgets.all():
            if w.is_visualization():
                w.unfinish()
Janez K's avatar
Janez K committed
1253
                #w.save()
Janez K's avatar
Janez K committed
1254 1255 1256 1257 1258
                unfinished_list.append(w.pk)
        mimetype = 'application/javascript'
        data = simplejson.dumps({'unfinished':unfinished_list})
        return HttpResponse(data,mimetype)
    else:
Janez K's avatar
Janez K committed
1259 1260 1261
        return HttpResponse(status=400)

@login_required
Janez K's avatar
Janez K committed
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277
def upload_handler(request):
    input = get_object_or_404(Input, pk=request.POST['input_id'])
    if (input.widget.workflow.user==request.user):
        destination = FILES_FOLDER+str(input.widget.workflow.id)+'/'+request.FILES['file'].name
        ensure_dir(destination)
        destination_file = open(destination, 'wb')
        for chunk in request.FILES['file'].chunks():
            destination_file.write(chunk)
        destination_file.close()
        input.value = destination
        input.save()
        input.widget.unfinish()
        error = None
        return render(request,'upload_handler.html', {"error":error,"input_id":input.id})
    else:
        return HttpResponse(status=400)
Janez K's avatar
Janez K committed
1278

Janez K's avatar
Janez K committed
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
@login_required
def widget_interaction(request):
    if request.is_ajax() or DEBUG:
        w = get_object_or_404(Widget, pk=request.POST['widget_id'])
        if (w.workflow.user==request.user):
            input_dict = {}
            output_dict = {}
            for i in w.inputs.all():
                if not i.parameter:
                    if i.connections.count() > 0:
                        i.value = i.connections.all()[0].output.value
                        i.save()
                    else:
                        i.value = None
                        i.save()
                if i.multi_id == 0:
                    input_dict[i.variable]=i.value
                else:
                    if not i.variable in input_dict:
                        input_dict[i.variable]=[]
                    if not i.value == None:
                        input_dict[i.variable].append(i.value)
            for o in w.outputs.all():
                output_dict[o.variable]=o.value
            view_to_call = getattr(workflows.interaction_views,w.abstract_widget.interaction_view)
            return view_to_call(request, input_dict, output_dict, w)
        else:
            return HttpResponse(status=400)
    else:
        return HttpResponse(status=400)
Janez K's avatar
Janez K committed
1309

Janez K's avatar
Janez K committed
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
@login_required
def finish_interaction(request):
    if request.is_ajax() or DEBUG:
        w = get_object_or_404(Widget, pk=request.POST['widget_id'])
        if (w.workflow.user==request.user):
            try:
                output_dict = w.run_post(dict(request.POST))
                w.interaction_waiting = False
                w.save()
                mimetype = 'application/javascript'
Janez K's avatar
Janez K committed
1320 1321 1322 1323
                if w.abstract_widget.visualization_view!='':
                    data = simplejson.dumps({'status':'visualize','message':'Visualizing widget '+w.name+'.','widget_id':w.id}) 
                else:                
                    data = simplejson.dumps({'status':'ok','message':'Widget '+w.name+' executed successfully.','widget_id':w.id})
1324
            except Exception,e:
Janez K's avatar
Janez K committed
1325 1326 1327 1328 1329 1330
                mimetype = 'application/javascript'
                w.error = True
                w.running = False
                w.finished = False
                w.interaction_waiting = False
                w.save()
1331
                print traceback.format_exc(e)
Janez K's avatar
Janez K committed
1332
                #raise
Janez K's avatar
Janez K committed
1333 1334 1335
                for o in w.outputs.all():
                    o.value=None
                    o.save()
Janez K's avatar
bugfix  
Janez K committed
1336
                data = simplejson.dumps({'status':'error','message':'Error occurred when trying to execute widget '+w.name+': '+str(type(e))+' '+str(e),'widget_id':w.id})
Janez K's avatar
Janez K committed
1337 1338 1339 1340 1341 1342
            return HttpResponse(data,mimetype)
        else:
            return HttpResponse(status=400)
    else:
        return HttpResponse(status=400)

Janez K's avatar
Janez K committed
1343

Janez K's avatar
Janez K committed
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402