Ejemplo n.º 1
0
def create_calendar_entry(req, reqId, rangeId, startDate, hours, energy):
    result = ""

    if reqId:
        title = req.title
        beam = True
    else:
        title = 'Downtime'
        beam = False

    entry = Calendar(
        username = req.username,
        facility = req.facility,
        integrator = req.integrator,
        totalTime = hours,
        startDate = startDate,
        private = False,
        title = title,
        requestId = reqId,
        rangeId = rangeId,
        beam = beam,
        energy = float(energy)
    )
    
    result = entry.create_entry()

    return result
Ejemplo n.º 2
0
def delete_event(request, event_id):
    calendar = Calendar(request.user)
    try:
        calendar.delete_event(event_id)
        return redirect(reverse("event_creator.views.index"))
    except apiclient.errors.HttpError:
        return HttpResponse("Calendar event was not deleted", status=500)
Ejemplo n.º 3
0
def delete_calendar_meal(user_id, meal_id):
    check_user = do_user_check(user_id)
    if check_user:
        meal = Calendar.query.get_or_404(meal_id)
        Calendar.delete(meal)
        return redirect(f'/users/{user_id}/calendar')
    else:
        return redirect('/')
Ejemplo n.º 4
0
def update_calendar(calendar: Calendar, data: dict) -> Calendar:
    if data.get('season', None):
        calendar.season = data['season']
    if data.get('season_week', None):
        calendar.season_week = data['season_week']
    if data.get('weekday', None):
        calendar.weekday = data['weekday']
    db.session.commit()
    return calendar
 def createCalendar(user_id):
     try:
         user_id = ObjectId(user_id)
     except:
         return "fail"
     calendar = Calendar(user_id)#create the calendar
     cal = calendar.save()
     print "created calendar:", cal.id
     return dumps(cal)#return the calendar object
Ejemplo n.º 6
0
 def createCalendar(user_id):
     try:
         user_id = ObjectId(user_id)
     except:
         return "fail"
     calendar = Calendar(user_id)  #create the calendar
     cal = calendar.save()
     print "created calendar:", cal.id
     return dumps(cal)  #return the calendar object
Ejemplo n.º 7
0
def add_date(response, calendar, date, event):
    with orm.db_session:
        if Calendar.get(id=calendar):
            calendar = Calendar.get(id=calendar)
            logger.warning("201")
            date = Date(calendar=calendar, date=date, event=event)
            response.status = HTTP_201
        else:
            logger.warning("404")
            response.status = HTTP_404
        return {}
Ejemplo n.º 8
0
def optionnal_calendar(sender, **kwargs):
    event = kwargs.pop('instance')

    if not isinstance(event, Event):
        return True
    if not event.calendar:
        try:
            calendar = Calendar._default_manager.get(name='default')
        except Calendar.DoesNotExist:
            calendar = Calendar(name='default', slug='default')
            calendar.save()

        event.calendar = calendar
    return True
Ejemplo n.º 9
0
def create_default_calendar(current_user, name):
    try:
        get_calendar(current_user, name)
        raise RepeatCalendarException('Calendar already exists')
    except DoesNotExistError:
        pass

    # creating the actual calendar object
    calendar = Calendar(parent=current_user.key,
                        owner=current_user.key,
                        name=name)
    calendar.column_names = Calendar.default_columns
    calendar.put()
    insert_row(calendar, current_user, datetime.today().date())
    return calendar
Ejemplo n.º 10
0
def get_stop_trips(stop_id,minutes):
    minutes = int(minutes)
    hour = datetime.now().hour
    if hour < 3:
        hour = hour + 24

    hourd = 0
    minutes_over = 0
    if minutes > 60 - datetime.now().minute:
        minutes_over = minutes - (60 - datetime.now().minute)
        minutes = 60
        hourd = 1

    stop_times = StopTime.query.filter_by(stop_id=stop_id)
    if minutes_over > 0:
        stop_times = stop_times.filter(or_(and_(\
            StopTime.arrival_time_minute >= 0, \
            StopTime.arrival_time_minute <= minutes_over,
            StopTime.arrival_time_hour == hour+hourd),and_( \
            StopTime.arrival_time_minute > datetime.now().minute, \
            StopTime.arrival_time_minute <= 60,
            StopTime.arrival_time_hour == hour)))
    else:    
        stop_times = stop_times.filter(StopTime.arrival_time_hour == hour)\
            .filter(StopTime.arrival_time_minute > datetime.now().minute)\
            .filter(StopTime.arrival_time_minute <= minutes + datetime.now().minute)
        
    stop_times = stop_times.all()
    
    # prune list of trips not running today
    for i,stop_time in enumerate(stop_times):
        if (not Calendar.is_running(stop_time.trip.service_id)):
            stop_times.remove(stop_time)
    
    return jsonify([stop_time.to_dict() for stop_time in stop_times])
Ejemplo n.º 11
0
def add_own_meal(user_id):
    check_user = do_user_check(user_id)
    if check_user:
        form = UserMealCalendarForm()
        if form.validate_on_submit():
            meal_name = form.meal_name.data
            dateSelected = myconverter(form.date.data)
            dateInfo = Calendar(user_id=user_id,
                                meal_name=meal_name,
                                selected_date=dateSelected)
            Calendar.save(dateInfo)
            return redirect(f'/users/{user_id}/calendar')
        else:
            return render_template('meal_add.html', form=form)
    else:
        return redirect('/')
Ejemplo n.º 12
0
def add_calendar(beam_request):
    result = ""

    try:
        entry = Calendar(username=beam_request.username,
                         facility=beam_request.facility,
                         integrator=beam_request.integrator,
                         totalTime=beam_request.hours,
                         startDate=beam_request.start,
                         private=False,
                         title=beam_request.title)
        result = entry.create_entry()

    except Exception as e:
        result = {'error': str(e), 'success': False}

    return result
Ejemplo n.º 13
0
def create_new_calendar(user: User, data: dict) -> Calendar:
    new_calendar = Calendar(user=user,
                            date=datetime.strptime(data['date'], date_format),
                            season=data['season'],
                            season_week=data['season_week'],
                            weekday=data['weekday'])
    db.session.add(new_calendar)
    db.session.commit()
    return new_calendar
Ejemplo n.º 14
0
def add_event(request):
    if request.method == "GET":
        add_event_form = AddEventForm()
    elif request.method == "POST":
        add_event_form = AddEventForm(request.POST)
        if add_event_form.is_valid():
            calendar = Calendar(request.user)
            try:
                calendar.add_event(add_event_form.cleaned_data["summary"],
                                   add_event_form.cleaned_data["start"],
                                   add_event_form.cleaned_data["end"])
            except apiclient.errors.HttpError:
                return HttpResponse("Calendar event was not added", status=500)
            return redirect(reverse("event_creator.views.index"))
    return render(request,
                  "add_event.html",
                  {"add_event_form": add_event_form,
                   "action": request.get_full_path()})
Ejemplo n.º 15
0
def create_entry():

    req = request.get_json()
    result = ""

    try:
        entry = Calendar(username=req['username'],
                         facility=req['facility'],
                         integrator=req['integrator'],
                         totalTime=req['totalTime'],
                         startDate=req['startDate'],
                         private=req['private'],
                         title=req['title'])
        result = entry.create_entry()

    except Exception as e:
        result = {'error': str(e), 'success': False}

    return result
Ejemplo n.º 16
0
def optionnal_calendar(sender, **kwargs):
    event = kwargs.pop('instance')

    if not isinstance(event, Event):
        return True
    try:
        if not event.calendar:
            calendar = Calendar._default_manager.get(name='default')
    except Calendar.DoesNotExist:
        name = getattr(settings, "EVENT_DEFAULT_CALENDAR_NAME", None) or u"default"
        calendar = Calendar(
            name = name,
            slug = slugify(name),
            category = get_default_category()
        )
        calendar.save()
        event.calendar = calendar
        
    return True
Ejemplo n.º 17
0
def get_calendar(user, calendar_name):
    cal_query = Calendar.query(ancestor=user.key)\
                        .filter(ndb.AND(Calendar.owner==user.key,
                                        Calendar.name==calendar_name))
    calendars = cal_query.fetch()
    if len(calendars) == 0:
        raise DoesNotExistError('Calendar %s owned by %s does not exist',
                                calendar_name, user.username)
    if len(calendars) > 1:
        raise Exception('This should never happen')
    return calendars[0]
Ejemplo n.º 18
0
def create_calendar_request(request):
    if request.method == 'POST':
        params = request.POST
        if 'descstring' in params:
            c = Calendar.create_calendar(params['descstring'])
        
            return redirect('monthly_view', calendar_id=c.idstring)
        else:
            return HttpResponse("")
    else:
        return HttpResponse("")
Ejemplo n.º 19
0
def add_recipe(user_id, meal_id, meal_name):
    check_user = do_user_check(user_id)
    if check_user:
        form = UserMealCalenderDateForm()
        if form.validate_on_submit():
            new_meal = Calendar(user_id=user_id,
                                meal_id=meal_id,
                                meal_name=meal_name,
                                selected_date=form.date.data)
            Calendar.save(new_meal)
            flash("You successfully saved your meal to calendar", "success")
            return redirect(
                f'/users/{user_id}/meals/{meal_id}/view/{meal_name}')
        else:
            return render_template('create_meal_calendar.html',
                                   form=form,
                                   meal_id=meal_id,
                                   meal_name=meal_name)
    else:
        return redirect('/')
Ejemplo n.º 20
0
def reset_calendars():
    """
    This function, used only for testing purposes, resets the calendars list to
    its initial states.
    :return: a simple status
    """
    # Removing all calendars and dates:
    with orm.db_session:
        # Deleting all dates and calendars
        Date.select().delete(bulk=True)
        Calendar.select().delete(bulk=True)

        # Creating sample calendars and dates
        Calendar(id=0, title="Empty calendar")
        c2 = Calendar(id=1, title="Sport and activities")
        Date(id=0, calendar=c2, date="2018-01-01", event="Go fishing")
        Date(id=1, calendar=c2, date="2018-01-11", event="Go surfing")
        Date(id=2, calendar=c2, date="2018-02-12", event="Go skying")
        Date(id=3, calendar=c2, date="2018-03-09", event="Go swimming")

    return dict(status="done")
Ejemplo n.º 21
0
def add_calendar():
    calendar_info = request.get_json()
    print("CALENDAR INFO", calendar_info)
    new_calendar = Calendar(notes=calendar_info['notes'],
                            start_date=calendar_info['startDate'],
                            end_date=calendar_info['endDate'],
                            title=calendar_info['title'])
    db.session.add(new_calendar)
    db.session.commit()
    response = Calendar.query.all()
    response = list(map(lambda x: x.serialize(), response))

    return jsonify(response), 200
Ejemplo n.º 22
0
def create_entry():

    username = get_jwt_identity()
    req = request.get_json()
    result = ""

    # date = datetime.strptime(form['date'], '%Y-%m-%dT%H:%M:%S.%fZ')

    try:
        entry = Calendar(
            username=req['username'],  # username
            facility=req['facility'],
            integrator=req['integrator'],
            totalTime=req['totalTime'],
            startDate=req['startDate'],
            private=req['private'],
            title=req['title'])
        result = entry.create_entry()

    except Exception as e:
        result = {'error': str(e), 'success': False}

    return result
Ejemplo n.º 23
0
def handle_calendar_post(calendar_title):
    # Validate the user input
    if len(calendar_title) >= 256 or len(calendar_title) < 4:
        return {'success': False, 'error_msg': 'API returned error'}

    calendar_hash = sha1(calendar_title + \
        str(int(time.time())).encode('utf-8') + \
        'my_s3cr3t_s4lt'.encode('utf-8')).hexdigest()

    c = Calendar(hash=calendar_hash, title=calendar_title)
    db.session.add(c)
    db.session.commit()

    print(calendar_hash)
    return {'success': True, 'hash': calendar_hash}
Ejemplo n.º 24
0
    def update(self):
        #self.get_settings()

        #		str_link_status = u'link_state"<span style=" font-weight:600; color:#ff0000;">М\'яке посилання не встановлене</span>'
        #		link_state = self.link_check()
        #		if link_state:
        #			str_link_status = link_state
        #		self.ui.labelLinkStatus.setText(str_link_status)

        model = MoodleCourseModel(self.db)
        self.ui.treeViewCourse.setModel(model)

        cal = Calendar()
        self.ui.treeViewCourse.setItemDelegateForColumn(2, cal)
        self.ui.treeViewCourse.show()
Ejemplo n.º 25
0
def get_dates(response, calendar):
    with orm.db_session:
        # Deleting all dates and calendars
        calendar = Calendar.get(id=calendar)

        dates = {}
        try:
            calendar_dates = calendar.dates

        except AttributeError:
            # There are not dates for this calendar
            response.status = HTTP_404
            return {}

        for date in calendar_dates.order_by(Date.date):
            dates[str(date.date)] = date.event

        return dates
Ejemplo n.º 26
0
def get_upcoming_trips(stop_id):
    limit = 3 if request.args.get('limit') == None else request.args.get('limit')
    current_minute = datetime.now().minute
    current_hour = StopTime.to_system_hour(datetime.now().hour)

    active_service_ids = [calendar.service_id for calendar in Calendar.get_active()]

    stop_times = StopTime.query.join(StopTime.trip).filter(StopTime.stop_id == stop_id)\
        .filter(Trip.service_id.in_(active_service_ids))\
        .filter(\
        or_(\
            and_(\
                StopTime.arrival_time_minute > current_minute,\
                    StopTime.arrival_time_minute <= 60,\
                    StopTime.arrival_time_hour == current_hour\
                    ),\
            StopTime.arrival_time_hour > current_hour\
            )\
         ).order_by(StopTime.arrival_time.asc()).limit(limit)\
         .options(orm.contains_eager(StopTime.trip,Trip.stop_times)).all()

    return jsonify({"stopTimes": [stop_time.to_dict() for stop_time in stop_times]})
Ejemplo n.º 27
0
def append_data(year, month, calendar_id, username):
    c = Calendar.get_calendar(calendar_id)
    if (c == None):
        return None

    if username == None:
        user = None
    else:
        user = SoftUser.create_softuser(username)
    
    currDate = datetime.date.today()

    if year is None:
        year = currDate.year
    else:
        year = int(year)
        
    if month is None:
        month = currDate.month
    else:
        month = int(month)
        
    return (year, month, c, user)
Ejemplo n.º 28
0
 def createCalendar(user_id):
     user_id = ObjectId(user_id)
     calendar = Calendar(user_id)
     cal = calendar.save()
     return dumps(cal)
Ejemplo n.º 29
0
def put_calendar_for_user(email, calendar_name):
    user = get_user_from_email(email)
    calendar = Calendar(parent=user.key, name=calendar_name, owner=user.key)
    calendar.put()
    return calendar
Ejemplo n.º 30
0
def index(request):
    events = None
    if request.user.is_authenticated():
        calendar = Calendar(request.user)
        events = calendar.get_events()
    return render(request, "index.html", {"events": events})
Ejemplo n.º 31
0
def query_user_calendars(email):
    user = get_user_from_email(email)
    calendar_query = Calendar.query(ancestor=user.key)\
                             .order(Calendar.name)
    return calendar_query
Ejemplo n.º 32
0
def handle_calendar_create(info):
    calendar = Calendar(**info)
    db.session.add(calendar)
    db.session.commit()
    logger.info(f"Created calendar with key: {(info['id'], info['user_id'])}")