Exemplo n.º 1
0
def do_import_github(project_id, github_user, github_project, github_branch, delete_project=False):
    try:
        url = "https://github.com/%s/%s/archive/%s.zip" % (github_user, github_project, github_branch)
        if file_exists(url):
            u = urllib2.urlopen(url)
            return do_import_archive(project_id, u.read())
        else:
            raise Exception("The branch '%s' does not exist." % github_branch)
    except Exception as e:
        try:
            project = Project.objects.get(pk=project_id)
            user = project.owner
        except:
            project = None
            user = None
        if delete_project and project is not None:
            try:
                project.delete()
            except:
                pass
        send_td_event('cloudpebble_github_import_failed', data={
            'data': {
                'reason': e.message,
                'github_user': github_user,
                'github_project': github_project,
                'github_branch': github_branch
            }
        }, user=user)
        raise
Exemplo n.º 2
0
def do_import_github(project_id, github_user, github_project, github_branch, delete_project=False):
    print("Running do_import_github:", project_id, github_user, github_project, github_branch, delete_project)
    try:
        url = "https://github.com/%s/%s/archive/%s.zip" % (github_user, github_project, github_branch)
        if file_exists(url):
            u = urllib2.urlopen(url)
            print("Forwarding to do_import_archive")
            return do_import_archive(project_id, u.read())
        else:
            raise Exception("The branch '%s' does not exist." % github_branch)
    except Exception as e:
        try:
            project = Project.objects.get(pk=project_id)
            user = project.owner
        except:
            project = None
            user = None
        if delete_project and project is not None:
            try:
                project.delete()
            except:
                pass
        send_td_event('cloudpebble_github_import_failed', data={
            'data': {
                'reason': e.message,
                'github_user': github_user,
                'github_project': github_project,
                'github_branch': github_branch
            }
        }, user=user)
        raise
Exemplo n.º 3
0
def save_source_file(request, project_id, file_id):
    project = get_object_or_404(Project, pk=project_id, owner=request.user)
    source_file = get_object_or_404(SourceFile, pk=file_id, project=project)

    if source_file.was_modified_since(int(request.POST['modified'])):
        send_td_event('cloudpebble_save_abort_unsafe',
                      data={
                          'data': {
                              'filename': source_file.file_name,
                              'kind': 'source'
                          }
                      },
                      request=request,
                      project=project)
        raise Exception(
            _("Could not save: file has been modified since last save."))
    source_file.save_file(request.POST['content'],
                          folded_lines=request.POST['folded_lines'])

    send_td_event(
        'cloudpebble_save_file',
        data={'data': {
            'filename': source_file.file_name,
            'kind': 'source'
        }},
        request=request,
        project=project)

    return {"modified": time.mktime(source_file.last_modified.utctimetuple())}
Exemplo n.º 4
0
def create_source_file(request, project_id):
    project = get_object_or_404(Project, pk=project_id, owner=request.user)
    try:
        f = SourceFile.objects.create(project=project,
                                      file_name=request.POST['name'],
                                      target=request.POST.get('target', 'app'))
        f.save_text(request.POST.get('content', ''))

    except IntegrityError as e:
        raise BadRequest(str(e))

    send_td_event('cloudpebble_create_file', data={
        'data': {
            'filename': request.POST['name'],
            'kind': 'source',
            'target': f.target
        }
    }, request=request, project=project)

    return {
        'file': {
            'id': f.id,
            'name': f.file_name,
            'target': f.target,
            'file_path': f.project_path
        }
    }
Exemplo n.º 5
0
def load_source_file(request, project_id, file_id):
    project = get_object_or_404(Project, pk=project_id, owner=request.user)
    source_file = get_object_or_404(SourceFile, pk=file_id, project=project)

    content = source_file.get_contents()

    try:
        folded_lines = json.loads(source_file.folded_lines)
    except ValueError:
        folded_lines = []

    send_td_event(
        'cloudpebble_open_file',
        data={'data': {
            'filename': source_file.file_name,
            'kind': 'source'
        }},
        request=request,
        project=project)

    return {
        "source": content,
        "modified": time.mktime(source_file.last_modified.utctimetuple()),
        "folded_lines": folded_lines
    }
Exemplo n.º 6
0
def do_import_github(project_id, github_user, github_project, github_branch, github_token, delete_project=False):
    try:
        url = "https://github.com/%s/%s/archive/%s.zip" % (github_user, github_project, github_branch)
        logger.info("URL: %s", url)
        r = urllib2.Request(url)
        if github_token is not None:
            r.add_header('Authorization', 'token ' + github_token)
        u = urllib2.urlopen(r)
        return do_import_archive(project_id, u.read())
    except Exception as e:
        try:
            project = Project.objects.get(pk=project_id)
            user = project.owner
        except:
            project = None
            user = None
        if delete_project and project is not None:
            try:
                project.delete()
            except:
                pass
        send_td_event('cloudpebble_github_import_failed', data={
            'data': {
                'reason': e.message,
                'github_user': github_user,
                'github_project': github_project,
                'github_branch': github_branch,
                'github_token': github_token
            }
        }, user=user)
        raise
Exemplo n.º 7
0
def view_project(request, project_id):
    project = get_object_or_404(Project, pk=project_id, owner=request.user)
    if project.app_uuid is None:
        project.app_uuid = generate_half_uuid()
    if project.app_company_name is None:
        project.app_company_name = request.user.username
    if project.app_short_name is None:
        project.app_short_name = project.name
    if project.app_long_name is None:
        project.app_long_name = project.app_short_name
    if project.app_version_label is None:
        project.app_version_label = '1.0'
    app_keys = project.get_parsed_appkeys()
    supported_platforms = ["aplite", "basalt"]
    if project.project_type != 'pebblejs' and project.sdk_version != '2':
        supported_platforms.append("chalk")

    send_td_event('cloudpebble_open_project', request=request, project=project)
    try:
        token = request.user.social_auth.get(provider='pebble').extra_data['access_token']
    except:
        token = ''
    return render(request, 'ide/project.html', {
        'project': project,
        'app_keys': app_keys,
        'font_css': settings.TYPOGRAPHY_CSS,
        'libpebble_proxy': json.dumps(settings.LIBPEBBLE_PROXY),
        'token': token,
        'phone_shorturl': settings.PHONE_SHORTURL,
        'supported_platforms': supported_platforms,
        'regexes': regexes,
        'regexes_json': json.dumps(regexes.regex_dictionary)
    })
Exemplo n.º 8
0
def view_project(request, project_id):
    project = get_object_or_404(Project, pk=project_id, owner=request.user)
    if project.app_uuid is None:
        project.app_uuid = generate_half_uuid()
    if project.app_company_name is None:
        project.app_company_name = request.user.username
    if project.app_short_name is None:
        project.app_short_name = project.name
    if project.app_long_name is None:
        project.app_long_name = project.app_short_name
    if project.app_version_label is None:
        project.app_version_label = '1.0'
    send_td_event('cloudpebble_open_project', request=request, project=project)
    app_keys = sorted(json.loads(project.app_keys).iteritems(), key=lambda x: x[1])
    supported_platforms = ["aplite", "basalt"]
    if project.project_type != 'pebblejs' and project.sdk_version != '2':
        supported_platforms.append("chalk")

    try:
        token = request.user.social_auth.get(provider='pebble').extra_data['access_token']
    except:
        token = ''
    return render(request, 'ide/project.html', {
        'project': project,
        'app_keys': app_keys,
        'font_css': settings.TYPOGRAPHY_CSS,
        'libpebble_proxy': json.dumps(settings.LIBPEBBLE_PROXY),
        'token': token,
        'phone_shorturl': settings.PHONE_SHORTURL,
        'supported_platforms': supported_platforms
    })
Exemplo n.º 9
0
def load_source_file(request, project_id, file_id):
    project = get_object_or_404(Project, pk=project_id, owner=request.user)
    source_file = get_object_or_404(SourceFile, pk=file_id, project=project)
    try:
        content = source_file.get_contents()

        try:
            folded_lines = json.loads(source_file.folded_lines)
        except ValueError:
            folded_lines = []

        send_td_event('cloudpebble_open_file', data={
            'data': {
                'filename': source_file.file_name,
                'kind': 'source'
            }
        }, request=request, project=project)

    except Exception as e:
        return json_failure(str(e))
    else:
        return json_response({
            "success": True,
            "source": content,
            "modified": time.mktime(source_file.last_modified.utctimetuple()),
            "folded_lines": folded_lines
        })
Exemplo n.º 10
0
def save_source_file(request, project_id, file_id):
    project = get_object_or_404(Project, pk=project_id, owner=request.user)
    source_file = get_object_or_404(SourceFile, pk=file_id, project=project)
    try:
        if source_file.was_modified_since(int(request.POST['modified'])):
            send_td_event('cloudpebble_save_abort_unsafe', data={
                'data': {
                    'filename': source_file.file_name,
                    'kind': 'source'
                }
            }, request=request, project=project)
            raise Exception(_("Could not save: file has been modified since last save."))
        source_file.save_file(request.POST['content'], folded_lines=request.POST['folded_lines'])

    except Exception as e:
        return json_failure(str(e))
    else:
        send_td_event('cloudpebble_save_file', data={
            'data': {
                'filename': source_file.file_name,
                'kind': 'source'
            }
        }, request=request, project=project)

        return json_response({"modified": time.mktime(source_file.last_modified.utctimetuple())})
Exemplo n.º 11
0
def create_archive(project_id):
    project = Project.objects.get(pk=project_id)
    prefix = re.sub(r'[^\w]+', '_', project.name).strip('_').lower()
    with tempfile.NamedTemporaryFile(suffix='.zip', delete=False) as temp:
        filename = temp.name
        with zipfile.ZipFile(filename, 'w',
                             compression=zipfile.ZIP_DEFLATED) as z:
            add_project_to_archive(z, project)

        # Generate a URL
        u = uuid.uuid4().hex

        send_td_event('cloudpebble_export_project', project=project)

        if not settings.AWS_ENABLED:
            outfile = '%s%s/%s.zip' % (settings.EXPORT_DIRECTORY, u, prefix)
            os.makedirs(os.path.dirname(outfile), 0755)
            shutil.copy(filename, outfile)
            os.chmod(outfile, 0644)
            return '%s%s/%s.zip' % (settings.EXPORT_ROOT, u, prefix)
        else:
            outfile = '%s/%s.zip' % (u, prefix)
            s3.upload_file('export',
                           outfile,
                           filename,
                           public=True,
                           content_type='application/zip')
            return '%s%s' % (settings.EXPORT_ROOT, outfile)
Exemplo n.º 12
0
def index(request, github_account=None, github_project=None):
    user = request.user
    my_projects = Project.objects.filter(owner=user).order_by('-last_modified')
    if not user.settings.accepted_terms:
        # Screw it.
        # user_settings = user.settings
        # user_settings.accepted_terms = True
        # user_settings.save()

        return render(request, 'ide/new-owner.html',
                      {'my_projects': my_projects})
    elif settings.SOCIAL_AUTH_PEBBLE_REQUIRED and user.social_auth.filter(
            provider='pebble').count() == 0:
        return render(request, 'registration/merge_account.html')
    else:
        send_td_event('cloudpebble_project_list', request=request)
        return render(
            request, 'ide/index.html', {
                'my_projects':
                my_projects,
                'sdk_templates':
                TemplateProject.objects.filter(
                    template_kind=TemplateProject.KIND_TEMPLATE),
                'demo_templates':
                TemplateProject.objects.filter(
                    template_kind=TemplateProject.KIND_SDK_DEMO),
                'default_template_id':
                settings.DEFAULT_TEMPLATE,
                'user':
                user,
            })
Exemplo n.º 13
0
def export_user_projects(user_id):
    user = User.objects.get(pk=user_id)
    projects = Project.objects.filter(owner=user)
    with tempfile.NamedTemporaryFile(suffix='.zip', delete=False) as temp:
        filename = temp.name
        with zipfile.ZipFile(filename, 'w',
                             compression=zipfile.ZIP_DEFLATED) as z:
            for project in projects:
                add_project_to_archive(z,
                                       project,
                                       prefix='cloudpebble-export/',
                                       suffix='-%d' % project.id)

        send_td_event('cloudpebble_export_all_projects', user=user)

        # Generate a URL
        u = uuid.uuid4().hex
        if not settings.AWS_ENABLED:
            outfile = '%s%s/%s.zip' % (settings.EXPORT_DIRECTORY, u,
                                       'cloudpebble-export')
            os.makedirs(os.path.dirname(outfile), 0755)
            shutil.copy(filename, outfile)
            os.chmod(outfile, 0644)
            return '%s%s/%s.zip' % (settings.EXPORT_ROOT, u,
                                    'cloudpebble-export')
        else:
            outfile = '%s/%s.zip' % (u, 'cloudpebble-export')
            s3.upload_file('export',
                           outfile,
                           filename,
                           public=True,
                           content_type='application/zip')
            return '%s%s' % (settings.EXPORT_ROOT, outfile)
Exemplo n.º 14
0
def resource_info(request, project_id, resource_id):
    project = get_object_or_404(Project, pk=project_id, owner=request.user)
    resource = get_object_or_404(ResourceFile, pk=resource_id)
    resources = resource.get_identifiers()

    send_td_event('cloudpebble_open_file',
                  data={
                      'data': {
                          'filename': resource.file_name,
                          'kind': 'resource',
                          'resource-kind': resource.kind
                      }
                  },
                  request=request,
                  project=project)

    return {
        'resource': {
            'resource_ids':
            [x.get_options_dict(with_id=True) for x in resources],
            'id': resource.id,
            'file_name': resource.file_name,
            'kind': resource.kind,
            "variants": [x.get_tags() for x in resource.variants.all()],
            "extra": {
                y.resource_id: y.get_options_dict(with_id=False)
                for y in resource.identifiers.all()
            }
        }
    }
Exemplo n.º 15
0
def delete_variant(request, project_id, resource_id, variant):
    project = get_object_or_404(Project, pk=project_id, owner=request.user)
    resource = get_object_or_404(ResourceFile, pk=resource_id, project=project)
    if variant == '0':
        variant = ''
    variant_to_delete = resource.variants.get(tags=variant)

    if resource.variants.count() == 1:
        return json_failure("You cannot delete the last remaining variant of a resource.")
    try:
        variant_to_delete.delete()
    except Exception as e:
        return json_failure(str(e))
    else:
        send_td_event('cloudpebble_delete_variant', data={
            'data': {
                'filename': resource.file_name,
                'kind': 'resource',
                'resource-kind': resource.kind,
                'variant': variant
            }
        }, request=request, project=project)

        return json_response({'resource': {
            'variants': [x.get_tags() for x in resource.variants.all()]
        }})
Exemplo n.º 16
0
def delete_variant(request, project_id, resource_id, variant):
    project = get_object_or_404(Project, pk=project_id, owner=request.user)
    resource = get_object_or_404(ResourceFile, pk=resource_id, project=project)
    if variant == '0':
        variant = ''
    variant_to_delete = resource.variants.get(tags=variant)

    if resource.variants.count() == 1:
        raise BadRequest(
            _("You cannot delete the last remaining variant of a resource."))

    variant_to_delete.delete()

    send_td_event('cloudpebble_delete_variant',
                  data={
                      'data': {
                          'filename': resource.file_name,
                          'kind': 'resource',
                          'resource-kind': resource.kind,
                          'variant': variant
                      }
                  },
                  request=request,
                  project=project)

    return {
        'resource': {
            'variants': [x.get_tags() for x in resource.variants.all()]
        }
    }
Exemplo n.º 17
0
def view_project(request, project_id):
    project = get_object_or_404(Project, pk=project_id, owner=request.user)
    if project.app_uuid is None:
        project.app_uuid = generate_half_uuid()
    if project.app_company_name is None:
        project.app_company_name = request.user.username
    if project.app_short_name is None:
        project.app_short_name = project.name
    if project.app_long_name is None:
        project.app_long_name = project.app_short_name
    if project.app_version_label is None:
        project.app_version_label = '1.0'
    app_keys = project.get_parsed_appkeys()

    send_td_event('cloudpebble_open_project', request=request, project=project)
    try:
        token = request.user.social_auth.get(provider='pebble').extra_data['access_token']
    except:
        token = ''
    return render(request, 'ide/project.html', {
        'project': project,
        'app_keys': app_keys,
        'font_css': settings.TYPOGRAPHY_CSS,
        'libpebble_proxy': json.dumps(settings.LIBPEBBLE_PROXY),
        'token': token,
        'phone_shorturl': settings.PHONE_SHORTURL,
        'supported_platforms': project.supported_platforms,
        'regexes': regexes,
        'regexes_json': json.dumps(regexes.regex_dictionary)
    })
Exemplo n.º 18
0
def view_project(request, project_id):
    project = get_object_or_404(Project, pk=project_id, owner=request.user)
    if project.app_uuid is None:
        project.app_uuid = generate_half_uuid()
    if project.app_company_name is None:
        project.app_company_name = request.user.username
    if project.app_short_name is None:
        project.app_short_name = project.name
    if project.app_long_name is None:
        project.app_long_name = project.app_short_name
    if project.app_version_label is None:
        project.app_version_label = '1.0'
    app_keys = project.get_parsed_appkeys()
    supported_platforms = ["aplite", "basalt"]
    if project.project_type != 'pebblejs' and project.sdk_version != '2':
        supported_platforms.append("chalk")

    send_td_event('cloudpebble_open_project', request=request, project=project)
    try:
        token = request.user.social_auth.get(provider='pebble').extra_data['access_token']
    except:
        token = ''
    return render(request, 'ide/project.html', {
        'project': project,
        'app_keys': app_keys,
        'font_css': settings.TYPOGRAPHY_CSS,
        'libpebble_proxy': json.dumps(settings.LIBPEBBLE_PROXY),
        'token': token,
        'phone_shorturl': settings.PHONE_SHORTURL,
        'supported_platforms': supported_platforms,
        'version_regex': SDK_VERSION_REGEX,
        'npm_manifest_support_enabled': settings.NPM_MANIFEST_SUPPORT
    })
Exemplo n.º 19
0
def remove_github_auth(request):
    try:
        user_github = request.user.github
        user_github.delete()
    except UserGithub.DoesNotExist:
        pass
    send_td_event('cloudpebble_github_revoked', request=request)
    return HttpResponseRedirect('/ide/settings')
Exemplo n.º 20
0
def remove_github_auth(request):
    try:
        user_github = request.user.github
        user_github.delete()
    except UserGithub.DoesNotExist:
        pass
    send_td_event("cloudpebble_github_revoked", request=request)
    return HttpResponseRedirect("/ide/settings")
Exemplo n.º 21
0
def delete_project(request, project_id):
    project = get_object_or_404(Project, pk=project_id, owner=request.user)
    if not bool(request.POST.get('confirm', False)):
        raise BadRequest(_("Not confirmed"))
    project.delete()
    send_td_event('cloudpebble_delete_project',
                  request=request,
                  project=project)
Exemplo n.º 22
0
def save_project_dependencies(request, project_id):
    project = get_object_or_404(Project, pk=project_id, owner=request.user)
    try:
        project.set_dependencies(json.loads(request.POST['dependencies']))
    except (IntegrityError, ValueError) as e:
        raise BadRequest(str(e))
    else:
        send_td_event('cloudpebble_save_project_settings', request=request, project=project)
Exemplo n.º 23
0
def create_project(request):
    name = request.POST['name']
    template_id = request.POST.get('template', None)
    if template_id is not None:
        template_id = int(template_id)
    project_type = request.POST.get('type', 'native')
    template_name = None
    sdk_version = str(request.POST.get('sdk', '2'))
    try:
        with transaction.atomic():
            app_keys = '{}' if sdk_version == '2' else '[]'
            project = Project.objects.create(
                name=name,
                owner=request.user,
                app_company_name=request.user.username,
                app_short_name=name,
                app_long_name=name,
                app_version_label='1.0',
                app_is_watchface=False,
                app_capabilities='',
                project_type=project_type,
                sdk_version=sdk_version,
                app_keys=app_keys)
            if template_id is not None and template_id != 0:
                template = TemplateProject.objects.get(pk=template_id)
                template_name = template.name
                template.copy_into_project(project)
            elif project_type == 'simplyjs':
                f = SourceFile.objects.create(project=project,
                                              file_name="app.js")
                f.save_text(
                    open('{}/src/html/demo.js'.format(
                        settings.SIMPLYJS_ROOT)).read())
            elif project_type == 'pebblejs':
                f = SourceFile.objects.create(project=project,
                                              file_name="app.js")
                f.save_text(
                    open('{}/src/js/app.js'.format(
                        settings.PEBBLEJS_ROOT)).read())
            # TODO: Default file for Rocky?
            project.full_clean()
            project.save()
    except IntegrityError as e:
        raise BadRequest(str(e))
    else:
        send_td_event(
            'cloudpebble_create_project',
            {'data': {
                'template': {
                    'id': template_id,
                    'name': template_name
                }
            }},
            request=request,
            project=project)

        return {"id": project.id}
Exemplo n.º 24
0
def import_gist(request, gist_id):
    send_td_event('cloudpebble_gist_landing',
                  data={'data': {
                      'gist_id': gist_id
                  }},
                  request=request)
    return render(request, 'ide/gist-import.html', {
        'gist_id': gist_id,
        'blurb': request.GET.get('blurb', None)
    })
Exemplo n.º 25
0
def save_project_dependencies(request, project_id):
    project = get_object_or_404(Project, pk=project_id, owner=request.user)
    try:
        project.set_dependencies(json.loads(request.POST['dependencies']))
        project.set_interdependencies([int(x) for x in json.loads(request.POST['interdependencies'])])
        return {'dependencies': project.get_dependencies()}
    except (IntegrityError, ValueError) as e:
        raise BadRequest(str(e))
    else:
        send_td_event('cloudpebble_save_project_settings', request=request, project=project)
Exemplo n.º 26
0
def delete_project(request, project_id):
    project = get_object_or_404(Project, pk=project_id, owner=request.user)
    if not bool(request.POST.get('confirm', False)):
        return json_failure("Not confirmed")
    try:
        project.delete()
    except Exception as e:
        return json_failure(str(e))
    else:
        send_td_event('cloudpebble_delete_project', request=request, project=project)
        return json_response({})
Exemplo n.º 27
0
def create_resource(request, project_id):
    project = get_object_or_404(Project, pk=project_id, owner=request.user)
    kind = request.POST['kind']
    resource_ids = json.loads(request.POST['resource_ids'])
    posted_file = request.FILES.get('file', None)
    file_name = request.POST['file_name']
    new_tags = json.loads(request.POST['new_tags'])
    resources = []
    try:
        with transaction.atomic():
            rf = ResourceFile.objects.create(project=project,
                                             file_name=file_name,
                                             kind=kind)
            for r in resource_ids:
                resource_options = decode_resource_id_options(r)
                resources.append(
                    ResourceIdentifier.objects.create(resource_file=rf,
                                                      **resource_options))
            if posted_file is not None:
                variant = ResourceVariant.objects.create(
                    resource_file=rf,
                    tags=",".join(str(int(t)) for t in new_tags))
                variant.save_file(posted_file, posted_file.size)

            rf.save()
    except IntegrityError as e:
        raise BadRequest(e)

    send_td_event('cloudpebble_create_file',
                  data={
                      'data': {
                          'filename': file_name,
                          'kind': 'resource',
                          'resource-kind': kind
                      }
                  },
                  request=request,
                  project=project)

    return {
        "file": {
            "id": rf.id,
            "kind": rf.kind,
            "file_name": rf.file_name,
            "resource_ids":
            [x.get_options_dict(with_id=True) for x in resources],
            "identifiers": [x.resource_id for x in resources],
            "variants": [x.get_tags() for x in rf.variants.all()],
            "extra": {
                y.resource_id: y.get_options_dict(with_id=False)
                for y in rf.identifiers.all()
            }
        }
    }
Exemplo n.º 28
0
def start_github_auth(request):
    nonce = uuid.uuid4().hex
    try:
        user_github = request.user.github
    except UserGithub.DoesNotExist:
        user_github = UserGithub.objects.create(user=request.user)
    user_github.nonce = nonce
    user_github.save()
    send_td_event('cloudpebble_github_started', request=request)
    return HttpResponseRedirect('https://github.com/login/oauth/authorize?client_id=%s&scope=repo&state=%s' %
                                (settings.GITHUB_CLIENT_ID, nonce))
Exemplo n.º 29
0
def start_github_auth(request):
    nonce = uuid.uuid4().hex
    try:
        user_github = request.user.github
    except UserGithub.DoesNotExist:
        user_github = UserGithub.objects.create(user=request.user)
    user_github.nonce = nonce
    user_github.save()
    send_td_event("cloudpebble_github_started", request=request)
    return HttpResponseRedirect(
        "https://github.com/login/oauth/authorize?client_id=%s&scope=repo&state=%s" % (settings.GITHUB_CLIENT_ID, nonce)
    )
Exemplo n.º 30
0
def delete_resource(request, project_id, resource_id):
    project = get_object_or_404(Project, pk=project_id, owner=request.user)
    resource = get_object_or_404(ResourceFile, pk=resource_id, project=project)

    resource.delete()
    send_td_event('cloudpebble_delete_file', data={
        'data': {
            'filename': resource.file_name,
            'kind': 'resource',
            'resource-kind': resource.kind
        }
    }, request=request, project=project)
Exemplo n.º 31
0
def save_published_media(request, project_id):
    project = get_object_or_404(Project, pk=project_id, owner=request.user)
    try:
        project.set_published_media(json.loads(
            request.POST['published_media']))
    except (IntegrityError, ValueError) as e:
        raise BadRequest(str(e))
    else:
        send_td_event('cloudpebble_save_published_media',
                      request=request,
                      project=project)
        return {'published_media': project.get_published_media()}
Exemplo n.º 32
0
def delete_source_file(request, project_id, file_id):
    project = get_object_or_404(Project, pk=project_id, owner=request.user)
    source_file = get_object_or_404(SourceFile, pk=file_id, project=project)

    source_file.delete()

    send_td_event('cloudpebble_delete_file', data={
        'data': {
            'filename': source_file.file_name,
            'kind': 'source'
        }
    }, request=request, project=project)
Exemplo n.º 33
0
def delete_resource(request, project_id, resource_id):
    project = get_object_or_404(Project, pk=project_id, owner=request.user)
    resource = get_object_or_404(ResourceFile, pk=resource_id, project=project)

    resource.delete()
    send_td_event('cloudpebble_delete_file', data={
        'data': {
            'filename': resource.file_name,
            'kind': 'resource',
            'resource-kind': resource.kind
        }
    }, request=request, project=project)
Exemplo n.º 34
0
def delete_source_file(request, project_id, file_id):
    project = get_object_or_404(Project, pk=project_id, owner=request.user)
    source_file = get_object_or_404(SourceFile, pk=file_id, project=project)

    source_file.delete()

    send_td_event('cloudpebble_delete_file', data={
        'data': {
            'filename': source_file.file_name,
            'kind': 'source'
        }
    }, request=request, project=project)
Exemplo n.º 35
0
def get_shortlink(request):
    from utils.td_helper import send_td_event
    url = request.POST['url']
    try:
        r = urllib2.Request('http://api.small.cat/entries', json.dumps({'value': url, 'duration': 60}), headers={'Content-Type': 'application/json'})
        response = json.loads(urllib2.urlopen(r).read())
    except urllib2.URLError as e:
        return json_failure(str(e))
    else:
        send_td_event('cloudpebble_generate_shortlink', data={
            'data': {'short_url': response['url']}
        }, request=request)
        return json_response({'url': response['url']})
Exemplo n.º 36
0
def build_log(request, project_id, build_id):
    project = get_object_or_404(Project, pk=project_id, owner=request.user)
    build = get_object_or_404(BuildResult, project=project, pk=build_id)

    log = build.read_build_log()

    send_td_event('cloudpebble_view_build_log', data={
        'data': {
            'build_state': build.state
        }
    }, request=request, project=project)

    return {"log": log}
Exemplo n.º 37
0
def build_log(request, project_id, build_id):
    project = get_object_or_404(Project, pk=project_id, owner=request.user)
    build = get_object_or_404(BuildResult, project=project, pk=build_id)

    log = build.read_build_log()

    send_td_event('cloudpebble_view_build_log', data={
        'data': {
            'build_state': build.state
        }
    }, request=request, project=project)

    return {"log": log}
Exemplo n.º 38
0
def npm_search(request):
    try:
        query = request.GET['q']
    except KeyError:
        return {'packages': []}
    search = requests.get('http://node-modules.com/search.json', {'q': query}).json()
    data = {'packages': [filter_dict(package, PACKAGE_SPEC) for package in search]}
    send_td_event('cloudpebble_package_search', data={
        'data': {
            'query': query
        }
    }, request=request)
    return data
Exemplo n.º 39
0
def delete_source_file(request, project_id, file_id):
    project = get_object_or_404(Project, pk=project_id, owner=request.user)
    source_file = get_object_or_404(SourceFile, pk=file_id, project=project)
    try:
        source_file.delete()
    except Exception as e:
        return json_failure(str(e))
    else:
        send_td_event('cloudpebble_delete_file', data={
            'data': {
                'filename': source_file.file_name,
                'kind': 'source'
            }
        }, request=request, project=project)
        return json_response({})
Exemplo n.º 40
0
def build_log(request, project_id, build_id):
    project = get_object_or_404(Project, pk=project_id, owner=request.user)
    build = get_object_or_404(BuildResult, project=project, pk=build_id)
    try:
        log = build.read_build_log()
    except Exception as e:
        return json_failure(str(e))

    send_td_event('cloudpebble_view_build_log', data={
        'data': {
            'build_state': build.state
        }
    }, request=request, project=project)

    return json_response({"log": log})
Exemplo n.º 41
0
def npm_info(request):
    query = request.GET['q']

    try:
        package = requests.get('http://node-modules.com/package/%s.json' %
                               urllib.quote(query)).json()
    except ValueError:
        raise Http404("Package not found")

    data = {'package': filter_dict(package, PACKAGE_SPEC)}
    send_td_event('cloudpebble_package_get_info',
                  data={'data': {
                      'query': query
                  }},
                  request=request)
    return data
Exemplo n.º 42
0
def npm_info(request):
    query = request.GET['q']

    try:
        package = requests.get('http://node-modules.com/package/%s.json' % urllib.quote(query)).json()
    except ValueError:
        raise Http404("Package not found")

    data = {
        'package': filter_dict(package, PACKAGE_SPEC)
    }
    send_td_event('cloudpebble_package_get_info', data={
        'data': {
            'query': query
        }
    }, request=request)
    return data
Exemplo n.º 43
0
def npm_search(request):
    try:
        query = request.GET['q']
    except KeyError:
        return {'packages': []}
    search = requests.get('http://node-modules.com/search.json', {
        'q': query
    }).json()
    data = {
        'packages': [filter_dict(package, PACKAGE_SPEC) for package in search]
    }
    send_td_event('cloudpebble_package_search',
                  data={'data': {
                      'query': query
                  }},
                  request=request)
    return data
Exemplo n.º 44
0
def proxy_keen(request, project_id):
    from utils.td_helper import send_td_event
    project = get_object_or_404(Project, pk=project_id)

    acceptable_events = {
        'app_install_succeeded',
        'websocket_connection_failed',
        'app_install_failed',
        'app_log_view',
        'app_log_clear',
        'app_log_download',
        'app_logged_crash',
        'sdk_screenshot_success',
        'sdk_screenshot_failed',
        'cloudpebble_created_ui_layout',
        'cloudpebble_ib_displayed',
        'cloudpebble_ib_created_layer',
        'cloudpebble_android_beta_modal',
        'cloudpebble_android_beta_download',
        'qemu_launched',
        'cloudpebble_timeline_displayed',
        'sdk_pin_inserted',
        'sdk_pin_deleted',
        'cloudpebble_fuzzyprompt_action'
    }

    event = request.POST['event']
    if event not in acceptable_events:
        return json_failure("nope.")

    data = {}
    if 'data' in request.POST:
        data['data'] = json.loads(request.POST['data'])

    if 'device' in request.POST:
        data['device'] = json.loads(request.POST['device'])

    collections = ['cloudpebble', 'sdk']
    if 'collections' in request.POST:
        collections = list(set(collections) & set(json.loads(request.POST['collections'])))

    if len(data.items()) == 0:
        data = None

    send_td_event(event, data=data, request=request, project=project)
    return json_response({})
Exemplo n.º 45
0
def save_project_settings(request, project_id):
    project = get_object_or_404(Project, pk=project_id, owner=request.user)
    try:
        with transaction.atomic():

            project.name = request.POST['name']
            project.app_uuid = request.POST['app_uuid']
            project.app_company_name = request.POST['app_company_name']
            project.app_short_name = request.POST['app_short_name']
            project.app_long_name = request.POST['app_long_name']
            project.app_version_label = request.POST['app_version_label']
            project.app_is_watchface = bool(
                int(request.POST['app_is_watchface']))
            project.app_is_hidden = bool(int(request.POST['app_is_hidden']))
            project.app_is_shown_on_communication = bool(
                int(request.POST['app_is_shown_on_communication']))
            project.app_capabilities = request.POST['app_capabilities']
            project.app_keys = request.POST['app_keys']
            project.app_jshint = bool(int(request.POST['app_jshint']))
            project.sdk_version = request.POST['sdk_version']
            project.app_platforms = request.POST['app_platforms']
            project.app_modern_multi_js = bool(
                int(request.POST['app_modern_multi_js']))

            menu_icon = request.POST['menu_icon']
            old_icon = project.menu_icon
            if menu_icon != '':
                menu_icon = int(menu_icon)
                if old_icon is not None:
                    old_icon.is_menu_icon = False
                    old_icon.save()
                icon_resource = project.resources.filter(id=menu_icon)[0]
                icon_resource.is_menu_icon = True
                icon_resource.save()
            elif old_icon is not None:
                old_icon.is_menu_icon = False
                old_icon.save()

            project.save()
    except IntegrityError as e:
        return BadRequest(str(e))
    else:
        send_td_event('cloudpebble_save_project_settings',
                      request=request,
                      project=project)
Exemplo n.º 46
0
def export_user_projects(user_id):
    user = User.objects.get(pk=user_id)
    projects = Project.objects.filter(owner=user)
    with tempfile.NamedTemporaryFile(suffix='.zip', delete=False) as temp:
        filename = temp.name
        with zipfile.ZipFile(filename, 'w', compression=zipfile.ZIP_DEFLATED) as z:
            for project in projects:
                add_project_to_archive(z, project, prefix='cloudpebble-export/')

        # Generate a URL
        u = uuid.uuid4().hex
        outfile = '%s%s/%s.zip' % (settings.EXPORT_DIRECTORY, u, 'cloudpebble-export')
        os.makedirs(os.path.dirname(outfile), 0755)
        shutil.copy(filename, outfile)
        os.chmod(outfile, 0644)

        send_td_event('cloudpebble_export_all_projects', user=user)
        return '%s%s/%s.zip' % (settings.EXPORT_ROOT, u, 'cloudpebble-export')
Exemplo n.º 47
0
def export_user_projects(user_id):
    user = User.objects.get(pk=user_id)
    projects = Project.objects.filter(owner=user)
    with tempfile.NamedTemporaryFile(suffix='.zip', delete=False) as temp:
        filename = temp.name
        with zipfile.ZipFile(filename, 'w', compression=zipfile.ZIP_DEFLATED) as z:
            for project in projects:
                add_project_to_archive(z, project, prefix='cloudpebble-export/')

        # Generate a URL
        u = uuid.uuid4().hex
        outfile = '%s%s/%s.zip' % (settings.EXPORT_DIRECTORY, u, 'cloudpebble-export')
        os.makedirs(os.path.dirname(outfile), 0755)
        shutil.copy(filename, outfile)
        os.chmod(outfile, 0644)

        send_td_event('cloudpebble_export_all_projects', user=user)
        return '%s%s/%s.zip' % (settings.EXPORT_ROOT, u, 'cloudpebble-export')
Exemplo n.º 48
0
def create_project(request):
    name = request.POST['name']
    template_id = request.POST.get('template', None)
    if template_id is not None:
        template_id = int(template_id)
    project_type = request.POST.get('type', 'native')
    template_name = None
    sdk_version = str(request.POST.get('sdk', '2'))
    try:
        with transaction.atomic():
            app_keys = '{}' if sdk_version == '2' else '[]'
            project = Project.objects.create(
                name=name,
                owner=request.user,
                app_company_name=request.user.username,
                app_short_name=name,
                app_long_name=name,
                app_version_label='1.0',
                app_is_watchface=False,
                app_capabilities='',
                project_type=project_type,
                sdk_version=sdk_version,
                app_keys=app_keys
            )
            if template_id is not None and template_id != 0:
                template = TemplateProject.objects.get(pk=template_id)
                template_name = template.name
                template.copy_into_project(project)
            elif project_type == 'simplyjs':
                f = SourceFile.objects.create(project=project, file_name="app.js")
                f.save_text(open('{}/src/html/demo.js'.format(settings.SIMPLYJS_ROOT)).read())
            elif project_type == 'pebblejs':
                f = SourceFile.objects.create(project=project, file_name="app.js")
                f.save_text(open('{}/src/js/app.js'.format(settings.PEBBLEJS_ROOT)).read())
            # TODO: Default file for Rocky?
            project.full_clean()
            project.save()
    except IntegrityError as e:
        raise BadRequest(str(e))
    else:
        send_td_event('cloudpebble_create_project', {'data': {'template': {'id': template_id, 'name': template_name}}},
                      request=request, project=project)

        return {"id": project.id}
Exemplo n.º 49
0
def create_source_file(request, project_id):
    project = get_object_or_404(Project, pk=project_id, owner=request.user)
    try:
        f = SourceFile.objects.create(project=project,
                                      file_name=request.POST['name'],
                                      target=request.POST.get('target', 'app'))
        f.save_file(request.POST.get('content', ''))
    except IntegrityError as e:
        return json_failure(str(e))
    else:
        send_td_event('cloudpebble_create_file', data={
            'data': {
                'filename': request.POST['name'],
                'kind': 'source',
                'target': f.target,
            }
        }, request=request, project=project)

        return json_response({"file": {"id": f.id, "name": f.file_name, "target": f.target}})
Exemplo n.º 50
0
def create_project_repo(request, project_id):
    project = get_object_or_404(Project, pk=project_id, owner=request.user)
    repo = request.POST['repo']
    description = request.POST['description']

    repo = ide.git.create_repo(request.user, repo, description)

    project.github_repo = repo.full_name
    project.github_branch = "master"
    project.github_last_sync = None
    project.github_last_commit = None
    project.save()

    send_td_event('cloudpebble_created_github_repo', data={
        'data': {
            'repo': project.github_repo
        }
    }, request=request, project=project)

    return {"repo": repo.html_url}
Exemplo n.º 51
0
def settings_page(request):
    user_settings = request.user.settings
    try:
        github = request.user.github
    except UserGithub.DoesNotExist:
        github = None

    if request.method == "POST":
        form = SettingsForm(request.POST, instance=user_settings)
        if form.is_valid():
            form.save()
            send_td_event("cloudpebble_change_user_settings", request=request)
            return render(request, "ide/settings.html", {"form": form, "saved": True, "github": github})

    else:
        form = SettingsForm(instance=user_settings)

    send_td_event("cloudpebble_view_user_settings", request=request)

    return render(request, "ide/settings.html", {"form": form, "saved": False, "github": github})
Exemplo n.º 52
0
def create_project_repo(request, project_id):
    project = get_object_or_404(Project, pk=project_id, owner=request.user)
    repo = request.POST['repo']
    description = request.POST['description']

    repo = ide.git.create_repo(request.user, repo, description)

    project.github_repo = repo.full_name
    project.github_branch = "master"
    project.github_last_sync = None
    project.github_last_commit = None
    project.save()

    send_td_event('cloudpebble_created_github_repo', data={
        'data': {
            'repo': project.github_repo
        }
    }, request=request, project=project)

    return {"repo": repo.html_url}
Exemplo n.º 53
0
def settings_page(request):
    user_settings = request.user.settings
    try:
        github = request.user.github
    except UserGithub.DoesNotExist:
        github = None

    if request.method == 'POST':
        form = SettingsForm(request.POST, instance=user_settings)
        if form.is_valid():
            form.save()
            send_td_event('cloudpebble_change_user_settings', request=request)
            return render(request, 'ide/settings.html', {'form': form, 'saved': True, 'github': github})

    else:
        form = SettingsForm(instance=user_settings)

    send_td_event('cloudpebble_view_user_settings', request=request)

    return render(request, 'ide/settings.html', {'form': form, 'saved': False, 'github': github})
Exemplo n.º 54
0
def save_project_settings(request, project_id):
    project = get_object_or_404(Project, pk=project_id, owner=request.user)
    try:
        with transaction.atomic():
            project.name = request.POST['name']
            project.app_uuid = request.POST['app_uuid']
            project.app_company_name = request.POST['app_company_name']
            project.app_short_name = request.POST['app_short_name']
            project.app_long_name = request.POST['app_long_name']
            project.app_version_label = request.POST['app_version_label']
            project.app_is_watchface = bool(int(request.POST['app_is_watchface']))
            project.app_is_hidden = bool(int(request.POST['app_is_hidden']))
            project.app_is_shown_on_communication = bool(int(request.POST['app_is_shown_on_communication']))
            project.app_capabilities = request.POST['app_capabilities']
            project.app_keys = request.POST['app_keys']
            project.app_jshint = bool(int(request.POST['app_jshint']))
            project.sdk_version = request.POST['sdk_version']
            project.app_platforms = request.POST['app_platforms']
            project.app_modern_multi_js = bool(int(request.POST['app_modern_multi_js']))

            menu_icon = request.POST['menu_icon']
            old_icon = project.menu_icon
            if menu_icon != '':
                menu_icon = int(menu_icon)
                if old_icon is not None:
                    old_icon.is_menu_icon = False
                    old_icon.save()
                icon_resource = project.resources.filter(id=menu_icon)[0]
                icon_resource.is_menu_icon = True
                icon_resource.save()
            elif old_icon is not None:
                old_icon.is_menu_icon = False
                old_icon.save()

            project.save()
    except IntegrityError as e:
        return json_failure(str(e))
    else:
        send_td_event('cloudpebble_save_project_settings', request=request, project=project)

        return json_response({})
Exemplo n.º 55
0
def create_resource(request, project_id):
    project = get_object_or_404(Project, pk=project_id, owner=request.user)
    kind = request.POST['kind']
    resource_ids = json.loads(request.POST['resource_ids'])
    posted_file = request.FILES.get('file', None)
    file_name = request.POST['file_name']
    new_tags = json.loads(request.POST['new_tags'])
    resources = []
    try:
        with transaction.atomic():
            rf = ResourceFile.objects.create(project=project, file_name=file_name, kind=kind)
            for r in resource_ids:
                resource_options = decode_resource_id_options(r)
                resources.append(ResourceIdentifier.objects.create(resource_file=rf, **resource_options))
            if posted_file is not None:
                variant = ResourceVariant.objects.create(resource_file=rf, tags=",".join(str(int(t)) for t in new_tags))
                variant.save_file(posted_file, posted_file.size)

            rf.save()

    except Exception as e:
        return json_failure(str(e))
    else:
        send_td_event('cloudpebble_create_file', data={
            'data': {
                'filename': file_name,
                'kind': 'resource',
                'resource-kind': kind
            }
        }, request=request, project=project)

        return json_response({"file": {
            "id": rf.id,
            "kind": rf.kind,
            "file_name": rf.file_name,
            "resource_ids": [x.get_options_dict(with_id=True) for x in resources],
            "identifiers": [x.resource_id for x in resources],
            "variants": [x.get_tags() for x in rf.variants.all()],
            "extra": {y.resource_id: y.get_options_dict(with_id=False) for y in rf.identifiers.all()}
        }})
Exemplo n.º 56
0
def rename_source_file(request, project_id, file_id):
    project = get_object_or_404(Project, pk=project_id, owner=request.user)
    source_file = get_object_or_404(SourceFile, pk=file_id, project=project)
    old_filename = source_file.file_name

    if source_file.file_name != request.POST['old_name']:
        send_td_event('cloudpebble_rename_abort_unsafe', data={
            'data': {
                'filename': source_file.file_name,
                'kind': 'source'
            }
        }, request=request, project=project)
        raise BadRequest(_("Could not rename, file has been renamed already."))
    if source_file.was_modified_since(int(request.POST['modified'])):
        send_td_event('cloudpebble_rename_abort_unsafe', data={
            'data': {
                'filename': source_file.file_name,
                'kind': 'source',
                'modified': time.mktime(source_file.last_modified.utctimetuple()),
            }
        }, request=request, project=project)
        raise BadRequest(_("Could not rename, file has been modified since last save."))
    source_file.file_name = request.POST['new_name']
    source_file.save()

    send_td_event('cloudpebble_rename_file', data={
        'data': {
            'old_filename': old_filename,
            'new_filename': source_file.file_name,
            'kind': 'source'
        }
    }, request=request, project=project)
    return {"modified": time.mktime(source_file.last_modified.utctimetuple())}
Exemplo n.º 57
0
def create_archive(project_id):
    project = Project.objects.get(pk=project_id)
    prefix = re.sub(r'[^\w]+', '_', project.name).strip('_').lower()
    with tempfile.NamedTemporaryFile(suffix='.zip', delete=False) as temp:
        filename = temp.name
        with zipfile.ZipFile(filename, 'w', compression=zipfile.ZIP_DEFLATED) as z:
            add_project_to_archive(z, project)

        # Generate a URL
        u = uuid.uuid4().hex

        send_td_event('cloudpebble_export_project', project=project)

        if not settings.AWS_ENABLED:
            outfile = '%s%s/%s.zip' % (settings.EXPORT_DIRECTORY, u, prefix)
            os.makedirs(os.path.dirname(outfile), 0755)
            shutil.copy(filename, outfile)
            os.chmod(outfile, 0644)
            return '%s%s/%s.zip' % (settings.EXPORT_ROOT, u, prefix)
        else:
            outfile = '%s/%s.zip' % (u, prefix)
            s3.upload_file('export', outfile, filename, public=True, content_type='application/zip')
            return '%s%s' % (settings.EXPORT_ROOT, outfile)