def wrapper(*a, **kw): request = get_current_request() try: return func(*a, **kw) except Exception as e: request.log_exc(level=logging.DEBUG) w = WeasylError('httpError') w.error_suffix = 'The original error was: %s' % (e,) raise w
def get_extension_for_category(filedata, category): try: _, fmt = file_type_for_category(filedata, _categories[category]) except UnknownFileFormat as uff: e = WeasylError('FileType') e.error_suffix = uff.args[0] raise e except InvalidFileFormat as iff: e = WeasylError('FileType') e.error_suffix = iff.args[0] raise e else: return '.' + fmt
def control_streaming_get_(request): form = request.web_input(target='') if form.target and request.userid not in staff.MODS: raise WeasylError('InsufficientPermissions') elif form.target: target = define.get_int(form.target) else: target = request.userid return Response( define.webpage( request.userid, "control/edit_streaming.html", [ # Profile profile.select_profile(target), form.target, ], title="Edit Streaming Settings"))
def select_profile(userid, viewer=None): query = d.engine.execute(""" SELECT pr.username, pr.full_name, pr.catchphrase, pr.created_at, pr.profile_text, pr.settings, pr.stream_url, pr.config, pr.stream_text, us.end_time FROM profile pr INNER JOIN login lo USING (userid) LEFT JOIN user_streams us USING (userid) WHERE userid = %(user)s """, user=userid).first() if not query: raise WeasylError('RecordMissing') _, is_banned, is_suspended = d.get_login_settings(userid) streaming_status = "stopped" if query[6]: # profile.stream_url if query[9] > d.get_time(): # user_streams.end_time streaming_status = "started" elif 'l' in query[5]: streaming_status = "later" return { "userid": userid, "user_media": media.get_user_media(userid), "username": query[0], "full_name": query[1], "catchphrase": query[2], "unixtime": query[3], "profile_text": query[4], "settings": query[5], "stream_url": query[6], "stream_text": query[8], "config": query[7], "show_favorites_bar": "u" not in query[7] and "v" not in query[7], "show_favorites_tab": userid == viewer or "v" not in query[7], "commish_slots": 0, "banned": is_banned, "suspended": is_suspended, "streaming_status": streaming_status, }
def _resize(filename, width, height, destination=None): in_place = False if not destination: destination = filename + '.new' in_place = True im = read(filename) if not images.image_extension(im): raise WeasylError("FileType") im = images.resize_image(im, width, height) if im is not None: im.write(destination) if in_place: os.rename(destination, filename) # if there's no need to resize, in-place resize is a no-op. otherwise copy # the source to the destination. elif not in_place: files.copy(filename, destination)
def reset(form): from weasyl import login # Raise an exception if `password` does not enter `passcheck` (indicating # that the user mistyped one of the fields) or if `password` does not meet # the system's password security requirements if form.password != form.passcheck: raise WeasylError("passwordMismatch") elif not login.password_secure(form.password): raise WeasylError("passwordInsecure") # Select the user information and record data from the forgotpassword table # pertaining to `token`, requiring that the link associated with the record # be visited no more than five minutes prior; if the forgotpassword record is # not found or does not meet this requirement, raise an exception query = d.engine.execute(""" SELECT lo.userid, lo.login_name, lo.email, fp.link_time, fp.address FROM login lo INNER JOIN userinfo ui USING (userid) INNER JOIN forgotpassword fp USING (userid) WHERE fp.token = %(token)s AND fp.link_time > %(cutoff)s """, token=form.token, cutoff=d.get_time() - 300).first() if not query: raise WeasylError("forgotpasswordRecordMissing") USERID, USERNAME, EMAIL, LINKTIME, ADDRESS = query # Check `username` and `email` against known correct values and raise an # exception if there is a mismatch if emailer.normalize_address( form.email) != emailer.normalize_address(EMAIL): raise WeasylError("emailIncorrect") elif d.get_sysname(form.username) != USERNAME: raise WeasylError("usernameIncorrect") elif d.get_address() != ADDRESS: raise WeasylError("addressInvalid") # Update the authbcrypt table with a new password hash d.engine.execute( 'INSERT INTO authbcrypt (userid, hashsum) VALUES (%(user)s, %(hash)s) ' 'ON CONFLICT (userid) DO UPDATE SET hashsum = %(hash)s', user=USERID, hash=login.passhash(form.password)) d.engine.execute("DELETE FROM forgotpassword WHERE token = %(token)s", token=form.token)
def clean_display_name(text): """ Process a user's selection of their own username into the username that will be stored. - Leading and trailing whitespace is removed. - Non-ASCII characters are removed. - Control characters are removed. - Semicolons are removed. - Only the first 25 characters are kept. Throws a WeasylError("usernameInvalid") if a well-formed username isn't produced by this process. """ cleaned = "".join(c for c in text.strip() if " " <= c <= "~" and c != ";")[:_USERNAME] sysname = d.get_sysname(cleaned) if sysname and sysname not in _BANNED_SYSNAMES: return cleaned else: raise WeasylError("usernameInvalid")
def shouts_(request): form = request.web_input(userid="", name="", backid=None, nextid=None) form.name = request.matchdict.get('name', form.name) form.userid = define.get_int(form.userid) otherid = profile.resolve(request.userid, form.userid, form.name) if not otherid: raise WeasylError("userRecordMissing") elif not request.userid and "h" in define.get_config(otherid): return Response( define.errorpage(request.userid, errorcode.no_guest_access)) userprofile = profile.select_profile(otherid, images=True, viewer=request.userid) has_fullname = userprofile[ 'full_name'] is not None and userprofile['full_name'].strip() != '' page_title = u"%s's shouts" % (userprofile['full_name'] if has_fullname else userprofile['username'], ) page = define.common_page_start(request.userid, title=page_title) page.append( define.render( 'user/shouts.html', [ # Profile information userprofile, # User information profile.select_userinfo(otherid, config=userprofile['config']), # Relationship profile.select_relation(request.userid, otherid), # Myself profile.select_myself(request.userid), # Comments shout.select(request.userid, ownerid=otherid), # Feature "shouts", ])) return Response(define.common_page_end(request.userid, page))
def staffnotes_(request): form = request.web_input(userid="") otherid = profile.resolve(request.userid, define.get_int(form.userid), request.matchdict.get('name', None)) if not otherid: raise WeasylError("userRecordMissing") userprofile = profile.select_profile(otherid, images=True, viewer=request.userid) has_fullname = userprofile[ 'full_name'] is not None and userprofile['full_name'].strip() != '' page_title = u"%s's staff notes" % (userprofile['full_name'] if has_fullname else userprofile['username'], ) page = define.common_page_start(request.userid, title=page_title) userinfo = profile.select_userinfo(otherid, config=userprofile['config']) reportstats = profile.select_report_stats(otherid) userinfo['reportstats'] = reportstats userinfo['reporttotal'] = sum(reportstats.values()) page.append( define.render( 'user/shouts.html', [ # Profile information userprofile, # User information userinfo, # Relationship profile.select_relation(request.userid, otherid), # Myself profile.select_myself(request.userid), # Comments shout.select(request.userid, ownerid=otherid, staffnotes=True), # Feature "staffnotes", ])) return Response(define.common_page_end(request.userid, page))
def edit_submission_get_(request): form = request.web_input(submitid="", anyway="") form.submitid = define.get_int(form.submitid) detail = submission.select_view(request.userid, form.submitid, ratings.EXPLICIT.code, False, anyway=form.anyway) if request.userid != detail['userid'] and request.userid not in staff.MODS: raise WeasylError('InsufficientPermissions') submission_category = detail['subtype'] // 1000 * 1000 return Response(define.webpage(request.userid, "edit/submission.html", [ # Submission detail detail, # Folders folder.select_flat(detail['userid']), # Subtypes [i for i in macro.MACRO_SUBCAT_LIST if submission_category <= i[0] < submission_category + 1000], profile.get_user_ratings(detail['userid']), ], title="Edit Submission"))
def POST(self): form = web.input(journalid="", title="", rating="", friends="", content="") rating = ratings.CODE_MAP.get(define.get_int(form.rating)) if not rating: raise WeasylError("ratingInvalid") j = orm.Journal() j.journalid = define.get_int(form.journalid) j.title = form.title j.rating = rating j.content = form.content journal.edit(self.user_id, j, friends_only=form.friends) raise web.seeother( "/journal/%i/%s%s" % (define.get_int(form.journalid), slug_for(form.title), ("?anyway=true" if self.user_id in staff.MODS else '')))
def edit_journal_post_(request): form = request.web_input(journalid="", title="", rating="", friends="", content="") rating = ratings.CODE_MAP.get(define.get_int(form.rating)) if not rating: raise WeasylError("ratingInvalid") j = orm.Journal() j.journalid = define.get_int(form.journalid) j.title = form.title j.rating = rating j.content = form.content journal.edit(request.userid, j, friends_only=form.friends) raise HTTPSeeOther( location="/journal/%i/%s%s" % (define.get_int(form.journalid), slug_for(form.title), ("?anyway=true" if request.userid in staff.MODS else '')))
def get_global_tag_restrictions(userid): """ Retrieves a list of tags on the globally restricted tag list for display to a director. Parameters: userid: The userid of the director requesting the list of tags. Returns: A dict mapping from globally restricted tag titles to the name of the director who added the tag. """ # Only directors can view the globally restricted tag list; sanity check against the @director_only decorator if userid not in staff.DIRECTORS: raise WeasylError("InsufficientPermissions") query = d.engine.execute(""" SELECT st.title, lo.login_name FROM globally_restricted_tags INNER JOIN searchtag AS st USING (tagid) INNER JOIN login AS lo USING (userid) """).fetchall() return {r.title: r.login_name for r in query}
def comment_insert(userid, commentid, otherid, submitid, charid, journalid): ownerid = d.get_ownerid(submitid, charid, journalid) if not otherid: otherid = ownerid if submitid: notiftype = 4020 if ownerid == otherid else 4050 elif charid: notiftype = 4040 elif journalid: notiftype = 4030 else: raise WeasylError("Unexpected") d.execute( "INSERT INTO welcome (userid, otherid, referid, targetid, unixtime, type) VALUES (%i, %i, %i, %i, %i, %i)", [ otherid, userid, d.get_targetid(submitid, charid, journalid), commentid, d.get_time(), notiftype ])
def reset(form): import login # Raise an exception if `password` does not enter `passcheck` (indicating # that the user mistyped one of the fields) or if `password` does not meet # the system's password security requirements if form.password != form.passcheck: raise WeasylError("passwordMismatch") elif not login.password_secure(form.password): raise WeasylError("passwordInsecure") # Select the user information and record data from the forgotpassword table # pertaining to `token`, requiring that the link associated with the record # be visited no more than five minutes prior; if the forgotpassword record is # not found or does not meet this requirement, raise an exception query = d.execute(""" SELECT lo.userid, lo.login_name, lo.email, fp.link_time, fp.address FROM login lo INNER JOIN userinfo ui USING (userid) INNER JOIN forgotpassword fp USING (userid) WHERE fp.token = '%s' AND fp.link_time > %i """, [form.token, d.get_time() - 300], options="single") if not query: raise WeasylError("forgotpasswordRecordMissing") USERID, USERNAME, EMAIL, LINKTIME, ADDRESS = query # Check `username` and `email` against known correct values and raise an # exception if there is a mismatch if emailer.normalize_address(form.email) != emailer.normalize_address(EMAIL): raise WeasylError("emailIncorrect") elif d.get_sysname(form.username) != USERNAME: raise WeasylError("usernameIncorrect") elif d.get_address() != ADDRESS: raise WeasylError("addressInvalid") # Update the authbcrypt table with a new password hash """ TODO TEMPORARY """ try: d.execute("INSERT INTO authbcrypt VALUES (%i, '')", [USERID]) except: pass d.execute("UPDATE authbcrypt SET hashsum = '%s' WHERE userid = %i", [login.passhash(form.password), USERID]) d.execute("DELETE FROM forgotpassword WHERE token = '%s'", [form.token])
def notes_(request): form = request.web_input(folder="inbox", filter="", backid="", nextid="") backid = int(form.backid) if form.backid else None nextid = int(form.nextid) if form.nextid else None filter_ = define.get_userid_list(form.filter) if form.folder == "inbox": return Response( define.webpage( request.userid, "note/message_list.html", [ # Folder "inbox", # Private messages note.select_inbox(request.userid, 50, backid=backid, nextid=nextid, filter=filter_), ])) if form.folder == "outbox": return Response( define.webpage( request.userid, "note/message_list.html", [ # Folder "outbox", # Private messages note.select_outbox(request.userid, 50, backid=backid, nextid=nextid, filter=filter_), ])) raise WeasylError("unknownMessageFolder")
def select_profile(userid, avatar=False, banner=False, propic=False, images=False, commish=True, viewer=None): query = d.execute(""" SELECT pr.username, pr.full_name, pr.catchphrase, pr.unixtime, pr.profile_text, pr.settings, pr.stream_url, pr.config, pr.stream_text, lo.settings, us.end_time FROM profile pr INNER JOIN login lo USING (userid) LEFT JOIN user_streams us USING (userid) WHERE userid = %i """, [userid], ["single"]) if not query: raise WeasylError('RecordMissing') streaming_status = "stopped" if query[6]: # profile.stream_url if query[10] > d.get_time(): # user_streams.end_time streaming_status = "started" elif 'l' in query[5]: streaming_status = "later" return { "userid": userid, "user_media": media.get_user_media(userid), "username": query[0], "full_name": query[1], "catchphrase": query[2], "unixtime": query[3], "profile_text": query[4], "settings": query[5], "stream_url": query[6], "stream_text": query[8], "config": query[7], "show_favorites_bar": "u" not in query[7] and "v" not in query[7], "show_favorites_tab": userid == viewer or "v" not in query[7], "commish_slots": 0, "banned": "b" in query[9], "suspended": "s" in query[9], "streaming_status": streaming_status, }
def create_price(userid, price, currency="", settings=""): if not price.title: raise WeasylError("titleInvalid") elif price.amount_min > _MAX_PRICE: raise WeasylError("minamountInvalid") elif price.amount_max > _MAX_PRICE: raise WeasylError("maxamountInvalid") elif price.amount_max and price.amount_max < price.amount_min: raise WeasylError("maxamountInvalid") elif not price.classid: raise WeasylError("classidInvalid") elif not d.engine.scalar( "SELECT EXISTS (SELECT 0 FROM commishclass WHERE (classid, userid) = (%(class_)s, %(user)s))", class_=price.classid, user=userid): raise WeasylError("classidInvalid") # Settings are at most one currency class, and optionally an 'a' to indicate an add-on price. # TODO: replace these character codes with an enum. settings = "%s%s" % ("".join( i for i in currency if i in CURRENCY_CHARMAP)[:1], "a" if "a" in settings else "") # TODO: should have an auto-increment ID priceid = d.engine.scalar( "SELECT MAX(priceid) + 1 FROM commishprice WHERE userid = %(user)s", user=userid) try: d.engine.execute( "INSERT INTO commishprice VALUES (%(newid)s, %(class_)s, %(user)s, %(title)s, %(amount_min)s, %(amount_max)s, %(settings)s)", newid=priceid if priceid else 1, class_=price.classid, user=userid, title=price.title, amount_min=price.amount_min, amount_max=price.amount_max, settings=settings, ) except PostgresError: return WeasylError("titleExists")
def following_(request): cachename = "user/following.html" form = request.web_input(userid="", name="", backid=None, nextid=None) form.name = request.matchdict.get('name', form.name) form.userid = define.get_int(form.userid) otherid = profile.resolve(request.userid, form.userid, form.name) if not otherid: raise WeasylError("userRecordMissing") elif not request.userid and "h" in define.get_config(otherid): return Response( define.errorpage(request.userid, errorcode.no_guest_access)) userprofile = profile.select_profile(otherid, images=True, viewer=request.userid) return Response( define.webpage( request.userid, cachename, [ # Profile information userprofile, # User information profile.select_userinfo(otherid, config=userprofile['config']), # Relationship profile.select_relation(request.userid, otherid), # Following followuser.select_following(request.userid, otherid, limit=44, backid=define.get_int(form.backid), nextid=define.get_int( form.nextid)), ]))
def characters_(request): form = request.web_input(userid="", name="", backid=None, nextid=None) form.name = request.matchdict.get('name', form.name) form.userid = define.get_int(form.userid) config = define.get_config(request.userid) rating = define.get_rating(request.userid) otherid = profile.resolve(request.userid, form.userid, form.name) if not otherid: raise WeasylError("userRecordMissing") elif not request.userid and "h" in define.get_config(otherid): return Response(define.errorpage(request.userid, errorcode.no_guest_access)) userprofile = profile.select_profile(otherid, images=True, viewer=request.userid) has_fullname = userprofile['full_name'] is not None and userprofile['full_name'].strip() != '' page_title = u"%s's characters" % (userprofile['full_name'] if has_fullname else userprofile['username'],) page = define.common_page_start(request.userid, title=page_title) url_format = "/characters?userid={userid}&%s".format(userid=userprofile['userid']) result = pagination.PaginatedResult( character.select_list, character.select_count, 'charid', url_format, request.userid, rating, 60, otherid=otherid, backid=define.get_int(form.backid), nextid=define.get_int(form.nextid), config=config) page.append(define.render('user/characters.html', [ # Profile information userprofile, # User information profile.select_userinfo(otherid, config=userprofile['config']), # Relationship profile.select_relation(request.userid, otherid), # Characters list result, ])) return Response(define.common_page_end(request.userid, page))
def edit_journal_get_(request): form = request.web_input(journalid="", anyway="") form.journalid = define.get_int(form.journalid) detail = journal.select_view(request.userid, ratings.EXPLICIT.code, form.journalid, False, anyway=form.anyway) if request.userid != detail['userid'] and request.userid not in staff.MODS: raise WeasylError('InsufficientPermissions') return Response( define.webpage( request.userid, "edit/journal.html", [ # Journal detail detail, profile.get_user_ratings(detail['userid']), ], title="Edit Journal"))
def GET(self): form = web.input(folder="inbox", filter="", backid="", nextid="") backid = int(form.backid) if form.backid else None nextid = int(form.nextid) if form.nextid else None filter_ = define.get_userid_list(form.filter) if form.folder == "inbox": return define.webpage(self.user_id, "note/message_list.html", [ # Folder "inbox", # Private messages note.select_inbox(self.user_id, 50, backid=backid, nextid=nextid, filter=filter_), ]) if form.folder == "outbox": return define.webpage(self.user_id, "note/message_list.html", [ # Folder "outbox", # Private messages note.select_outbox(self.user_id, 50, backid=backid, nextid=nextid, filter=filter_), ]) raise WeasylError("unknownMessageFolder")
def edit_submission_post_(request): form = request.web_input(submitid="", title="", folderid="", subtype="", rating="", content="", friends="", critique="", embedlink="") rating = ratings.CODE_MAP.get(define.get_int(form.rating)) if not rating: raise WeasylError("ratingInvalid") s = orm.Submission() s.submitid = define.get_int(form.submitid) s.title = form.title s.rating = rating s.content = form.content s.folderid = define.get_int(form.folderid) or None s.subtype = define.get_int(form.subtype) submission.edit(request.userid, s, embedlink=form.embedlink, friends_only=form.friends, critique=form.critique) raise HTTPSeeOther(location="/submission/%i/%s%s" % ( define.get_int(form.submitid), slug_for(form.title), "?anyway=true" if request.userid in staff.MODS else '' ))
def charactersbyuser(userid, form): if userid not in staff.MODS: raise WeasylError("Unexpected") query = d.execute( """ SELECT ch.charid, pr.username, ch.unixtime, ch.char_name, ch.age, ch.gender, ch.height, ch.weight, ch.species, ch.content, ch.rating, ch.settings, ch.page_views, pr.config FROM character ch INNER JOIN profile pr ON ch.userid = pr.userid INNER JOIN login ON ch.userid = login.userid WHERE login.login_name = '%s' """, [d.get_sysname(form.name)]) return [{ "contype": 20, "userid": userid, "charid": item[0], "username": item[1], "unixtime": item[2], "title": item[3], "rating": item[10], "settings": item[11], "sub_media": character.fake_media_items(item[0], userid, d.get_sysname(item[1]), item[11]), } for item in query]
def GET(self, login): userid = profile.resolve_by_login(login) if not userid: web.ctx.status = '404 Not Found' raise WeasylError('userRecordMissing') form = web.input(since=None, count=0, folderid=0, backid=0, nextid=0) since = None try: if form.since: since = d.parse_iso8601(form.since) count = int(form.count) folderid = int(form.folderid) backid = int(form.backid) nextid = int(form.nextid) except ValueError: web.ctx.status = '422 Unprocessable Entity' return json.dumps(_ERROR_UNEXPECTED) else: count = min(count or 100, 100) submissions = submission.select_list( self.user_id, d.get_rating(self.user_id), count + 1, otherid=userid, folderid=folderid, backid=backid, nextid=nextid) backid, nextid = d.paginate(submissions, backid, nextid, count, 'submitid') ret = [] for sub in submissions: if since is not None and since >= sub['unixtime']: break tidy_submission(sub) ret.append(sub) return json.dumps({ 'backid': backid, 'nextid': nextid, 'submissions': ret, })
def GET(self, name=""): cachename = "user/following.html" form = web.input(userid="", name="", backid=None, nextid=None) form.name = name if name else form.name form.userid = define.get_int(form.userid) otherid = profile.resolve(self.user_id, form.userid, form.name) if not otherid: raise WeasylError("userRecordMissing") elif not self.user_id and "h" in define.get_config(otherid): return define.errorpage(self.user_id, errorcode.no_guest_access) userprofile = profile.select_profile(otherid, images=True, viewer=self.user_id) return define.webpage( self.user_id, cachename, [ # Profile information userprofile, # User information profile.select_userinfo(otherid, config=userprofile['config']), # Relationship profile.select_relation(self.user_id, otherid), # Following followuser.select_following(self.user_id, otherid, limit=44, backid=define.get_int(form.backid), nextid=define.get_int( form.nextid)), ])
def submissionsbyuser(userid, form): if userid not in staff.MODS: raise WeasylError("Unexpected") query = d.execute(""" SELECT su.submitid, su.title, su.rating, su.unixtime, su.userid, pr.username, su.settings FROM submission su INNER JOIN profile pr USING (userid) WHERE su.userid = (SELECT userid FROM login WHERE login_name = '%s') ORDER BY su.submitid DESC """, [d.get_sysname(form.name)]) ret = [{ "contype": 10, "submitid": i[0], "title": i[1], "rating": i[2], "unixtime": i[3], "userid": i[4], "username": i[5], "settings": i[6], } for i in query] media.populate_with_submission_media(ret) return ret
def admincontrol_manageuser_post_(request): userid = d.get_int(request.params.get('userid', '')) if request.userid != userid and userid in staff.ADMINS and request.userid not in staff.TECHNICAL: raise WeasylError('InsufficientPermissions') profile.do_manage( request.userid, userid, username=request.params.get('username', '').strip() if 'ch_username' in request.params else None, full_name=request.params.get('full_name', '').strip() if 'ch_full_name' in request.params else None, catchphrase=request.params.get('catchphrase', '').strip() if 'ch_catchphrase' in request.params else None, birthday=request.params.get('birthday', '') if 'ch_birthday' in request.params else None, gender=request.params.get('gender', '') if 'ch_gender' in request.params else None, country=request.params.get('country', '') if 'ch_country' in request.params else None, remove_social=request.params.getall('remove_social'), permission_tag='permission-tag' in request.params) raise HTTPSeeOther(location="/admincontrol")
def control_editemailpassword_post_(request): form = request.web_input(newemail="", newemailcheck="", newpassword="", newpasscheck="", password="") newemail = emailer.normalize_address(form.newemail) newemailcheck = emailer.normalize_address(form.newemailcheck) # Check if the email was invalid; Both fields must be valid (not None), and have the form fields set if not newemail and not newemailcheck and form.newemail != "" and form.newemailcheck != "": raise WeasylError("emailInvalid") return_message = profile.edit_email_password( request.userid, form.username, form.password, newemail, newemailcheck, form.newpassword, form.newpasscheck ) if not return_message: # No changes were made message = "No changes were made to your account." else: # Changes were made, so inform the user of this message = "**Success!** " + return_message # Finally return the message about what (if anything) changed to the user return Response(define.errorpage( request.userid, message, [["Go Back", "/control"], ["Return Home", "/"]]) )
def modcontrol_contentbyuser_(request): form = request.web_input(name='', features=[]) # Does the target user exist? There's no sense in displaying a blank page if not. target_userid = profile.resolve(None, None, form.name) if not target_userid: raise WeasylError("userRecordMissing") submissions = moderation.submissionsbyuser( target_userid) if 's' in form.features else [] characters = moderation.charactersbyuser( target_userid) if 'c' in form.features else [] journals = moderation.journalsbyuser( target_userid) if 'j' in form.features else [] return Response( define.webpage(request.userid, "modcontrol/contentbyuser.html", [ form.name, sorted(submissions + characters + journals, key=lambda item: item['unixtime'], reverse=True), ], title=form.name + "'s Content"))
def favorite_insert(db, userid, submitid=None, charid=None, journalid=None, otherid=None): ownerid = d.get_ownerid(submitid, charid, journalid) if not otherid: otherid = ownerid if submitid: notiftype = 3020 if ownerid == otherid else 3050 elif charid: notiftype = 3100 elif journalid: notiftype = 3110 else: raise WeasylError("Unexpected") db.execute( "INSERT INTO welcome (userid, otherid, referid, targetid, unixtime, type) VALUES (%s, %s, %s, 0, %s, %s)", (otherid, userid, d.get_targetid(submitid, charid, journalid), d.get_time(), notiftype), )
def _select_journal_and_check(userid, journalid, rating=None, ignore=True, anyway=False, increment_views=True): """Selects a journal, after checking if the user is authorized, etc. Args: userid (int): Currently authenticating user ID. journalid (int): Character ID to fetch. rating (int): Maximum rating to display. Defaults to None. ignore (bool): Whether to respect ignored or blocked tags. Defaults to True. anyway (bool): Whether ignore checks and display anyway. Defaults to False. increment_views (bool): Whether to increment the number of views on the submission. Defaults to True. Returns: A journal and all needed data as a dict. """ query = d.engine.execute(""" SELECT jo.userid, pr.username, jo.unixtime, jo.title, jo.content, jo.rating, jo.settings, jo.page_views, pr.config FROM journal jo JOIN profile pr ON jo.userid = pr.userid WHERE jo.journalid = %(id)s """, id=journalid).first() if not query: # If there's no query result, there's no record, so fast-fail. raise WeasylError('journalRecordMissing') elif journalid and userid in staff.MODS and anyway: pass elif not query or 'h' in query.settings: raise WeasylError('journalRecordMissing') elif query.rating > rating and ((userid != query.userid and userid not in staff.MODS) or d.is_sfw_mode()): raise WeasylError('RatingExceeded') elif 'f' in query.settings and not frienduser.check(userid, query.userid): raise WeasylError('FriendsOnly') elif ignore and ignoreuser.check(userid, query.userid): raise WeasylError('UserIgnored') elif ignore and blocktag.check(userid, journalid=journalid): raise WeasylError('TagBlocked') query = dict(query) if increment_views and d.common_view_content(userid, journalid, 'journal'): query['page_views'] += 1 return query