def get_list(self): if "concise" in self.request.args: self.bundle = self.auth_filter() return mongo_jsonify(map(lambda x: x['@graph'], self.bundle)) alist = [] self.bundle = self.auth_filter() thumbRetriever = [] for d in self.bundle: alist.append( self.model.make_part(d["@graph"], config.APIHOST, self.request.args.get("part", "details"))) thumbRetriever.extend(alist[-1].get("fromYt")) alist[-1].pop("fromYt", None) ytThumbs = getYtThumbs(thumbRetriever) for vid in alist: for image in vid["ma:image"]: if image.get("ytId"): try: image["thumb"] = ytThumbs[image["ytId"]]["thumb"] image["poster"] = ytThumbs[image["ytId"]]["poster"] except Exception: image["thumb"] = None image["poster"] = None image.pop("ytId", None) return mongo_jsonify(alist)
def serialize_bundle(self,payload): if payload: v=assets.find({"@graph.ma:isMemberOf.@id":payload["_id"]}) payload["@graph"]["videos"]=[] if not is_enrolled(payload) and not (payload['@graph']['dc:coverage'] == 'public'): v=self.auth_filter(v) thumbRetriever=[] for vid in v: if self.request.args.get("full",False): resource=uri_pattern(vid["@graph"]["pid"],config.APIHOST+"/video") vid["@graph"]["type"]=resolve_type(vid["@graph"]["dc:type"]) vid["@graph"]["resource"]=resource vid["@graph"]["ma:image"]=[] annot=self.find_by_relations(vid['@graph']['pid'], payload['_id']) try: vid['@graph']['transcript']=bool(annot['@graph']['vcp:playSettings']['vcp:showTranscript']) except (TypeError, KeyError): vid['@graph']['transcript']=False if vid["@graph"]["type"]=="humvideo": needs_ext=True elif 'type' in payload['@graph'] and payload['@graph']['type']=='humaudio': needs_ext=True elif vid["@graph"]["type"]=="yt": needs_ext=False for location in vid["@graph"]["ma:locator"]: if needs_ext: poster=uri_pattern(location["@id"]+".jpg",config.HOST+"/posters") thumb=uri_pattern(location["@id"]+"_thumb.jpg",config.HOST+"/posters") vid["@graph"]["ma:image"].append({"poster":poster,"thumb":thumb}) else: loc=location["@id"] vid["@graph"]["ma:image"].append({"ytId":loc}) thumbRetriever.append(loc) payload["@graph"]['videos'].append(vid["@graph"]) else: payload["@graph"]["videos"].append(assets.Video.make_part(vid["@graph"],config.APIHOST,self.request.args.get("part","details"))) thumbRetriever.extend(payload["@graph"]["videos"][-1].get("fromYt")) payload["@graph"]["videos"][-1].pop("fromYt",None) payload["@graph"]["type"]=resolve_type(payload["@graph"]["dc:type"]) ytThumbs=getYtThumbs(thumbRetriever) for vid in payload["@graph"]["videos"]: for image in vid["ma:image"]: if image.get("ytId"): try: image["thumb"] = ytThumbs[image["ytId"]]["thumb"] image["poster"] = ytThumbs[image["ytId"]]["poster"] except KeyError: image["thumb"] = None image["poster"] = None image.pop("ytId",None) return mongo_jsonify(payload["@graph"]) else: return mongo_jsonify({})
def serialize_bundle(self,payload): if payload: v=assets.find({"@graph.ma:isMemberOf.@id":payload["_id"]}) payload["@graph"]["videos"]=[] if not is_enrolled(payload) and not (payload['@graph']['dc:coverage'] == 'public'): v=self.auth_filter(v) thumbRetriever=[] for vid in v: if self.request.args.get("full",False): resource=uri_pattern(vid["@graph"]["pid"],config.APIHOST+"/video") vid["@graph"]["type"]=resolve_type(vid["@graph"]["dc:type"]) vid["@graph"]["resource"]=resource vid["@graph"]["ma:image"]=[] annot=self.find_by_relations(vid['@graph']['pid'], payload['_id']) try: vid['@graph']['transcript']=bool(annot['@graph']['vcp:playSettings']['vcp:showTranscript']) except (TypeError, KeyError): vid['@graph']['transcript']=False if vid["@graph"]["type"]=="humvideo": needs_ext=True elif vid["@graph"]["type"]=="yt": needs_ext=False for location in vid["@graph"]["ma:locator"]: if needs_ext: poster=uri_pattern(location["@id"]+".jpg",config.HOST+"/posters") thumb=uri_pattern(location["@id"]+"_thumb.jpg",config.HOST+"/posters") vid["@graph"]["ma:image"].append({"poster":poster,"thumb":thumb}) else: loc=location["@id"] vid["@graph"]["ma:image"].append({"ytId":loc}) thumbRetriever.append(loc) payload["@graph"]['videos'].append(vid["@graph"]) else: payload["@graph"]["videos"].append(assets.Video.make_part(vid["@graph"],config.APIHOST,self.request.args.get("part","details"))) thumbRetriever.extend(payload["@graph"]["videos"][-1].get("fromYt")) payload["@graph"]["videos"][-1].pop("fromYt",None) payload["@graph"]["type"]=resolve_type(payload["@graph"]["dc:type"]) ytThumbs=getYtThumbs(thumbRetriever) for vid in payload["@graph"]["videos"]: for image in vid["ma:image"]: if image.get("ytId"): image["thumb"] = ytThumbs[image["ytId"]]["thumb"] image["poster"] = ytThumbs[image["ytId"]]["poster"] image.pop("ytId",None) return mongo_jsonify(payload["@graph"]) else: return mongo_jsonify({})
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)
def delete_subtitle(self, filename): from os import remove from helpers import endpoint_404 query = { "@graph.ma:hasRelatedResource": { "$elemMatch": { "@id": filename } } } bundle = self.model.find_one(query) if bundle is None: return endpoint_404() if not self.acl_write_check(bundle): return action_401() l = bundle.get("@graph").get("ma:hasRelatedResource") l[:] = [d for d in l if d.get('@id') != filename] bundle.save() remove(config.SUBTITLE_DIRECTORY + filename) return mongo_jsonify(bundle)
def serialize_bundle(self,payload): payload["@graph"]["resource"]=uri_pattern(payload["@graph"]["pid"],config.APIHOST+"/"+self.endpoint) payload["@graph"]["type"]=resolve_type(payload["@graph"]["dc:type"]) payload["@graph"]["url"]=[] payload["@graph"]["ma:image"]=[] if payload["@graph"]["type"]=="humvideo": prefix=config.HOST + '/' needs_ext=True elif payload['@graph']['type']=='humaudio': prefix=config.HOST + '/' needs_ext=True elif payload["@graph"]["type"]=="yt": prefix="http://youtu.be" needs_ext=False fromYt=[] for location in payload["@graph"]["ma:locator"]: if needs_ext: ext=location["ma:hasFormat"].split("/")[-1] fileName= '/' + location["@id"] + "." + ext hexTime="{0:x}".format(int(time.time())) token = hashlib.md5(''.join([ config.AUTH_TOKEN_SECRET, fileName, hexTime, request.remote_addr if config.AUTH_TOKEN_IP else '' ])).hexdigest() loc = ''.join([ config.AUTH_TOKEN_PREFIX, token, "/", hexTime, fileName ]) poster=uri_pattern(location["@id"]+".jpg",config.HOST+"/posters") thumb=uri_pattern(location["@id"]+"_thumb.jpg",config.HOST+"/posters") payload["@graph"]["ma:image"].append({"poster":poster,"thumb":thumb}) else: loc=location["@id"] fromYt.append(loc) payload["@graph"]["ma:image"].append({"ytId":loc}) payload["@graph"]["url"].append(uri_pattern(loc,prefix)) ytThumbs=getYtThumbs(fromYt) for image in payload["@graph"]["ma:image"]: if image.get("ytId"): image["thumb"] = ytThumbs[image["ytId"]]["thumb"] image["poster"] = ytThumbs[image["ytId"]]["poster"] image.pop("ytId",None) for annot in payload["@graph"]["ma:isMemberOf"]: coll=ags.find_one({"_id":annot["@id"]}) annot["title"]=coll["@graph"]["dc:title"] try: details=annotations.find_one({"_id":annot["restrictor"]}) annot["transcript"]=bool(details['@graph']['vcp:playSettings']['vcp:showTranscript']) except (KeyError, TypeError): annot["transcript"] = False try: for track in payload["@graph"]["ma:hasRelatedResource"]: track["@id"]=uri_pattern(track["@id"],config.HOST+"/text") except KeyError: pass return mongo_jsonify(payload["@graph"])
def get_list(self): alist=[] self.bundle=self.auth_filter() if self.bundle: for d in self.bundle: d["@graph"]["resource"]=uri_pattern(d["@graph"]["pid"],config.APIHOST+"/"+self.endpoint) d["@graph"]["type"]=resolve_type(d["@graph"]["dc:type"]) alist.append(d["@graph"]) return mongo_jsonify(alist)
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)
def get_list(self): alist=[] self.bundle=self.auth_filter() for d in self.bundle: if self.request.args.get("client",None): alist.append(self.client_process(d,True)) else: d["@graph"]["resource"]=uri_pattern(d["@graph"]["pid"],config.APIHOST+"/"+self.endpoint) alist.append(d["@graph"]) return mongo_jsonify(alist)
def get_list(self): alist=[] self.bundle=self.auth_filter() for d in self.bundle: client = self.request.args.get("client",None) if client: alist.append(self.client_process(d,True)) else: d["@graph"]["resource"]=uri_pattern(d["@graph"]["pid"],config.APIHOST+"/"+self.endpoint) alist.append(d["@graph"]) return mongo_jsonify(alist)
def get_list(self): # Verify that a user is logged in. from auth import get_profile userid = get_profile()['userid'] if not userid: return action_401() query = {'userid': userid} results = self.collection.find(query) return mongo_jsonify(list(results))
def update_lastview(self, id, limit=0): '''Update the last view time if the 'view' url parameter is used.''' self.bundle = self.model.find_one({'$or': [{'_id': str(id)}, {'_id': ObjectId(id)}]}) if self.bundle: self.bundle = self.auth_filter(self.bundle) if not self.bundle: return action_401() self.bundle[u'@graph'][u'dc:lastviewed'] = datetime.utcnow() self.set_attrs() # Sometimes in the development testing database the ma:duration filed is missing. # This causes an error when the lastview field is updated. # This eats the error, which is probably not a best practice but makes the user # experience better. from mongokit.schema_document import RequireFieldError try: self.bundle.save() except RequireFieldError: return mongo_jsonify({"resp":200}) return mongo_jsonify({"resp":200}) else: return bundle_400('The ID you submitted is malformed.')
def get_list(self): if "concise" in self.request.args: self.bundle=self.auth_filter() return mongo_jsonify(map(lambda x: x['@graph'], self.bundle)) alist=[] self.bundle=self.auth_filter() thumbRetriever=[] for d in self.bundle: alist.append(self.model.make_part(d["@graph"],config.APIHOST,self.request.args.get("part","details"))) thumbRetriever.extend(alist[-1].get("fromYt")) alist[-1].pop("fromYt",None) ytThumbs=getYtThumbs(thumbRetriever) for vid in alist: for image in vid["ma:image"]: if image.get("ytId"): try: image["thumb"] = ytThumbs[image["ytId"]]["thumb"] image["poster"] = ytThumbs[image["ytId"]]["poster"] except Exception: image["thumb"] = None image["poster"] = None image.pop("ytId",None) return mongo_jsonify(alist)
def update_subtitle(self, filename, new_file): from helpers import endpoint_404 query = { "@graph.ma:hasRelatedResource":{"$elemMatch": {"@id":filename}} } bundle = self.model.find_one(query) if bundle is None: return endpoint_404() if not self.acl_write_check(bundle): return action_401() new_file.save(config.SUBTITLE_DIRECTORY + filename) return mongo_jsonify(bundle)
def delete_subtitle(self, filename): from os import remove from helpers import endpoint_404 query = { "@graph.ma:hasRelatedResource":{"$elemMatch": {"@id":filename}} } bundle = self.model.find_one(query) if bundle is None: return endpoint_404() if not self.acl_write_check(bundle): return action_401() l = bundle.get("@graph").get("ma:hasRelatedResource") l[:] = [d for d in l if d.get('@id') != filename] bundle.save() remove(config.SUBTITLE_DIRECTORY + filename) return mongo_jsonify(bundle)
def serialize_bundle(self,payload): return mongo_jsonify(payload["@graph"])
def languages(): from langs import langs return mongo_jsonify(langs)
def getCourseDepartments(): from programs import programs return mongo_jsonify(programs)