def list_creations(self): web_user = WebUser.current_web_user(self.request) _creations = sorted( Creation.search_by_party(web_user.party.id), key=lambda creation: creation.artist.name ) return {'creations': _creations}
def current_artists_select_widget(node, kw): request = kw.get('request') web_user = WebUser.current_web_user(request) artists = Artist.search_by_party(web_user.party.id) artist_options = [(artist.id, artist.name) for artist in artists] widget = deform.widget.Select2Widget(values=artist_options) return widget
def list_artists(self): web_user = WebUser.current_web_user(self.request) _party_id = web_user.party.id return { 'solo_artists': Artist.search_solo_artists_by_party(_party_id), 'group_artists': Artist.search_group_artists_by_party(_party_id) }
def current_orphans(cls, request, category='all'): """ Searches orphan content in category of current web user. Args: request (pyramid.request.Request): Current request. category (str): optional - Category of content. Returns: list (content): List of content. None: If no match is found. """ party = WebUser.current_web_user(request).party return cls.search_orphans(party.id, category)
def ban(request): request.session['abuse_rank']['banned'] = True request.session['abuse_rank']['bantime'] = time.time() web_user = WebUser.current_web_user(request) if not web_user.abuse_rank: web_user.abuse_rank = 0 web_user.abuse_rank += 1 web_user.save() log.info( ( "banned upload for user %s (db abuse rank: %s)\n" ) % ( web_user, web_user.abuse_rank ) )
def current_rejects(cls, request, reason, category='all'): """ Searches rejected content (optionally in category) of current web user. Args: request (pyramid.request.Request): Current request. reason (str): Reason for rejected content. category (str): optional - Category of content. Returns: list (content): List of content. None: If no match is found. """ party = WebUser.current_web_user(request).party return cls.search_rejects(party.id, reason, category)
def controller(self): self.form = edit_profile_form(self.request) if self.submitted(): # submit validated data from form if self.validate(): self.change_profile() else: # initialize form web_user = WebUser.current_web_user(self.request) self.appstruct = { 'name': web_user.party.name or "", 'firstname': web_user.party.firstname or "", 'lastname': web_user.party.lastname or "", 'email': web_user['email'] or "" } self.render(self.appstruct) return self.response
def validate_unique_user_email(node, values, **kwargs): # multifield validator """Check for valid email and prevent duplicate usernames.""" request = node.bindings["request"] email_value = values["email"] current_web_user = WebUser.current_web_user(request) if email_value != current_web_user.email: # email has been changed: check if it conflicts with other webuser found_conflicting_web_user = WebUser.search_by_email(email_value) if found_conflicting_web_user: raise colander.Invalid(node, _(u"Email address already taken")) # finally, check email format if len(email_value) > 7: if re.match('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+' + # noqa: W605 '(\.[a-z0-9-]+)*(\.[a-z]{2,4})$', email_value) is not None: return raise colander.Invalid(node, "Invalid email address")
def validate_unique_user_email(node, values, **kwargs): # multifield validator """Check for valid email and prevent duplicate usernames.""" request = node.bindings["request"] email_value = values["email"] current_web_user = WebUser.current_web_user(request) if email_value != current_web_user.email: # email has been changed: check if it conflicts with other webuser found_conflicting_web_user = WebUser.search_by_email(email_value) if found_conflicting_web_user: raise colander.Invalid(node, _(u"Email address already taken")) # finally, check email format if len(email_value) > 7: if re.match( '^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+' + # noqa: W605 '(\.[a-z0-9-]+)*(\.[a-z]{2,4})$', email_value) is not None: return raise colander.Invalid(node, "Invalid email address")
def pocket_widget(request): heading = _(u'Pocket') web_user = WebUser.current_web_user(request) pocket_balance = web_user.party.pocket_balance pocket_budget = web_user.party.pocket_budget log.debug( ( "pocket_balance: %s\n" ) % ( pocket_balance ) ) body = render( '../../templates/widgets/pocket.pt', { 'pocket_balance': pocket_balance, 'pocket_budget': pocket_budget }, request=request ) return {'heading': heading, 'body': body}
def is_banned(request): if 'abuse_rank' not in request.session: request.session['abuse_rank'] = { 'current': 0, 'banned': False, 'bantime': None } banned = request.session['abuse_rank']['banned'] if not banned: return False currenttime = time.time() bantime = int(request.session['abuse_rank']['bantime']) removeban = int(request.registry.settings['abuse_rank.removeban']) if currenttime > bantime + removeban: request.session['abuse_rank']['banned'] = False request.session['abuse_rank']['current'] = 0 web_user = WebUser.current_web_user(request) log.debug( ( "removed upload ban for user %s (db abuse rank: %s)\n" ) % ( web_user, web_user.abuse_rank ) ) return request.session['abuse_rank']['banned']
def musician_list(self): web_user = WebUser.current_web_user(self.request) utilisations = CreationUtilisationIMP.search_by_musician( web_user.party.id ) return {'utilisations': utilisations}
def post_repertoire_upload(request): # create paths create_paths(request) # upload files files = [] for name, fieldStorage in request.POST.items(): # check fieldStorage if not isinstance(fieldStorage, FieldStorage): continue # configure upload rank = (request.registry.settings['abuse_rank.active'] == 'true') rank_max = int(request.registry.settings['abuse_rank.max']) hostname = get_hostname() descriptor = fieldStorage.file filename = os.path.basename(fieldStorage.filename).encode('utf-8') filename_hash = _hash_algorithm(filename).hexdigest() temporary_path = get_path(request, _path_temporary, filename_hash) contentrange = ContentRange.parse( request.headers.get('Content-Range', None) ) contentlength = request.headers.get('Content-Length', None) # create checksum with benchmark(request, name='checksum', uid=filename, normalize=descriptor, scale=100*1024*1024): checksum = create_checksum( descriptor=descriptor, algorithm=_checksum_algorithm ) save_checksum( path=temporary_path + _checksum_postfix, algorithm=_checksum_algorithm.__name__, checksum=checksum.hexdigest(), contentrange=contentrange or (0, contentlength, contentlength) ) # abuse rank if rank: if is_banned(request): # TODO: number wont be replaced, also see # BirthdateField line 300+ in register_webuser.py files.append({ 'name': fieldStorage.filename, 'error': _( u"Abuse detected. Wait for {number}" u" seconds before trying another" u" upload.", mapping={'number': int(still_banned_for(request))} )}) continue if is_collision(contentrange, checksum): raise_abuse_rank(request) current_rank = request.session['abuse_rank']['current'] if current_rank == rank_max: ban(request) # save to filesystem (-> temporary) ok, complete = save_upload_to_fs( descriptor=descriptor, absolute_path=temporary_path, contentrange=contentrange ) if not ok: pass if not complete: # client feedback files.append({ 'name': fieldStorage.filename, 'size': os.path.getsize(temporary_path) }) continue # get content uuid content_uuid = get_content_uuid() # get uuid paths uploaded_path = get_path(request, _path_uploaded, content_uuid) rejected_path = get_path(request, _path_rejected, content_uuid) file_category = get_category_from_mimetype(temporary_path) file_size = os.path.getsize(temporary_path) mime_type = str(mime.from_file(temporary_path)) # validate file error = validate_upload(filename, temporary_path) if error: # move files (temporary -> rejected) ok = move_files_with_prefixes( source=temporary_path, target=rejected_path ) if not ok: panic( request, reason="Files could not be moved.", identifiers=[filename_hash, content_uuid] ) # save file to database _content = { 'uuid': content_uuid, 'processing_hostname': hostname, 'processing_state': "rejected", 'rejection_reason': "format_error", 'entity_origin': "direct", 'entity_creator': WebUser.current_web_user(request).party, 'name': str(name), 'category': file_category, 'mime_type': mime_type, 'size': file_size, 'path': rejected_path } content = save_upload_to_db(_content) if not content: panic( request, reason="Content could not be created.", identifiers=[filename_hash, content_uuid] ) # save checksums to database # admin feedback # 2DO: Mail log.info( ( "Content rejected (format error): %s\n" ) % ( rejected_path ) ) # client feedback files.append({ 'name': fieldStorage.filename, 'error': error }) continue # we used to create a preview, now done in repertoire processing # this is only for displaying some file properties # audio = AudioSegment.from_file(temporary_path) file_category = get_category_from_mimetype(temporary_path) # move files (temporary -> uploaded) ok = move_files_with_prefixes( source=temporary_path, target=uploaded_path ) if not ok: panic( request, reason="Files could not be moved.", identifiers=[filename_hash, content_uuid] ) # save file to database _content = { 'uuid': content_uuid, 'processing_hostname': hostname, 'processing_state': "uploaded", 'entity_origin': "direct", 'entity_creator': WebUser.current_web_user(request).party, 'name': str(filename), 'category': file_category, 'mime_type': str(mime.from_file(uploaded_path)), 'size': os.path.getsize(uploaded_path), 'path': uploaded_path, # 'length': "%.6f" % audio.duration_seconds, # 'channels': int(audio.channels), # 'sample_rate': int(audio.frame_rate), # 'sample_width': int(audio.sample_width * 8) } content = save_upload_to_db(_content) if not content: panic( request, reason="Content could not be created.", identifiers=[filename_hash, content_uuid] ) # save checksums to database save_checksums_to_db( content=content, path=uploaded_path + _checksum_postfix ) # client feedback files.append(get_content_info(request, content)) # finally, see if there are old temporary files in the temp folder # structure cleanup_temp_directory(request) # TODO: add timestamp file in temp folder to track if cleanup run # was already started this day return {'files': files}
def list_clients(self): web_user = WebUser.current_web_user(self.request) return { 'player_names': Client.get_player_names_by_web_user(web_user.id), 'clients': Client.search_by_web_user(web_user.id) }