Example #1
0
def main():
  uid = get_uid_from_cookie()
  uid_dir = os.path.join(app_dir, 'storage', 'users', uid['uid'])

  form = cgi.FieldStorage()
  if form.has_key('task'):
    taskstring = form.getvalue('task')
    task = parse_json_task(form.getvalue('task'))

  else:
    reply_failure("No task.")
    sys.exit()

  userconfig = read_user_config(uid)

  if not os.path.exists(uid_dir):
    write_user_config(uid, userconfig)
 
  d = datetime.now()
  taskname = d.strftime('%w') + str(d.hour*3600+d.minute*60+d.second)
  filename = 'tasktemp_'+ taskname +'.tsk'

  with open(os.path.join(uid_dir, filename), 'w') as f:
    f.write(create_xcsoar_task(task))
    reply_success(uid, taskname)
    sys.exit()

  reply_failure("Unknown failure.")
Example #2
0
def delete(taskname):
    uid = get_uid_from_cookie()
    uid_dir = os.path.join(current_app.config["USERS_FOLDER"], uid["uid"])

    userconfig = read_user_config(uid)

    success = False

    for key, d in enumerate(userconfig["task_files"]):
        if d.get("name") == taskname:
            taskfile = os.path.join(uid_dir, "task_" + str(d.get("id")) + ".tsk")
            os.unlink(taskfile)
            userconfig["task_files"].pop(key)
            success = True
            break

    for key, d in enumerate(userconfig["task_files"]):
        if (key + 1) != int(d.get("id")):
            taskfile_old = os.path.join(uid_dir, "task_" + str(d.get("id")) + ".tsk")
            taskfile_new = os.path.join(uid_dir, "task_" + str(key + 1) + ".tsk")
            os.rename(taskfile_old, taskfile_new)
            d["id"] = str(key + 1)

    write_user_config(uid, userconfig)

    return jsonify({"success": success, "settings": get_user_config_as_json(uid, encoded=False)})
Example #3
0
def main():
  uid = get_uid_from_cookie()
  uid_dir = os.path.join(app_dir, 'storage', 'users', uid['uid'])

  form = cgi.FieldStorage()
  fileId = int(form.getvalue('fileId'))

  if form.has_key('settings'):
    settings = form.getvalue('settings')
    userconfig = set_user_config_from_json(uid, settings)
  else:
    userconfig = read_user_config(uid)

  if len(userconfig['tp_files']) >= fileId: 
    os.remove(os.path.join(uid_dir, 'turnpoints_' + str(fileId) + '.cup'))
    userconfig['tp_files'].pop(fileId-1)

  for f_id in range(fileId+1, (len(userconfig['tp_files'])+2)):
    os.rename(os.path.join(uid_dir, 'turnpoints_' + str(f_id) + '.cup'),
              os.path.join(uid_dir, 'turnpoints_' + str(f_id-1) + '.cup'))

  write_user_config(uid, userconfig)

  print "Content-type: text/html"
  print
#  print '{"success":true}'
  print get_user_config_as_json(uid)
Example #4
0
def main():
  uid = get_uid_from_cookie()
  storage_dir = os.path.join(app_dir, 'storage')
  uid_dir = os.path.join(storage_dir, 'users', uid['uid'])
  userconfig = read_user_config(uid)

  form = cgi.FieldStorage()  

  m = re.compile('([^&+/;]*)').match(form.getvalue('task_name'))
  taskname = m.group(1)

  taskfile = ''


  for d in userconfig['task_files']:
    if d.get('name') == taskname:
      taskfile = os.path.join(uid_dir, 'task_' + str(d.get('id')) + '.tsk')

  if taskfile == '' or not os.path.exists(taskfile):
    raise RuntimeError('Task File does not exist')

  task = parse_xcsoar_task(taskfile)

  print "Content-Type: text/html"
  print
  print write_json_task(task)
Example #5
0
def delete(taskname):
    uid = get_uid_from_cookie()
    uid_dir = os.path.join(current_app.config['USERS_FOLDER'], uid['uid'])

    userconfig = read_user_config(uid)

    success = False

    for key, d in enumerate(userconfig['task_files']):
        if d.get('name') == taskname:
            taskfile = os.path.join(
                uid_dir, 'task_' + str(d.get('id')) + '.tsk')
            os.unlink(taskfile)
            userconfig['task_files'].pop(key)
            success = True
            break

    for key, d in enumerate(userconfig['task_files']):
        if (key + 1) != int(d.get('id')):
            taskfile_old = os.path.join(
                uid_dir, 'task_' + str(d.get('id')) + '.tsk')
            taskfile_new = os.path.join(
                uid_dir, 'task_' + str(key + 1) + '.tsk')
            os.rename(taskfile_old, taskfile_new)
            d['id'] = str(key + 1)

    write_user_config(uid, userconfig)

    return jsonify({
        'success': success,
        'settings': get_user_config_as_json(uid, encoded=False),
    })
Example #6
0
def delete(taskname):
    uid = get_uid_from_cookie()
    uid_dir = os.path.join(current_app.config['USERS_FOLDER'], uid['uid'])

    userconfig = read_user_config(uid)

    success = False

    for key, d in enumerate(userconfig['task_files']):
        if d.get('name') == taskname:
            taskfile = os.path.join(uid_dir,
                                    'task_' + str(d.get('id')) + '.tsk')
            os.unlink(taskfile)
            userconfig['task_files'].pop(key)
            success = True
            break

    for key, d in enumerate(userconfig['task_files']):
        if (key + 1) != int(d.get('id')):
            taskfile_old = os.path.join(uid_dir,
                                        'task_' + str(d.get('id')) + '.tsk')
            taskfile_new = os.path.join(uid_dir,
                                        'task_' + str(key + 1) + '.tsk')
            os.rename(taskfile_old, taskfile_new)
            d['id'] = str(key + 1)

    write_user_config(uid, userconfig)

    return jsonify({
        'success': success,
        'settings': get_user_config_as_json(uid, encoded=False),
    })
Example #7
0
def main():
  uid = get_uid_from_cookie()
  storage_dir = os.path.join(app_dir, 'storage')

  form = cgi.FieldStorage()

  tpfile_id = int(form.getvalue('id'))
  tpfile_lon = int(form.getvalue('lon'))
  tpfile_lat = int(form.getvalue('lat'))

  uid_dir = os.path.join(storage_dir, 'users', uid['uid'])
  userconfig = read_user_config(uid)

  if len(userconfig['tp_files']) < tpfile_id or tpfile_id < 1:
    raise RuntimeError('Waypoint File does not exist')

  turnpoint_file = os.path.join(storage_dir, 'users', uid['uid'], 'turnpoints_' + str(tpfile_id) + '.cup')
  if not os.path.exists(turnpoint_file):
    raise RuntimeError('Waypoint File does not exist')


  f = open(turnpoint_file, 'r')
  waypoints = parse_seeyou_waypoints(f)
  f.close()

  database = []

  for waypoint in waypoints:
    if waypoint.lon >= tpfile_lon \
       and waypoint.lon < tpfile_lon + 5 \
       and waypoint.lat >= tpfile_lat \
       and waypoint.lat < tpfile_lat + 5:

      database.append( {'lon': waypoint.lon,
                        'lat': waypoint.lat,
                        'type': 'T',
                        'altitude': waypoint.altitude,
                        'name': unicode(waypoint.name, "ISO-8859-1"),
                        'comment': ''} )

  sorted_database = sorted(database, key=lambda waypoint:(waypoint['lon'], waypoint['lat']))

  sorted_database.insert(0, {'chunk': {'lon_left': tpfile_lon,
                                       'lat_lower': tpfile_lat} } )

  
  print "Content-type: text/html"
  print
  print json.dumps(sorted_database, indent = 1)
Example #8
0
def get(tpfile_id, tpfile_lon, tpfile_lat):
    uid = get_uid_from_cookie()

    userconfig = read_user_config(uid)

    if len(userconfig['tp_files']) < tpfile_id or tpfile_id < 1:
        raise NotFound('Waypoint File does not exist')

    turnpoint_file = os.path.join(
        current_app.config['USERS_FOLDER'], uid['uid'],
        'turnpoints_' + str(tpfile_id) + '.cup'
    )
    if not os.path.exists(turnpoint_file):
        raise NotFound('Waypoint File does not exist')

    f = open(turnpoint_file, 'r')
    waypoints = parse_seeyou_waypoints(f)
    f.close()

    database = []

    for waypoint in waypoints:
        if waypoint.lon >= tpfile_lon \
           and waypoint.lon < tpfile_lon + 5 \
           and waypoint.lat >= tpfile_lat \
           and waypoint.lat < tpfile_lat + 5:

            database.append({
                'lon': waypoint.lon,
                'lat': waypoint.lat,
                'type': 'T',
                'altitude': waypoint.altitude,
                'name': unicode(waypoint.name, "ISO-8859-1"),
                'comment': '',
            })

    sorted_database = sorted(
        database, key=lambda waypoint: (waypoint['lon'], waypoint['lat']))

    sorted_database.insert(0, {
        'chunk': {
            'lon_left': tpfile_lon,
            'lat_lower': tpfile_lat,
        },
    })

    return json.dumps(sorted_database, indent=1)
Example #9
0
def load(taskname):
    uid = get_uid_from_cookie()
    uid_dir = os.path.join(current_app.config["USERS_FOLDER"], uid["uid"])
    userconfig = read_user_config(uid)

    taskfile = ""

    for d in userconfig["task_files"]:
        if d.get("name") == taskname:
            taskfile = os.path.join(uid_dir, "task_" + str(d.get("id")) + ".tsk")

    if taskfile == "" or not os.path.exists(taskfile):
        raise NotFound("Task File does not exist")

    task = parse_xcsoar_task(taskfile)

    return write_json_task(task)
Example #10
0
def main():
  form = cgi.FieldStorage()  
#  uid = get_uid_from_cookie()

  m = re.compile('([0-9a-z]*)').match(form.getvalue('uid'))
  uid = {'uid': m.group(1)}

  storage_dir = os.path.join(app_dir, 'storage')
  uid_dir = os.path.join(storage_dir, 'users', uid['uid'])
  userconfig = read_user_config(uid)

  m = re.compile('([^&+/;]*)').match(form.getvalue('task'))
  taskname = m.group(1)

  temptask = form.getvalue('temp', 0)
  taskfile = ''

  if not temptask:
    for d in userconfig['task_files']:
      if d.get('name') == taskname:
        taskfile = os.path.join(uid_dir, 'task_' + str(d.get('id')) + '.tsk')

  else:
    taskfile = os.path.join(uid_dir, 'tasktemp_' + str(taskname) + '.tsk') 

  if taskfile == '' or not os.path.exists(taskfile):
    print "Status: 404 Not Found"
    print "Content-type: text/html"
    print
    print "Task file not found: " + taskname
    sys.exit() 
#    raise RuntimeError('Task File does not exist')

  task = parse_xcsoar_task(taskfile)

  if (form.getvalue('filetype') == 'xcsoar'):
    print "Content-Type: application/xcsoar"
    print "Content-disposition: attachment; filename=" + taskname + ".tsk"
    print
    print create_xcsoar_task(task)

  elif (form.getvalue('filetype') == 'seeyou'):
    print "Content-Type: application/seeyou"
    print "Content-disposition: attachment; filename=" + taskname + ".cup"
    print
    print create_seeyou_task(task, taskname)
Example #11
0
def load(taskname):
    uid = get_uid_from_cookie()
    uid_dir = os.path.join(current_app.config['USERS_FOLDER'], uid['uid'])
    userconfig = read_user_config(uid)

    taskfile = ''

    for d in userconfig['task_files']:
        if d.get('name') == taskname:
            taskfile = os.path.join(
                uid_dir, 'task_' + str(d.get('id')) + '.tsk')

    if taskfile == '' or not os.path.exists(taskfile):
        raise NotFound('Task File does not exist')

    task = parse_xcsoar_task(taskfile)

    return write_json_task(task)
Example #12
0
def load(taskname):
    uid = get_uid_from_cookie()
    uid_dir = os.path.join(current_app.config['USERS_FOLDER'], uid['uid'])
    userconfig = read_user_config(uid)

    taskfile = ''

    for d in userconfig['task_files']:
        if d.get('name') == taskname:
            taskfile = os.path.join(uid_dir,
                                    'task_' + str(d.get('id')) + '.tsk')

    if taskfile == '' or not os.path.exists(taskfile):
        raise NotFound('Task File does not exist')

    task = parse_xcsoar_task(taskfile)

    return write_json_task(task)
Example #13
0
def save_temp():
    uid = get_uid_from_cookie()
    uid_dir = os.path.join(current_app.config["USERS_FOLDER"], uid["uid"])

    if "task" in request.values:
        taskstring = request.values["task"]
        task = parse_json_task(taskstring)

    else:
        return jsonify({"success": False, "reason": "No task."})

    userconfig = read_user_config(uid)

    if not os.path.exists(uid_dir):
        write_user_config(uid, userconfig)

    d = datetime.now()
    taskname = d.strftime("%w") + str(d.hour * 3600 + d.minute * 60 + d.second)
    filename = "tasktemp_" + taskname + ".tsk"

    with open(os.path.join(uid_dir, filename), "w") as f:
        f.write(create_xcsoar_task(task))

        base_url = "tasks/" + uid["uid"] + "/temp/" + taskname
        return jsonify(
            {
                "success": True,
                "settings": get_user_config_as_json(uid, encoded=False),
                "download": {
                    "xcsoar": {
                        "name": "XCSoar (*.tsk)",
                        "url": base_url + "/xcsoar",
                        "qrcode": base_url + "/xcsoar/qr",
                    },
                    "seeyou": {
                        "name": "SeeYou (*.cup)",
                        "url": base_url + "/seeyou",
                        "qrcode": base_url + "/seeyou/qr",
                    },
                },
            }
        )

    return jsonify({"success": False, "reason": "Unknown failure."})
Example #14
0
def save_temp():
    uid = get_uid_from_cookie()
    uid_dir = os.path.join(current_app.config['USERS_FOLDER'], uid['uid'])

    if 'task' in request.values:
        taskstring = request.values['task']
        task = parse_json_task(taskstring)

    else:
        return jsonify({'success': False, 'reason': 'No task.'})

    userconfig = read_user_config(uid)

    if not os.path.exists(uid_dir):
        write_user_config(uid, userconfig)

    d = datetime.now()
    taskname = d.strftime('%w') + str(d.hour * 3600 + d.minute * 60 + d.second)
    filename = 'tasktemp_' + taskname + '.tsk'

    with open(os.path.join(uid_dir, filename), 'w') as f:
        f.write(create_xcsoar_task(task))

        base_url = 'tasks/' + uid['uid'] + '/temp/' + taskname
        return jsonify({
            'success': True,
            'settings': get_user_config_as_json(uid, encoded=False),
            'download': {
                'xcsoar': {
                    'name': 'XCSoar (*.tsk)',
                    'url': base_url + '/xcsoar',
                    'qrcode': base_url + '/xcsoar/qr',
                },
                'seeyou': {
                    'name': 'SeeYou (*.cup)',
                    'url': base_url + '/seeyou',
                    'qrcode': base_url + '/seeyou/qr',
                },
            }
        })

    return jsonify({'success': False, 'reason': 'Unknown failure.'})
Example #15
0
def main():
  uid = get_uid_from_cookie()
  uid_dir = os.path.join(app_dir, 'storage', 'users', uid['uid'])

  form = cgi.FieldStorage()
  m = re.compile('([^&+/;]*)').match(form.getvalue('task_name'))
  taskname = m.group(1)

  userconfig = read_user_config(uid)

  success = False

  for key, d in enumerate(userconfig['task_files']):
    if d.get('name') == taskname:
      taskfile = os.path.join(uid_dir, 'task_' + str(d.get('id')) + '.tsk')
      os.unlink(taskfile)
      userconfig['task_files'].pop(key)
      success = True
      break

  for key, d in enumerate(userconfig['task_files']):
    if (key+1) != int(d.get('id')):
      taskfile_old = os.path.join(uid_dir, 'task_' + str(d.get('id')) + '.tsk')
      taskfile_new = os.path.join(uid_dir, 'task_' + str(key+1) + '.tsk')
      os.rename(taskfile_old, taskfile_new)
      d['id'] = str(key+1)

  write_user_config(uid, userconfig)

  print "Content-type: text/html"
  print
  print '{'

  if success:
    print '"success":true,'
  else:
    print '"success":false,'

  print '"settings":' + get_user_config_as_json(uid)
  print '}'
Example #16
0
def download(uid, taskname, filetype, temptask=False):
    uid = {'uid': uid}

    uid_dir = os.path.join(current_app.config['USERS_FOLDER'], uid['uid'])
    userconfig = read_user_config(uid)

    taskfile = ''

    if not temptask:
        for d in userconfig['task_files']:
            if d.get('name') == taskname:
                taskfile = os.path.join(uid_dir,
                                        'task_' + str(d.get('id')) + '.tsk')

    else:
        taskfile = os.path.join(uid_dir, 'tasktemp_' + str(taskname) + '.tsk')

    if taskfile == '' or not os.path.exists(taskfile):
        raise NotFound('Task file not found: ' + taskname)

    task = parse_xcsoar_task(taskfile)

    if filetype == 'xcsoar':
        mimetype = 'application/xcsoar'
        file_extension = 'tsk'
        task = create_xcsoar_task(task)

    elif filetype == 'seeyou':
        mimetype = 'application/seeyou'
        file_extension = 'cup'
        task = create_seeyou_task(task, taskname)

    io = StringIO()
    io.write(task.encode('utf-8'))
    io.seek(0)

    return send_file(io,
                     mimetype=mimetype,
                     as_attachment=True,
                     attachment_filename=(taskname + '.' + file_extension))
Example #17
0
def save_temp():
    uid = get_uid_from_cookie()
    uid_dir = os.path.join(current_app.config['USERS_FOLDER'], uid['uid'])

    if 'task' not in request.values:
        return jsonify({'success': False, 'reason': 'No task.'})

    taskstring = request.values['task']
    task = parse_json_task(taskstring)

    userconfig = read_user_config(uid)

    if not os.path.exists(uid_dir):
        write_user_config(uid, userconfig)

    d = datetime.now()
    taskname = d.strftime('%w') + str(d.hour * 3600 + d.minute * 60 + d.second)
    filename = 'tasktemp_' + taskname + '.tsk'

    with open(os.path.join(uid_dir, filename), 'w') as f:
        write_xcsoar_task(f, task)

    base_url = 'tasks/' + uid['uid'] + '/temp/' + taskname
    return jsonify({
        'success': True,
        'settings': get_user_config_as_json(uid, encoded=False),
        'download': {
            'xcsoar': {
                'name': 'XCSoar (*.tsk)',
                'url': base_url + '/xcsoar',
                'qrcode': base_url + '/xcsoar/qr',
            },
            'seeyou': {
                'name': 'SeeYou (*.cup)',
                'url': base_url + '/seeyou',
                'qrcode': base_url + '/seeyou/qr',
            },
        }
    })
Example #18
0
def remove(fileId):
    uid = get_uid_from_cookie()
    uid_dir = os.path.join(current_app.config['USERS_FOLDER'], uid['uid'])

    if 'settings' in request.values:
        settings = request.values['settings']
        userconfig = set_user_config_from_json(uid, settings)
    else:
        userconfig = read_user_config(uid)

    if len(userconfig['tp_files']) >= fileId:
        os.remove(os.path.join(uid_dir, 'turnpoints_' + str(fileId) + '.cup'))
        userconfig['tp_files'].pop(fileId - 1)

    for f_id in range(fileId + 1, (len(userconfig['tp_files']) + 2)):
        os.rename(
            os.path.join(uid_dir, 'turnpoints_' + str(f_id) + '.cup'),
            os.path.join(uid_dir, 'turnpoints_' + str(f_id - 1) + '.cup')
        )

    write_user_config(uid, userconfig)

    return jsonify(get_user_config_as_json(uid, encoded=False))
Example #19
0
def download(uid, taskname, filetype, temptask=False):
    uid = {'uid': uid}

    uid_dir = os.path.join(current_app.config['USERS_FOLDER'], uid['uid'])
    userconfig = read_user_config(uid)

    taskfile = ''

    if not temptask:
        for d in userconfig['task_files']:
            if d.get('name') == taskname:
                taskfile = os.path.join(
                    uid_dir, 'task_' + str(d.get('id')) + '.tsk')

    else:
        taskfile = os.path.join(uid_dir, 'tasktemp_' + str(taskname) + '.tsk')

    if taskfile == '' or not os.path.exists(taskfile):
        raise NotFound('Task file not found: ' + taskname)

    task = parse_xcsoar_task(taskfile)

    io = StringIO()
    if filetype == 'xcsoar':
        mimetype = 'application/xcsoar'
        file_extension = 'tsk'
        write_xcsoar_task(io, task)

    elif filetype == 'seeyou':
        mimetype = 'application/seeyou'
        file_extension = 'cup'
        write_seeyou_task(io, task, taskname)

    io.seek(0)

    return send_file(io, mimetype=mimetype, as_attachment=True,
                     attachment_filename=(taskname + '.' + file_extension))
Example #20
0
def download(uid, taskname, filetype, temptask=False):
    uid = {"uid": uid}

    uid_dir = os.path.join(current_app.config["USERS_FOLDER"], uid["uid"])
    userconfig = read_user_config(uid)

    taskfile = ""

    if not temptask:
        for d in userconfig["task_files"]:
            if d.get("name") == taskname:
                taskfile = os.path.join(uid_dir, "task_" + str(d.get("id")) + ".tsk")

    else:
        taskfile = os.path.join(uid_dir, "tasktemp_" + str(taskname) + ".tsk")

    if taskfile == "" or not os.path.exists(taskfile):
        raise NotFound("Task file not found: " + taskname)

    task = parse_xcsoar_task(taskfile)

    if filetype == "xcsoar":
        mimetype = "application/xcsoar"
        file_extension = "tsk"
        task = create_xcsoar_task(task)

    elif filetype == "seeyou":
        mimetype = "application/seeyou"
        file_extension = "cup"
        task = create_seeyou_task(task, taskname)

    io = StringIO()
    io.write(task.encode("utf-8"))
    io.seek(0)

    return send_file(io, mimetype=mimetype, as_attachment=True, attachment_filename=(taskname + "." + file_extension))
Example #21
0
def main():
  uid = get_uid_from_cookie()
  uid_dir = os.path.join(app_dir, 'storage', 'users', uid['uid'])

  form = cgi.FieldStorage()
  if form.has_key('task'):
    taskstring = form.getvalue('task')
    task = parse_json_task(form.getvalue('task'))

  else:
    reply_failure("No task.")
    sys.exit()

  m = re.compile('([^&+/;]*)').match(form.getvalue('task_name'))
  task_name = m.group(1)

  if task_name == '':
    reply_failure("Invalid task name.")
    sys.exit()

  userconfig = read_user_config(uid)

  if not os.path.exists(uid_dir):
    write_user_config(uid, userconfig)

  replace = False

  taskid = len(userconfig['task_files']) 

  for key, value in enumerate(userconfig['task_files']):

    if value['name'] == task_name:
      replace = True
      taskid = key
      break

  if taskid >= 20:
    reply_failure("Too much tasks saved already (maximum of 20 reached).")
    sys.exit()
#    raise RuntimeError('Too much tasks saved')
 
  filename = 'task_'+str(taskid+1)+'.tsk'
  d = datetime.today()

  with open(os.path.join(uid_dir, filename), 'w') as f:
    f.write(create_xcsoar_task(task))
    
    if not replace:
      userconfig['task_files'].append({'id': taskid+1,
                                       'name': task_name,
                                       'distance': task.distance,
                                       'type': task.type,
                                       'turnpoints': len(task),
                                       'date': d.isoformat() })
    else:
      userconfig['task_files'][taskid] = {'id': taskid+1,
                                       'name': task_name,
                                       'distance': task.distance,
                                       'type': task.type,
                                       'turnpoints': len(task),
                                       'date': d.isoformat() }

    write_user_config(uid, userconfig)
    reply_success(uid)
    exit()

  reply_failure("Unknown failure.")
Example #22
0
def save(task_name):
    uid = get_uid_from_cookie()
    uid_dir = os.path.join(current_app.config['USERS_FOLDER'], uid['uid'])

    if 'task' not in request.values:
        return jsonify({'success': False, 'reason': 'No task.'})

    taskstring = request.values['task']
    task = parse_json_task(taskstring)

    m = re.compile('([^&+/;]*)').match(task_name)
    task_name = m.group(1)

    if task_name == '':
        return jsonify({'success': False, 'reason': 'Invalid task name.'})

    userconfig = read_user_config(uid)

    if not os.path.exists(uid_dir):
        write_user_config(uid, userconfig)

    replace = False

    taskid = len(userconfig['task_files'])

    for key, value in enumerate(userconfig['task_files']):

        if value['name'] == task_name:
            replace = True
            taskid = key
            break

    if taskid >= 20:
        return jsonify({
            'success': False,
            'reason': 'Too much tasks saved already (maximum of 20 reached).'
        })

    filename = 'task_' + str(taskid + 1) + '.tsk'
    d = datetime.today()

    with open(os.path.join(uid_dir, filename), 'w') as f:
        write_xcsoar_task(f, task)

    taskinfo = {
        'id': taskid + 1,
        'name': task_name,
        'distance': task.distance,
        'type': task.type,
        'turnpoints': len(task),
        'date': d.isoformat()
    }

    if not replace:
        userconfig['task_files'].append(taskinfo)
    else:
        userconfig['task_files'][taskid] = taskinfo

    write_user_config(uid, userconfig)
    return jsonify({
        'success': True,
        'settings': get_user_config_as_json(uid, encoded=False)
    })
Example #23
0
def save(task_name):
    uid = get_uid_from_cookie()
    uid_dir = os.path.join(current_app.config['USERS_FOLDER'], uid['uid'])

    if 'task' not in request.values:
        return jsonify({'success': False, 'reason': 'No task.'})

    taskstring = request.values['task']
    task = parse_json_task(taskstring)

    m = re.compile('([^&+/;]*)').match(task_name)
    task_name = m.group(1)

    if task_name == '':
        return jsonify({'success': False, 'reason': 'Invalid task name.'})

    userconfig = read_user_config(uid)

    if not os.path.exists(uid_dir):
        write_user_config(uid, userconfig)

    replace = False

    taskid = len(userconfig['task_files'])

    for key, value in enumerate(userconfig['task_files']):

        if value['name'] == task_name:
            replace = True
            taskid = key
            break

    if taskid >= 20:
        return jsonify({
            'success':
            False,
            'reason':
            'Too much tasks saved already (maximum of 20 reached).'
        })

    filename = 'task_' + str(taskid + 1) + '.tsk'
    d = datetime.today()

    with open(os.path.join(uid_dir, filename), 'w') as f:
        write_xcsoar_task(f, task)

    taskinfo = {
        'id': taskid + 1,
        'name': task_name,
        'distance': task.distance,
        'type': task.type,
        'turnpoints': len(task),
        'date': d.isoformat()
    }

    if not replace:
        userconfig['task_files'].append(taskinfo)
    else:
        userconfig['task_files'][taskid] = taskinfo

    write_user_config(uid, userconfig)
    return jsonify({
        'success': True,
        'settings': get_user_config_as_json(uid, encoded=False)
    })
Example #24
0
def save(task_name):
    uid = get_uid_from_cookie()
    uid_dir = os.path.join(current_app.config["USERS_FOLDER"], uid["uid"])

    if "task" in request.values:
        taskstring = request.values["task"]
        task = parse_json_task(taskstring)

    else:
        return jsonify({"success": False, "reason": "No task."})

    m = re.compile("([^&+/;]*)").match(task_name)
    task_name = m.group(1)

    if task_name == "":
        return jsonify({"success": False, "reason": "Invalid task name."})

    userconfig = read_user_config(uid)

    if not os.path.exists(uid_dir):
        write_user_config(uid, userconfig)

    replace = False

    taskid = len(userconfig["task_files"])

    for key, value in enumerate(userconfig["task_files"]):

        if value["name"] == task_name:
            replace = True
            taskid = key
            break

    if taskid >= 20:
        return jsonify({"success": False, "reason": "Too much tasks saved already (maximum of 20 reached)."})

    filename = "task_" + str(taskid + 1) + ".tsk"
    d = datetime.today()

    with open(os.path.join(uid_dir, filename), "w") as f:
        f.write(create_xcsoar_task(task))

        if not replace:
            userconfig["task_files"].append(
                {
                    "id": taskid + 1,
                    "name": task_name,
                    "distance": task.distance,
                    "type": task.type,
                    "turnpoints": len(task),
                    "date": d.isoformat(),
                }
            )
        else:
            userconfig["task_files"][taskid] = {
                "id": taskid + 1,
                "name": task_name,
                "distance": task.distance,
                "type": task.type,
                "turnpoints": len(task),
                "date": d.isoformat(),
            }

        write_user_config(uid, userconfig)
        return jsonify({"success": True, "settings": get_user_config_as_json(uid, encoded=False)})

    return jsonify({"success": False, "reason": "Unknown failure."})