Example #1
0
def save_talk():
    raw_data = request.form
    resp, seminar, talk = can_edit_talk(raw_data.get("seminar_id", ""),
                                        raw_data.get("seminar_ctr", ""),
                                        raw_data.get("token", ""))
    if resp is not None:
        return resp

    data = {
        'seminar_id': talk.seminar_id,
        'token': talk.token,
        'display': talk.display,  # could be being edited by anonymous user
    }
    if talk.new:
        curmax = talks_max('seminar_ctr', {'seminar_id': talk.seminar_id})
        if curmax is None:
            curmax = 0
        data['seminar_ctr'] = curmax + 1
    else:
        data['seminar_ctr'] = talk.seminar_ctr
    for col in db.talks.search_cols:
        if col in data: continue
        try:
            val = raw_data.get(col)
            if not val:
                data[col] = None
            else:
                data[col] = process_user_input(val, db.talks.col_type[col])
            if col == 'speaker_homepage' and val and not val.startswith(
                    "http"):
                data[col] = "http://" + data[col]
            if col == "access" and val not in ["open", "users", "endorsed"]:
                raise ValueError("Invalid access type")
        except Exception as err:
            flash_error("Error processing %s: %s", [col, err])
            talk = WebTalk(talk.seminar_id, talk.seminar_ctr, data=raw_data)
            title = "Create talk" if talk.new else "Edit talk"
            return render_template("edit_talk.html",
                                   talk=talk,
                                   seminar=seminar,
                                   title=title,
                                   top_menu=basic_top_menu(),
                                   categories=categories(),
                                   institutions=institutions(),
                                   timezones=timezones)
    new_version = WebTalk(talk.seminar_id, data['seminar_ctr'], data=data)
    if new_version == talk:
        flash("No changes made to talk.")
    else:
        new_version.save()
        edittype = "created" if talk.new else "edited"
        flash("Talk successfully %s!" % edittype)
    return redirect(
        url_for("show_talk",
                semid=new_version.seminar_id,
                talkid=new_version.seminar_ctr), 301)
Example #2
0
def save_seminar_schedule():
    raw_data = request.form
    shortname = raw_data["shortname"]
    resp, seminar = can_edit_seminar(shortname, new=False)
    if resp is not None:
        return resp
    frequency = raw_data.get("frequency")
    try:
        frequency = int(frequency)
    except Exception:
        pass
    slots = int(raw_data["slots"])
    curmax = talks_max("seminar_ctr", {"seminar_id": shortname})
    if curmax is None:
        curmax = 0
    ctr = curmax + 1
    updated = 0
    warned = False
    errmsgs = []
    tz = seminar.tz
    to_save = []
    for i in list(range(slots)):
        seminar_ctr = raw_data.get("seminar_ctr%s" % i)
        speaker = process_user_input(raw_data.get("speaker%s" % i, ""),
                                     "speaker", "text", tz)
        if not speaker:
            if not warned and any(
                    raw_data.get("%s%s" % (col, i), "").strip()
                    for col in optional_cols):
                warned = True
                flash_warning("Talks are only saved if you specify a speaker")
            elif (not warned and seminar_ctr and not any(
                    raw_data.get("%s%s" % (col, i), "").strip()
                    for col in optional_cols)):
                warned = True
                flash_warning(
                    "To delete an existing talk, click Details and then click delete on the Edit talk page"
                )
            continue
        date = start_time = end_time = None
        dateval = raw_data.get("date%s" % i).strip()
        timeval = raw_data.get("time%s" % i).strip()
        if dateval and timeval:
            try:
                date = process_user_input(dateval, "date", "date", tz)
            except Exception as err:  # should only be ValueError's but let's be cautious
                errmsgs.append(format_input_errmsg(err, dateval, "date"))
            if date:
                try:
                    interval = process_user_input(timeval, "time", "daytimes",
                                                  tz)
                    start_time, end_time = date_and_daytimes_to_times(
                        date, interval, tz)
                except Exception as err:  # should only be ValueError's but let's be cautious
                    errmsgs.append(format_input_errmsg(err, timeval, "time"))
        if not date or not start_time or not end_time:
            errmsgs.append(
                format_errmsg(
                    "You must specify a date and time for the talk by %s",
                    speaker))

        # we need to flag date and time errors before we go any further
        if errmsgs:
            return show_input_errors(errmsgs)

        if daytimes_early(interval):
            flash_warning(
                "Talk for speaker %s includes early AM hours, please correct if this is not intended (use 24-hour time format).",
                speaker,
            )
        elif daytimes_long(interval) > 8 * 60:
            flash_warning(
                "Time s %s is longer than 8 hours, please correct if this is not intended.",
                speaker),

        if seminar_ctr:
            # existing talk
            seminar_ctr = int(seminar_ctr)
            talk = WebTalk(shortname, seminar_ctr, seminar=seminar)
        else:
            # new talk
            talk = WebTalk(shortname, seminar=seminar, editing=True)

        data = dict(talk.__dict__)
        data["speaker"] = speaker
        data["start_time"] = start_time
        data["end_time"] = end_time

        for col in optional_cols:
            typ = db.talks.col_type[col]
            try:
                val = raw_data.get("%s%s" % (col, i), "")
                data[
                    col] = None  # make sure col is present even if process_user_input fails
                data[col] = process_user_input(val, col, typ, tz)
            except Exception as err:
                errmsgs.append(format_input_errmsg(err, val, col))

        # Don't try to create new_version using invalid input
        if errmsgs:
            return show_input_errors(errmsgs)

        if seminar_ctr:
            new_version = WebTalk(talk.seminar_id, data=data)
            if new_version != talk:
                updated += 1
                to_save.append(
                    new_version)  # defer save in case of errors on other talks
        else:
            data["seminar_ctr"] = ctr
            ctr += 1
            new_version = WebTalk(talk.seminar_id, data=data)
            to_save.append(
                new_version)  # defer save in case of errors on other talks

    for newver in to_save:
        newver.save()

    if raw_data.get("detailctr"):
        return redirect(
            url_for(
                ".edit_talk",
                seminar_id=shortname,
                seminar_ctr=int(raw_data.get("detailctr")),
            ),
            302,
        )
    else:
        flash("%s talks updated, %s talks created" %
              (updated, ctr - curmax - 1))
        if warned:
            return redirect(url_for(".edit_seminar_schedule", **raw_data), 302)
        else:
            return redirect(
                url_for(
                    ".edit_seminar_schedule",
                    shortname=shortname,
                    begin=raw_data.get("begin"),
                    end=raw_data.get("end"),
                    frequency=raw_data.get("frequency"),
                    weekday=raw_data.get("weekday"),
                ),
                302,
            )
Example #3
0
def save_talk():
    raw_data = request.form
    token = raw_data.get("token", "")
    resp, talk = can_edit_talk(raw_data.get("seminar_id", ""),
                               raw_data.get("seminar_ctr", ""), token)
    if resp is not None:
        return resp
    errmsgs = []

    data = {
        "seminar_id": talk.seminar_id,
        "token": talk.token,
        "display": talk.display,  # could be being edited by anonymous user
    }
    if talk.new:
        curmax = talks_max("seminar_ctr", {"seminar_id": talk.seminar_id},
                           include_deleted=True)
        if curmax is None:
            curmax = 0
        data["seminar_ctr"] = curmax + 1
    else:
        data["seminar_ctr"] = talk.seminar_ctr
    default_tz = talk.seminar.timezone
    if not default_tz:
        default_tz = "UTC"
    data["timezone"] = tz = raw_data.get("timezone", default_tz)
    tz = pytz.timezone(tz)
    for col in db.talks.search_cols:
        if col in data:
            continue
        typ = db.talks.col_type[col]
        try:
            val = raw_data.get(col, "")
            data[
                col] = None  # make sure col is present even if process_user_input fails
            data[col] = process_user_input(val, col, typ, tz)
            if col == "access" and data[col] not in [
                    "open", "users", "endorsed"
            ]:
                errmsgs.append(
                    format_errmsg("Access type %s invalid", data[col]))
        except Exception as err:  # should only be ValueError's but let's be cautious
            errmsgs.append(format_input_errmsg(err, val, col))
    if not data["speaker"]:
        errmsgs.append(
            "Speaker name cannot be blank -- use TBA if speaker not chosen.")
    if data["start_time"] is None or data["end_time"] is None:
        errmsgs.append("Talks must have both a start and end time.")
    data["topics"] = clean_topics(data.get("topics"))
    data["language"] = clean_language(data.get("language"))
    data["subjects"] = clean_subjects(data.get("subjects"))
    if not data["subjects"]:
        errmsgs.append("Please select at least one subject")

    # Don't try to create new_version using invalid input
    if errmsgs:
        return show_input_errors(errmsgs)
    else:  # to make it obvious that these two statements should be together
        new_version = WebTalk(talk.seminar_id, data=data)

    # Warnings
    sanity_check_times(new_version.start_time, new_version.end_time)
    if "zoom" in data["video_link"] and not "rec" in data["video_link"]:
        flash_warning(
            "Recorded video link should not be used for Zoom meeting links; be sure to use Livestream link for meeting links."
        )
    if not data["topics"]:
        flash_warning(
            "This talk has no topics, and thus will only be visible to users when they disable their topics filter."
        )
    if new_version == talk:
        flash("No changes made to talk.")
    else:
        new_version.save()
        edittype = "created" if talk.new else "edited"
        flash("Talk successfully %s!" % edittype)
    edit_kwds = dict(seminar_id=new_version.seminar_id,
                     seminar_ctr=new_version.seminar_ctr)
    if token:
        edit_kwds["token"] = token
    else:
        edit_kwds.pop("token", None)
    return redirect(url_for(".edit_talk", **edit_kwds), 302)
Example #4
0
def import_talks(csv_file):
    talks = []
    ctr = {}
    with open(csv_file) as F:
        for i, line in enumerate(reader(F)):
            if i == 0:
                assert line == [
                    "Timestamp",
                    "Title",
                    "Speaker",
                    "Speaker_inst",
                    "Abstract",
                    "Host",
                    "Seminar",
                    "Site",
                    "In_Charge",
                    "arXiv",
                    "Date",
                    "Start_Time",
                    "End_Time",
                    "Timezone",
                    "Approved",
                ]
                continue
            (
                timestamp,
                title,
                speaker,
                speaker_affiliation,
                abstract,
                host,
                seminar_id,
                site,
                in_charge,
                arXiv,
                date,
                start_time,
                end_time,
                timezone,
                approved,
            ) = line
            # Make sure seminar exists
            seminar = seminars_lookup(seminar_id)
            if not seminar:
                continue
            if seminar is None:
                print("Warning: seminar %s does not exist" % seminar_id)
                continue
            if seminar_id not in ctr:
                m = talks_max("seminar_ctr", {"seminar_id": seminar_id})
                if m is None:
                    m = -1
                ctr[seminar_id] = m + 1
            # This time zone info is specific to importing in early April
            # There is some broken data, where time zones were incrementing the minute.  We reset them all to zero.
            tzdict = {
                -7: "America/Los_Angeles",
                -4: "America/New_York",
                -5: "America/Chicago",
                -3: "America/Buenos_Aires",
                2: "Europe/Paris",
                1: "Europe/London",
            }
            timezone = tzdict[int(timezone[4:7])]
            tz = pytz.timezone(timezone)
            date = parse(date, dayfirst=True).date()
            start_time = tz.localize(
                datetime.datetime.combine(date,
                                          parse(start_time).time()))
            end_time = tz.localize(
                datetime.datetime.combine(date,
                                          parse(end_time).time()))
            # Check to see if a talk at this time in the seminar already exists
            curtalk = talks_lucky({
                "seminar_id": seminar_id,
                "speaker": speaker
            })
            if curtalk is not None:
                print(
                    "Talk with speaker %s already exists in seminar %s; continuing"
                    % (speaker, seminar_id))
                continue
            curtalk = talks_lucky({
                "seminar_id": seminar_id,
                "start_time": start_time
            })
            if curtalk is not None:
                print(
                    "Talk at time %s (speaker %s) already exists in seminar %s; continuing"
                    % (start_time.strftime("%a %b %d %-H:%M"), speaker,
                       seminar_id))
                continue
            topics = (arXiv.replace(" ", "").replace("Math.", "").replace(
                "math.", "").lower().split(","))
            if not topics:
                topics = []
            talks.append(
                dict(
                    title=title,
                    speaker=speaker,
                    speaker_affiliation=speaker_affiliation,
                    abstract=abstract,
                    topics=topics,
                    timezone=timezone,
                    start_time=start_time,
                    end_time=end_time,
                    display=True,
                    token="%016x" % random.randrange(16**16),
                    online=True,
                    live_link=seminar.live_link,
                    room=seminar.room,
                    access=seminar.access,
                    comments=seminar.comments,
                    seminar_id=seminar_id,
                    seminar_ctr=ctr[seminar_id],
                ))
            ctr[seminar_id] += 1
    return talks
Example #5
0
def save_seminar_schedule():
    raw_data = request.form
    shortname = raw_data["shortname"]
    resp, seminar = can_edit_seminar(shortname, new=False)
    if resp is not None:
        return resp
    frequency = raw_data.get("frequency")
    try:
        frequency = int(frequency)
    except Exception:
        pass
    schedule_count = int(raw_data["schedule_count"])
    # FIXME not being used
    # update_times = bool(raw_data.get("update_times"))
    curmax = talks_max("seminar_ctr", {"seminar_id": shortname})
    if curmax is None:
        curmax = 0
    ctr = curmax + 1
    updated = 0
    warned = False
    for i in list(range(schedule_count)):
        seminar_ctr = raw_data.get("seminar_ctr%s" % i)
        speaker = process_user_input(raw_data.get("speaker%s" % i, ""),
                                     "text",
                                     tz=seminar.timezone)
        if not speaker:
            if not warned and any(
                    raw_data.get("%s%s" % (col, i), "").strip()
                    for col in optional_cols):
                warned = True
                flash_warning("Talks are only saved if you specify a speaker")
            continue
        date = raw_data.get("date%s" % i).strip()
        if date:
            try:
                date = process_user_input(date, "date", tz=seminar.tz)
            except ValueError as err:
                flash_error("invalid date %s: {0}".format(err), date)
                redirect(
                    url_for(".edit_seminar_schedule",
                            shortname=shortname,
                            **raw_data), 301)
        else:
            date = None
        time_input = raw_data.get("time%s" % i, "").strip()
        if time_input:
            try:
                time_split = time_input.split("-")
                if len(time_split) == 1:
                    raise ValueError("Must specify both start and end times")
                elif len(time_split) > 2:
                    raise ValueError("More than one hyphen")
                # TODO: clean this up
                start_time = process_user_input(time_split[0], "time",
                                                seminar.tz).time()
                end_time = process_user_input(time_split[1], "time",
                                              seminar.tz).time()
                if check_time(start_time, end_time):
                    raise ValueError
            except ValueError as err:
                if str(err):
                    flash_error("invalid time range %s: {0}".format(err),
                                time_input)
                return redirect(url_for(".edit_seminar_schedule", **raw_data),
                                301)
        else:
            start_time = end_time = None
        if any(X is None for X in [start_time, end_time, date]):
            flash_error("You must give a date, start and end time for %s" %
                        speaker)
            return redirect(url_for(".edit_seminar_schedule", **raw_data), 301)
        if seminar_ctr:
            # existing talk
            seminar_ctr = int(seminar_ctr)
            talk = WebTalk(shortname, seminar_ctr, seminar=seminar)
        else:
            # new talk
            talk = WebTalk(shortname, seminar=seminar, editing=True)
        data = dict(talk.__dict__)
        data["speaker"] = speaker
        for col in optional_cols:
            data[col] = process_user_input(raw_data.get("%s%s" % (col, i), ""),
                                           "text",
                                           tz=seminar.timezone)
        data["start_time"] = localize_time(
            datetime.datetime.combine(date, start_time), seminar.tz)
        data["end_time"] = localize_time(
            datetime.datetime.combine(date, end_time), seminar.tz)
        if seminar_ctr:
            new_version = WebTalk(talk.seminar_id,
                                  data["seminar_ctr"],
                                  data=data)
            if new_version != talk:
                updated += 1
                new_version.save()
        else:
            data["seminar_ctr"] = ctr
            ctr += 1
            new_version = WebTalk(talk.seminar_id, ctr, data=data)
            new_version.save()

    if raw_data.get("detailctr"):
        return redirect(
            url_for(
                ".edit_talk",
                seminar_id=shortname,
                seminar_ctr=int(raw_data.get("detailctr")),
            ),
            301,
        )
    else:
        if updated or ctr > curmax + 1:
            flash("%s talks updated, %s talks created" %
                  (updated, ctr - curmax - 1))
        if warned:
            return redirect(url_for(".edit_seminar_schedule", **raw_data), 301)
        else:
            return redirect(
                url_for(".edit_seminar_schedule",
                        shortname=shortname,
                        begin=raw_data.get('begin'),
                        end=raw_data.get('end'),
                        frequency=raw_data.get('frequency'),
                        weekday=raw_data.get('weekday')), 301)
Example #6
0
def save_talk():
    raw_data = request.form
    token = raw_data.get("token", "")
    resp, talk = can_edit_talk(raw_data.get("seminar_id", ""),
                               raw_data.get("seminar_ctr", ""), token)
    if resp is not None:
        return resp

    def make_error(talk, col=None, err=None):
        if err is not None:
            flash_error("Error processing %s: {0}".format(err), col)
        talk = WebTalk(talk.seminar_id, talk.seminar_ctr, data=raw_data)
        title = "Create talk error" if talk.new else "Edit talk error"
        return render_template(
            "edit_talk.html",
            talk=talk,
            seminar=talk.seminar,
            title=title,
            section="Manage",
            subsection="edittalk",
            institutions=institutions(),
            timezones=timezones,
        )

    data = {
        "seminar_id": talk.seminar_id,
        "token": talk.token,
        "display": talk.display,  # could be being edited by anonymous user
    }
    if talk.new:
        curmax = talks_max("seminar_ctr", {"seminar_id": talk.seminar_id})
        if curmax is None:
            curmax = 0
        data["seminar_ctr"] = curmax + 1
    else:
        data["seminar_ctr"] = talk.seminar_ctr
    default_tz = talk.seminar.timezone
    if not default_tz:
        default_tz = "UTC"
    data["timezone"] = tz = raw_data.get("timezone", default_tz)
    tz = pytz.timezone(tz)
    for col in db.talks.search_cols:
        if col in data:
            continue
        try:
            val = raw_data.get(col, "").strip()
            if not val:
                data[col] = None
            else:
                data[col] = process_user_input(val,
                                               db.talks.col_type[col],
                                               tz=tz)
            if col == "speaker_homepage" and val and not val.startswith(
                    "http"):
                data[col] = "http://" + data[col]
            if col == "access" and val not in ["open", "users", "endorsed"]:
                raise ValueError("Invalid access type")
        except Exception as err:
            return make_error(talk, col, err)
    data["topics"] = clean_topics(data.get("topics"))
    data["language"] = clean_language(data.get("language"))
    new_version = WebTalk(talk.seminar_id, data["seminar_ctr"], data=data)
    if check_time(new_version.start_time,
                  new_version.end_time,
                  check_past=True):
        return make_error(talk)
    if new_version == talk:
        flash("No changes made to talk.")
    else:
        new_version.save()
        edittype = "created" if talk.new else "edited"
        flash("Talk successfully %s!" % edittype)
    edit_kwds = dict(seminar_id=new_version.seminar_id,
                     seminar_ctr=new_version.seminar_ctr)
    if token:
        edit_kwds["token"] = token
    else:
        edit_kwds.pop("token", None)
    return redirect(url_for(".edit_talk", **edit_kwds), 301)
Example #7
0
def save_seminar_schedule():
    raw_data = request.form
    shortname = raw_data["shortname"]
    resp, seminar = can_edit_seminar(shortname, new=False)
    if resp is not None:
        return resp
    schedule_count = int(raw_data["schedule_count"])
    update_times = bool(raw_data.get("update_times"))
    curmax = talks_max('seminar_ctr', {'seminar_id': shortname})
    if curmax is None:
        curmax = 0
    ctr = curmax + 1
    try:
        start_time = datetime.time.fromisoformat(raw_data["start_time"])
        end_time = datetime.time.fromisoformat(raw_data["end_time"])
    except ValueError as err:
        flash_error("Invalid time: %s", err)
        return redirect(url_for(".edit_seminar_schedule", shortname=shortname),
                        301)
    for i in range(schedule_count):
        seminar_ctr = raw_data.get("seminar_ctr%s" % i)
        date = datetime.date.fromisoformat(raw_data["date%s" % i])
        if seminar_ctr:
            # existing talk
            seminar_ctr = int(seminar_ctr)
            talk = WebTalk(shortname, seminar_ctr, seminar=seminar)
            data = dict(talk.__dict__)
            for col in [
                    "speaker", "speaker_affiliation", "speaker_email", "title"
            ]:
                data[col] = process_user_input(raw_data["%s%s" % (col, i)],
                                               'text')
            if update_times:
                data["start_time"] = datetime.datetime.combine(
                    date, start_time)
                data["end_time"] = datetime.datetime.combine(date, end_time)
            new_version = WebTalk(talk.seminar_id,
                                  data['seminar_ctr'],
                                  data=data)
            if new_version != talk:
                print(data)
                new_version.save()
        elif raw_data["speaker%s" % i].strip():
            # new talk
            talk = WebTalk(shortname, seminar=seminar, editing=True)
            data = dict(talk.__dict__)
            for col in [
                    "speaker", "speaker_affiliation", "speaker_email", "title"
            ]:
                data[col] = process_user_input(raw_data["%s%s" % (col, i)],
                                               'text')
            data["start_time"] = datetime.datetime.combine(date, start_time)
            data["end_time"] = datetime.datetime.combine(date, end_time)
            data["seminar_ctr"] = ctr
            ctr += 1
            new_version = WebTalk(talk.seminar_id, ctr, data=data)
            print(data)
            new_version.save()

    return redirect(url_for(".edit_seminar_schedule", shortname=shortname),
                    301)