Esempio n. 1
0
 def GET(self):
     userid = web.ctx.session.get('userid',-1)
     superuser = is_superuser(userid=userid)
     if not is_superuser(userid):
         raise web.seeother("/index", absolute=True)
     username = get_username(userid=userid)
     index_wiki = get_page()
     ctx = Storage(locals())
     return render.edit_index(ctx) 
Esempio n. 2
0
def videoCreationBatch():
    from auth import get_user, is_superuser
    if not is_superuser():
        return action_401()
    if request.method=="GET":
        chdir(config.INGEST_DIRECTORY)
        files=[f for f in listdir(getcwd()) if f[0] != '.']
        return json.dumps(files)
    else:
        packet=request.json

        ids = [up.get('id') for up in packet]

        if len(set(ids)) is not len(ids):
            return bundle_400("Duplicate IDs found. Cannot update." % s)

        # test everything before we start ingesting, otherwise half the batch
        # might get completed before we get an error. easier to just reject everything
        # than half of everything
        for up in packet:
            i = up['id']
            dupe = assets.find_one({'@graph.ma:locator': {'$elemMatch': {'@id': i}}})
            mp4 = (unicode(config.MEDIA_DIRECTORY) + i + '.mp4').encode('utf-8')
            webm = (unicode(config.MEDIA_DIRECTORY) + i + '.webm').encode('utf-8')
            if path.isfile(mp4) or path.isfile(webm) or dupe is not None:
                return bundle_400("That file (%s) already exists; try another unique ID." %i)

        for up in packet:
            result = MediaAsset.set_new_file(up['pid'], up['id'], up['filepath'])
            if not result[0]:
                return bundle_400(result[1])

	return "Success"
Esempio n. 3
0
 def GET(self):
     userid = web.ctx.session.get('userid',-1)
     username = get_username(userid=userid)
     superuser = is_superuser(userid=userid)
     index_wiki = get_page()
     ctx = Storage(locals())
     return render.index(ctx)
Esempio n. 4
0
def audioCreationBatch():
    import mutagen
    import uuid
    import os
    from werkzeug.utils import secure_filename
    from auth import is_superuser

    if not is_superuser():
        return action_401()

    files = request.files.getlist('audio[]')

    if not len(files):
        return bundle_400("Missing form field 'audio[]'")

    incompatible = filter(lambda x: not x.filename.endswith('mp3'), files)

    if len(incompatible):
        return bundle_400("Only MP3 files are supported.")

    results = []
    for f in files:
        ext = f.filename.split('.')[-1]
        filename = secure_filename(f.filename.split('.', 1)[0]) \
                   + str(uuid.uuid4()) + '.' + ext

        path = os.path.join(config.MEDIA_DIRECTORY, filename)
        f.save(path)

        id3 = mutagen.File(path, easy=True)  # metadata
        _id = str(ObjectId())

        audio = assets.Video()
        audio['_id'] = _id
        audio['@graph']['dc:type'] = 'hummedia:type/humaudio'
        audio['@graph']['pid'] = _id
        audio['@graph']['ma:title'] = id3.get('title', [f.filename])[0]
        audio['@graph']['ma:hasContributor'] = [{
            '@id': '',
            'name': x
        } for x in id3.get('artist', [])]

        try:
            audio['@graph']["ma:date"] = int(id3.get('date')[0])
        except:
            audio['@graph'][
                'ma:date'] = 1970  # TODO: this requires a number, but I don't have one for it

        audio['@graph']["ma:locator"] = [{
            "@id":
            '.'.join(filename.split('.')[0:-1]),
            "ma:hasFormat":
            "audio/" + ext,
            "ma:hasCompression": {}
        }]
        audio.save()
        audio['@graph']['ma:locator'][0]['@id'] += '.mp3'
        results.append(audio['@graph'])

    return mongo_jsonify(results)
Esempio n. 5
0
def videoCreationBatch():
    from auth import get_user, is_superuser
    if not is_superuser():
        return action_401()
    if request.method=="GET":
        chdir(config.INGEST_DIRECTORY)
        files=[f for f in listdir(getcwd()) if f[0] != '.']
        return json.dumps(files)
    else:
        from PIL import Image
        from shutil import move
        from helpers import getVideoInfo
        packet=request.json
        for up in packet:
            filepath=unicode(config.INGEST_DIRECTORY + up['filepath'])
	    new_file=unicode(config.MEDIA_DIRECTORY + up['id'] + ".mp4")
	    if path.isfile(new_file):
		return bundle_400("That file already exists; try another unique ID.")
            if path.isfile(filepath.encode('utf-8')):
                md=getVideoInfo(filepath.encode('utf-8'))
                poster = config.POSTERS_DIRECTORY + "%s.jpg" % (up["id"])
                thumb = config.POSTERS_DIRECTORY + "%s_thumb.jpg" % (up["id"])
                move(filepath.encode('utf-8'), new_file.encode('utf-8'))
                assets.update({"_id":up["pid"]},{"$set":{
                    "@graph.ma:frameRate":float(md["framerate"]),
                    "@graph.ma:averageBitRate":int(float(md["bitrate"])),
                    "@graph.ma:frameWidth":int(md["width"]),
                    "@graph.ma:frameHeight":int(md["height"]),
                    "@graph.ma:duration":int( round(float(md["duration"])) )/60,
                    "@graph.ma:locator": [
                        {
                            "@id": up["id"],
                            "ma:hasFormat": "video/mp4",
                            "ma:hasCompression": {"@id":"http://www.freebase.com/view/en/h_264_mpeg_4_avc","name": "avc.42E01E"}
                        },
                        {
                            "@id": up["id"],
                            "ma:hasFormat": "video/webm",
                            "ma:hasCompression": {"@id":"http://www.freebase.com/m/0c02yk5","name":"vp8.0"}
                        }
                    ]
                }})
                imgcmd = "avconv -i '%s' -q:v 1 -r 1 -t 00:00:01 -ss 00:00:30 -f image2 '%s'" % (new_file,poster)
                system(imgcmd.encode('utf-8'))
                chmod(poster,0775)
                im=Image.open(poster)
                im.thumbnail((160,90))
                im.save(thumb)
                chmod(thumb,0775)
                
                if not app.config.get('TESTING'):
                    from gearman import GearmanClient
                    client = GearmanClient(config.GEARMAN_SERVERS)
                    client.submit_job("generate_webm", str(up["id"]))
                else:
                    from ingest import generate_webm
                    result = generate_webm(file_id=up['id'])
                    if result == "ERROR":
                      raise Exception("Could not convert media file.")
	return "Success"
Esempio n. 6
0
def audioCreationBatch():
    import mutagen
    import uuid
    import os
    from werkzeug.utils import secure_filename
    from auth import is_superuser

    if not is_superuser():
      return action_401()

    files = request.files.getlist('audio[]')
    
    if not len(files):
      return bundle_400("Missing form field 'audio[]'")

    incompatible = filter(lambda x: not x.filename.endswith('mp3'), files)
    
    if len(incompatible):
      return bundle_400("Only MP3 files are supported.")

    results = []
    for f in files:
        ext = f.filename.split('.')[-1]
        filename = secure_filename(f.filename.split('.', 1)[0]) \
                   + str(uuid.uuid4()) + '.' + ext

        path = os.path.join(config.MEDIA_DIRECTORY, filename)
        f.save(path)

        id3 = mutagen.File(path, easy=True) # metadata
        _id = str(ObjectId())

        audio = assets.Video()
        audio['_id'] = _id
        audio['@graph']['dc:type'] = 'hummedia:type/humaudio'
        audio['@graph']['pid'] = _id
        audio['@graph']['ma:title'] = id3.get('title',[f.filename])[0]
        audio['@graph']['ma:hasContributor'] = [{'@id': '', 'name': x} for x in id3.get('artist',[])]

        try:
            audio['@graph']["ma:date"] = int(id3.get('date')[0])
        except:
            audio['@graph']['ma:date'] = 1970 # TODO: this requires a number, but I don't have one for it

        audio['@graph']["ma:locator"] = [
             {
                 "@id": '.'.join(filename.split('.')[0:-1]),
                 "ma:hasFormat": "audio/" + ext,
                 "ma:hasCompression": {}
             }
        ]
        audio.save()
        audio['@graph']['ma:locator'][0]['@id'] += '.mp3'
        results.append(audio['@graph'])

    return mongo_jsonify(results)
Esempio n. 7
0
 def GET(self):
     userid = web.ctx.session.get('userid', -1)
     superuser = is_superuser(userid)
     if userid == -1 or not is_superuser(userid):
         raise web.seeother("/index", absolute=True)
     username = get_username(userid=userid)
     all_pending_servers = get_all_pending_servers().list()
     all_running_servers = get_tenant_servers(tenant_name=os_tenant_name)
     images = get_images(os_tenant_name)
     images_dict = dict([(i.id, i.name) for i in images])
     all_pending_servers_x = []
     for pending_server in all_pending_servers:
         if pending_server.image not in images_dict:
             delete_pending_server(id=pending_server.id)
         else:
             all_pending_servers_x.append(pending_server)
     all_pending_servers = all_pending_servers_x
     flavors = get_flavors(os_tenant_name)
     flavors_dict = dict([(f.id,'cpus:%s ram:%s disk:%s'%(f.vcpus, f.ram, f.disk)) for f in flavors])
     tenants_dict = dict([(t.id, t.name) for t in get_all_tenants()]) 
     ctx = Storage(locals()) 
     return render.admin(ctx)
Esempio n. 8
0
 def GET(self):
     userid = web.ctx.session.get('userid',-1)
     superuser = is_superuser(userid)
     username = get_username(userid=userid)
     tenant_name = username
     servers = get_servers(userid).list()
     running_servers = get_tenant_servers_db(tenant_name)
     images_dict = get_images_dict_db()
     servers_x = []
     for server in servers:
         if server.image not in images_dict:
             delete_server(image=server.image) 
         else:
             servers_x.append(server)
     servers = servers_x
     flavors_dict = get_flavors_dict_db()
     floating_ips = get_floatingips_db(tenant_name)
     ctx = Storage(locals())
     return render.home(ctx)