Exemple #1
0
def get_events(user, finalized_only=False):
  created_events = Event.objects(creator=user.id)
  invited_events = Event.objects(invitees=user.id)
  if finalized_only:
    finalized_events = []
    for event in created_events:
      if event.status == 'Finalized':
        finalized_events.append(event)
    for event in invited_events:
      if event.status == 'Finalized':
        finalized_events.append(event)
    return finalized_events

  results = {
    'created_events': [x.to_json() for x in created_events],
    'invited_events': [x.to_json() for x in invited_events],
  }
  for event in results['invited_events']:
    response = Response.objects(event=Event.objects().get(id=event['id']), responder=user.id)
    if response is not None and len(response) > 0:
      if response[0].response:
        event['res'] = 'Yes'
      else:
        event['res'] = 'No'
    else:
      event['res'] = 'notfound'
  return results
Exemple #2
0
def free_repeat(request):
    # get information
    user = request.user
    event_start = strToDateTime(request.POST['start']) # last date to free (starting from head)
    event_end = strToDateTime(request.POST['end'])
    id = request.POST['sid']
    title = request.POST['title']
    allDay = True if (request.POST['allDay'] == 'true') else False

    # calculate the event length if an end exists
    if event_end:
        event_length = event_end - event_start

    # get the RepeatEvent object
    repeat = user.repeatevent_set.all().get(pk = id)
    head = repeat.start

    # format the breaks array
    breaks = []
    for _break in repeat.breaks.all():
        breaks.append(_break.date)

    # delete the RepeatEvent object
    repeat.delete()

    # TODO! get rrule from repeat object

    # loop from head to event_start, making new Event objects
    cursor = head
    ids = ''
    while cursor < event_start:
        # check if current date is a break
        if cursor in breaks:
            continue

        # make new event and save
        event = Event(
            user=user,
            title=title,
            start=cursor,
            end=cursor,
            allDay=allDay
        )
        # add length of event if it exists
        if event_end:
            event.end += event_length
        event.save()

        # add id to ids csv string
        ids += str(event.id) + ','

        # move cursor
        cursor = oneForward(cursor, 'rrule')

    # remove last comma
    ids = ids[:-1]

    return HttpResponse(ids)
Exemple #3
0
def all_events():
  u = current_user
  created_events = Event.objects(creator=u.id)
  invited_events = Event.objects(invitees=u.id)
  results = {
    'created_events': [x.to_json() for x in created_events],
    'invited_events': [x.to_json() for x in invited_events],
  }
  return results
Exemple #4
0
def share_event(request):

    if request.method == 'POST':
        # unload the sent data
        to_user = request.POST["user"]
        title = request.POST["title"]
        start = strToDateTime(request.POST["start"])
        end = strToDateTime(request.POST["end"])
        allDay = True if (request.POST["allDay"] == "true") else False
        type = request.POST["type"]
        rrule = request.POST["rrule"]
        endRepeat = strToDateTime(request.POST["endRepeat"])

        # convert 'null' to None where needed

        # get the actual user
        user = User.objects.filter(username = to_user)[0]

        # handle if non-repeating event
        if type == "event":
            shared_event = Event(
                user = user,
                title = title,
                start = start,
                end = end,
                allDay = allDay
            )

        # handle if repeating event
        else:
            shared_event = RepeatEvent(
                user = user,
                title = title,
                start = start,
                end = end,
                allDay = allDay,
                rrule =  rrule,
                endRepeat = endRepeat
            )

        # save the shared event
        shared_event.save()

        # leave a message for whoever we shared with
        slash_date = str(start.month) + "/" + str(start.day) + "/" + str(start.year)[2] + str(start.year)[3]
        repeat_message = "an" if (type == "event") else "a repeating"
        start_message = "" if (type == "event") else "starting "
        message = request.user.username + " added " + repeat_message + " event to your calendar " + start_message + "on " + slash_date
        note = Note(
            user = user,
            message = message
        )
        note.save()

        return HttpResponse ("event shared")
    else:
        return HttpResponseRedirect('/')
Exemple #5
0
def current_events():
  user = current_user
  created_events = Event.objects(creator=user.id)
  invited_events = Event.objects(invitees=user.id)

  results = {
    'created_events': [x.to_json() for x in created_events],
    'invited_events': [x.to_json() for x in invited_events],
  }
  return jsonify(results)
Exemple #6
0
def events(user_id):
  finalized_only = False
  user = User.objects.get(id=user_id)
  created_events = Event.objects(creator=user.id)
  invited_events = Event.objects(invitees=user.id)

  results = {
    'created_events': [x.to_json() for x in created_events],
    'invited_events': [x.to_json() for x in invited_events],
  }
  return jsonify(results)
Exemple #7
0
def add_fakedata():
  user1 = User(username='******',name='Frost Li TEST')
  user1.save()
  user2 = User(username='******', name='Hello world')
  user2.save()
  event = Event(name='Why not dinner?',from_time_range=datetime.datetime.now(),
    to_time_range=datetime.datetime.now() + datetime.timedelta(hours=2),
    location='birate',duration_minutes=120,creator=user2.id,threshold=1)
  event.invitees.append(user2)
  event.save()
  return 'done'
Exemple #8
0
def delete_repeat(request):
    if request.method == 'POST':
        # get event id and user
        user = request.user
        id = request.POST['sid']
        date = strToDateTime(request.POST['start'])

        # get type to deal with case of free repeat on second to last
        type = request.POST['type']

        # container for httpresponse
        idreturn = ''

        # get RepeatEvent object
        repeat = user.repeatevent_set.get(pk = id)

        # check whether date is at the head
        # special case of type change on the second from the head of repeat event (type is event)
        if date == repeat.start or type == 'event':
            # delete RepeatEvent
            repeat.delete()

        # check if you are one past the head
        elif oneBack(date, repeat) == repeat.start:
            # make the head into a new Event object
            event = Event(
                user = user,
                title=repeat.title,
                start=repeat.start,
                end=repeat.end,
                allDay=repeat.allDay
            )
            event.save()

            # save id to return
            idreturn = str(event.id)

            # delete RepeatEvent
            repeat.delete()
        # not head and not one past head
        else:
            # set end date to one instance back of the passed in date
            end = oneBack(date, repeat)
            # update repeat and save
            repeat.endRepeat = end
            repeat.save()

        # return id or ''
        return HttpResponse(idreturn)
    else:
        return HttpResponseRedirect('/')
Exemple #9
0
def share_event(request):

    if request.method == 'POST':
        # unload the sent data
        to_user = request.POST["user"]
        title = request.POST["title"]
        start = strToDateTime(request.POST["start"])
        end = strToDateTime(request.POST["end"])
        allDay = True if (request.POST["allDay"] == "true") else False
        type = request.POST["type"]
        rrule = request.POST["rrule"]
        endRepeat = strToDateTime(request.POST["endRepeat"])

        # convert 'null' to None where needed

        # get the actual user
        user = User.objects.filter(username=to_user)[0]

        # handle if non-repeating event
        if type == "event":
            shared_event = Event(user=user,
                                 title=title,
                                 start=start,
                                 end=end,
                                 allDay=allDay)

        # handle if repeating event
        else:
            shared_event = RepeatEvent(user=user,
                                       title=title,
                                       start=start,
                                       end=end,
                                       allDay=allDay,
                                       rrule=rrule,
                                       endRepeat=endRepeat)

        # save the shared event
        shared_event.save()

        # leave a message for whoever we shared with
        slash_date = str(start.month) + "/" + str(start.day) + "/" + str(
            start.year)[2] + str(start.year)[3]
        repeat_message = "an" if (type == "event") else "a repeating"
        start_message = "" if (type == "event") else "starting "
        message = request.user.username + " added " + repeat_message + " event to your calendar " + start_message + "on " + slash_date
        note = Note(user=user, message=message)
        note.save()

        return HttpResponse("event shared")
    else:
        return HttpResponseRedirect('/')
Exemple #10
0
def delete_repeat(request):
    if request.method == 'POST':
        # get event id and user
        user = request.user
        id = request.POST['sid']
        date = strToDateTime(request.POST['start'])

        # get type to deal with case of free repeat on second to last
        type = request.POST['type']

        # container for httpresponse
        idreturn = ''

        # get RepeatEvent object
        repeat = user.repeatevent_set.get(pk=id)

        # check whether date is at the head
        # special case of type change on the second from the head of repeat event (type is event)
        if date == repeat.start or type == 'event':
            # delete RepeatEvent
            repeat.delete()

        # check if you are one past the head
        elif oneBack(date, repeat) == repeat.start:
            # make the head into a new Event object
            event = Event(user=user,
                          title=repeat.title,
                          start=repeat.start,
                          end=repeat.end,
                          allDay=repeat.allDay)
            event.save()

            # save id to return
            idreturn = str(event.id)

            # delete RepeatEvent
            repeat.delete()
        # not head and not one past head
        else:
            # set end date to one instance back of the passed in date
            end = oneBack(date, repeat)
            # update repeat and save
            repeat.endRepeat = end
            repeat.save()

        # return id or ''
        return HttpResponse(idreturn)
    else:
        return HttpResponseRedirect('/')
Exemple #11
0
def add_event(request):
    # get new event data
    user = request.user
    title = request.POST['title']
    start = strToDateTime(request.POST['start'])
    end = strToDateTime(request.POST['end'])
    allDay = True if (request.POST['allDay'] == 'true') else False

    # make new event and save
    event = Event(
        user = user,
        title=title,
        start=start,
        end=end,
        allDay=allDay
    )
    event.save()

    # return the id of the new event
    return HttpResponse(str(event.id))
Exemple #12
0
def delete_repeat(request):
    # get event id and user
    user = request.user
    id = request.POST['sid']
    date = strToDateTime(request.POST['start'])

    # container for httpresponse
    idreturn = ''

    # get RepeatEvent object
    repeat = user.repeatevent_set.get(pk = id)

    # check whether date is at the head
    if date == repeat.start:
        # delete RepeatEvent
        repeat.delete()
    # check if you are one past the head
    elif oneBack(date, 'rrule') == repeat.start:
        # make the head into a new Event object
        event = Event(
            user = user,
            title=repeat.title,
            start=repeat.start,
            end=repeat.end,
            allDay=repeat.allDay
        )
        event.save()
        idreturn = str(event.id)

        # delete RepeatEvent
        repeat.delete()
    # otherwise
    else:
        # set end date to one instance back of the passed in date
        end = oneBack(date, 'ruleHere')
        # update repeat and save
        repeat.endRepeat = end
        repeat.save()

    # return id of new event that was made at the head
    return HttpResponse(idreturn)
Exemple #13
0
def add_event(request):
    if request.method == 'POST':
        # get new event data
        user = request.user
        title = request.POST['title']
        start = strToDateTime(request.POST['start'])
        end = strToDateTime(request.POST['end'])
        allDay = True if (request.POST['allDay'] == 'true') else False

        # make new event and save
        event = Event(user=user,
                      title=title,
                      start=start,
                      end=end,
                      allDay=allDay)
        event.save()

        # return the id of the new event
        return HttpResponse(str(event.id))
    else:
        return HttpResponseRedirect('/')
Exemple #14
0
def activate(request, uidb64, token):
    user = None
    try:
        uid = force_text(urlsafe_base64_decode(uidb64))
        user = User.objects.get(pk=uid)
    except (TypeError, ValueError, OverflowError, User.DoesNotExist):
        messages.error(request, "That activation link did not work")
        return HttpResponseRedirect(reverse_lazy('login'))

    if user is not None and account_activation_token.check_token(user, token):
        user.is_active = True
        user.save()
        login(request, user)
        try:
            user_cal = Calendar.objects.get(user=user)
        except Calendar.DoesNotExist:
            user_cal = Calendar(user=user)
            user_cal.save()

            #all of this down to the return statement creates a yearly repeating account anniversary event
            today = datetime.now().replace(hour=0,
                                           minute=0,
                                           second=0,
                                           microsecond=0)
            pattern = rrule(freq=YEARLY, dtstart=today)

            description = "On this day in " + str(
                today.year) + ", your account was created!"
            aa_event = Event(rrule=pattern,
                             all_day=True,
                             start_time=today,
                             end_time=today + timedelta(days=1),
                             event_type='AA',
                             title="Account Anniversary",
                             description=description)
            aa_event.calendar = user_cal
            aa_event.save()

    messages.success(request, "Successfully verified your account!")
    return HttpResponseRedirect(reverse_lazy('home:main'))
Exemple #15
0
def addEvent(request, pk=None, pk1=None):
    print("sono dentro add event")
    instance = Event()
    instance = Event(calendar_id=pk1)

    form = EventForm(request.POST or None, instance=instance)
    if request.POST and form.is_valid():
        form.save()
        print("Form valido")

        #Controllo se evento appena aggiunto si svolgerà prima di un dato tempo ed in caso richiamo il publisher
        e = Event.objects.filter(calendar=pk1).latest('id')
        now = datetime.now().time()

        #Trasformo orari in int per poter sottrarre
        now = int(now.strftime('%H%M%S'))
        temp = int(e.start_time.strftime('%H%M%S'))

        #Se l'evento avviene fra meno di un ora chiamo la publish
        #if((temp-now) < 6000):
        publish(pk, pk1, client1)

        return HttpResponseRedirect(reverse('cal:list_event', args=[pk, pk1]))
    return render(request, 'cal/form.html', {'form': form, 'name': "Eventi"})
Exemple #16
0
def check_events(doctor, year, month, day):
    events = list(
        Event.objects.filter(doctor=doctor,
                             date__year=year,
                             date__month=month,
                             date__day=day))
    for p in Profile.objects.filter(dob__month=month,
                                    dob__day=day,
                                    doctor=doctor):
        e = Event()
        e.doctor = p.doctor
        e.start_time = dtime(0, 0)
        e.end_time = dtime(0, 0)
        e.description = _(u'Cumpleaños de') + ' ' + p.get_full_name()
        events.insert(0, e)
    return events
Exemple #17
0
def add_event():
  data = request.values
  invitees = []
  for i in data.getlist('invitees') or data.getlist('invitees[]'):
    invitees += [x.strip() for x in i.split(',')]

  invitees = list(set(invitees))
  print str(data)
  days = data.get('days','mtw')

  from_time_range = parser.parse(data['from_time_range'])
  to_time_range = parser.parse(data['to_time_range'])
  if current_user.is_authenticated():
    creator = current_user
  else:
    creator = User.objects.get(id=data['cookie'])
  event = Event(name=data['name'],from_time_range=from_time_range,
    to_time_range=to_time_range,location=data['location'],duration_minutes=data['duration'],
    creator=creator.id,threshold=data['threshold'], days=''.join(days))
  for invitee_name in invitees:
    if not invitee_name.strip():
      continue
    u = User.objects.get(name__icontains=invitee_name.strip())
    event.invitees.append(u)
  
  #event.suggested_from_time = event.from_time_range
  event.suggested_from_time = datetime.datetime(month=2, day=20, year=2014, hour=11)
  #evernote stuff
  store = EvernoteClient(token='S=s1:U=8df7b:E=14b91fcbdb9:C=1443a4b91bb:P=1cd:A=en-devtoken:V=2:H=58cee1b9b995670db8f66230ec99b5e1').get_note_store()
  note = Note()
  note.title = 'Event ' + str(request.values.get('name'))
  note.content = '<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">'
  content = 'Selected date: ' + event.suggested_from_time.strftime('%A %B %d at %I:%M %p') + '<br/>'
  for i in invitees:
    content += i +  ' - Waiting for response' + '<br />'
  note.content += '<en-note>%s</en-note>' % content
  createdNote = store.createNote(note)
  event.note_guid = createdNote.guid
  print 'note guid is ' + createdNote.guid
  event.save()
  event.send_invites()
  return 'OK'
Exemple #18
0
def todoPage(request, pk):
    project = Project.objects.get(id=pk)
    members = project.project_members.all()
    todo = Todo.objects.filter(project=project).order_by('rank')
    if len(todo) > 0:
        last_rank = todo.last().rank
    else:
        last_rank = 0

    if request.method == "POST":
        todoform = TodoForm(pk, request.POST)
        added_by = members.get(user=request.user)
        new_todo_title = todoform.data['title']
        new_todo_desc = todoform.data['description']

        deadline = todoform.data['deadline']
        end_date = datetime.strptime(deadline, '%Y-%m-%dT%H:%M')
        deadline_month = end_date.strftime("%m")
        deadline_year = end_date.strftime("%Y")

        assigned_to = members.get(pk=todoform.data['assigned_to'])
        new_todo = Todo(title=new_todo_title,
                        description=new_todo_desc,
                        last_modified_by=added_by,
                        project=project,
                        rank=last_rank + 1,
                        last_modified=datetime.now(),
                        deadline=deadline,
                        deadline_month=deadline_month,
                        deadline_year=deadline_year,
                        assigned_to=assigned_to)
        new_todo.save()

        new_event = Event(project=project,
                          todo=new_todo,
                          title=new_todo_title,
                          description=new_todo_desc,
                          start_time=None,
                          start_month=0,
                          start_year=0,
                          end_time=deadline,
                          end_month=end_date.strftime("%m"),
                          end_year=end_date.strftime("%Y"),
                          label='Todo')
        new_event.save()
        project.todo_set.add(new_todo)

        modified_by = members.get(user=request.user)
        project.cal_last_modified = datetime.now()
        project.cal_last_modified_by = modified_by
        project.last_modified = datetime.now()
        project.last_modified_by = modified_by
        project.last_modified_item = "Todo"
        project.save()

        return redirect('/project/' + str(pk) + '/todo')
    else:
        todoform = TodoForm(pk)

    context = {
        'project': project,
        'members': members,
        'todoform': todoform,
        'todo': todo,
        'rank_options': rank_options,
        'month_options': month_options,
        'Year': datetime.now().strftime("%Y")
    }
    return render(request, 'todo/todo_page.html', context)
Exemple #19
0
    def handle(self):
        bs = BeautifulSoup(self.content)
        if 'container' in self.kwargs:
            # TODO
            bs = bs.find("div", self.kwargs['container']).find("div", "view-content")

        ele = bs.find('h3')
        tmp_day = ele.text.split(',')[-1].strip()
        tmp_day += str(datetime.today().year)

        while ele.nextSibling:
            ele = ele.nextSibling
            if type(ele) == NavigableString:
                continue
            elif ele.name == 'h3':
                tmp_day = ele.text.split(',')[-1].strip()
                tmp_day += str(datetime.today().year)
            elif ele.name == 'div':
                # Get all div's with a certain class.
                bs_event = ele

                bs_title = bs_event.find(attrs={'class':self.kwargs['cluster_title']}).find('a')
                cluster_title = bs_title.string

                tmp_description = bs_event.find('p')
                if tmp_description:
                    cluster_description = strip_tags(unicode(bs_event.find('p')), ['a'])
                else:
                    cluster_description = ""
                if 'url' in self.kwargs:
                    cluster_url = "http://path.princeton.edu" + bs_title['href']
                    cluster_description += ("<p>Note: This event was automatically added from"
                        " <a href='http://path.princeton.edu'>Path to Princeton</a>, and may not"
                        " be fully accurate.  Click <a href='%s'>here</a> for the original event.</p>"
                        % (cluster_url,))

                # TODO
                tmp_starttime = bs_event.find(attrs={'class':"date-display-start"})
                if tmp_starttime:
                    tmp_starttime = tmp_starttime.text
                    event_date_time_start = parse_time(tmp_day, tmp_starttime)
                    tmp_endtime = bs_event.find(attrs={'class':"date-display-end"}
                        ).text
                    event_date_time_end = parse_time(tmp_day, tmp_endtime)
                else:
                    tmp_starttime = bs_event.find(attrs={'class':"date-display-single"}
                        ).text
                    event_date_time_start = parse_time(tmp_day, tmp_starttime)
                    event_date_time_end = event_date_time_start + timedelta(hours=1)

                # TODO
                tmp_location = bs_event.find(attrs={'class':self.kwargs['event_location']})
                if tmp_location:
                    event_location_objs = tmp_location.find(attrs={'class':'field-content'}).findAll('li')
                    if len(event_location_objs) == 1:
                        event_location_str = event_location_objs[0].text
                        success = False
                        if event_location_str in self.locations:
                            event_location = self.locations[event_location_str]
                            if event_location_str in self.alt_locations:
                                event_location_details = event_location_str
                            else:
                                event_location_details = ""
                        else:
                            # Try various methods..
                            for c in [", ", " - "]:
                                if c in event_location_str:
                                    parts = event_location_str.split(c)
                                    for i, els in enumerate(parts):
                                        if els in self.locations:
                                            event_location = self.locations[els]
                                            parts.pop(i)
                                            event_location_details = c.join(parts)
                                            success = True
                                if success:
                                    break
                            if not success:
                                parts = event_location_str.split()
                                els = " ".join(parts[:-1])
                                if els in self.locations:
                                    event_location = self.locations[els]
                                    event_location_details = parts[-1]
                                    success = True
                                if not success:
                                    els = " ".join(parts[1:])
                                    if els in self.locations:
                                        event_location = self.locations[els]
                                        event_location_details = parts[0]
                                        success = True
                                    if not success:
                                        event_location = ""
                                        event_location_details = event_location_str
                    else:
                        event_location = ""
                        event_location_details = "; ".join([
                            elo.text for elo in event_location_objs])
                else:
                    event_location = ""
                    event_location_details = ""

                event_cluster = EventCluster(
                    cluster_title = cluster_title,
                    cluster_description = cluster_description,
                    cluster_user_created = self.user,
                )
                event_cluster.save()
                for cluster_tag in self.cluster_tags:
                    event_cluster.cluster_tags.add(cluster_tag)
                event_cluster.save()
                event = Event(
                    event_cluster=event_cluster,
                    event_date_time_start=event_date_time_start,
                    event_date_time_end=event_date_time_end,
                    event_location=event_location,
                    event_location_details=event_location_details,
                    event_user_last_modified=self.user,
                    event_attendee_count=0,
                )
                event.save()

                print (u"Added event '%s' (%s - %s)" % (
                    cluster_title,
                    event_date_time_start,
                    event_date_time_end)).encode('ascii', 'ignore')
Exemple #20
0
def edit_repeat(request):
    if request.method == 'POST':
        # get passed in data
        user = request.user
        id = request.POST['sid']
        oldStart = strToDateTime(request.POST['oldStart'])
        newStart = strToDateTime(request.POST['start'])
        newEnd = strToDateTime(request.POST['end'])
        type = request.POST['type']
        endRepeat = request.POST['endRepeat']

        # handle datatype conversions
        if endRepeat == 'null':
            endRepeat = None

        # get old RepeatEvent object
        repeat = user.repeatevent_set.get(pk=id)
        breaks = repeat.breaks.all()
        oldEndRepeat = repeat.endRepeat

        # get break events to move to new repeatevent
        breaks_new = []
        for br in breaks:
            if br.date > oldStart:
                # remove from old repeat
                repeat.breaks.remove(br)
                # add to breaks_new array
                breaks_new.append(br)

        # container to hold httpresponse of ids
        ids = ''

        # check whether oldStart is the head
        if oldStart == repeat.start:
            # delete old RepeatEvent
            repeat.delete()

        # check if you are one past the head
        elif oneBack(oldStart, repeat) == repeat.start:
            # make the head of the old RepeatEvent into a new Event object
            event = Event(user=user,
                          title=repeat.title,
                          start=repeat.start,
                          end=repeat.end,
                          allDay=repeat.allDay)
            event.save()

            # add id to container
            ids = str(event.id) + ','

            # delete old RepeatEvent
            repeat.delete()

        # otherwise
        else:
            # set end date of old RepeatEvent to one instance back of the passed in date
            end = oneBack(oldStart, repeat)
            # update old RepeatEvent and save
            repeat.endRepeat = end
            repeat.save()

        # create new Event object if you edited the last in the chain
        # could be editing last in chain and making it a new rrule
        if type == 'event':
            tail = Event(user=user,
                         title=request.POST['title'],
                         start=newStart,
                         end=newEnd,
                         allDay=request.POST['allDay'])
            tail.save()

            # add id to container
            ids += str(tail.id)

        # create new RepeatEvent object otherwise
        else:
            new_repeat = RepeatEvent(user=user,
                                     title=request.POST['title'],
                                     start=newStart,
                                     end=newEnd,
                                     allDay=request.POST['allDay'],
                                     rrule=int(request.POST['rrule']),
                                     endRepeat=endRepeat)
            new_repeat.save()

            # add id to container
            ids += str(new_repeat.id)

            # move breaks and endRepeat to new chain by delta
            delta = newStart - oldStart
            for br in breaks_new:
                br.date += delta
                br.save()
                new_repeat.breaks.add(br)
            if (oldEndRepeat):
                new_repeat.endRepeat = oldEndRepeat + delta
                new_repeat.save()

        # '3' OR '1,3' where first number is the event id for the head and second is id of new RepeatEvent / Event (if last moved is tail)
        return HttpResponse(ids)
    else:
        return HttpResponseRedirect('/')
Exemple #21
0
    def handle(self):
        bs = BeautifulSoup(self.content)
        if 'container' in self.kwargs:
            # TODO
            bs = bs.find("div",
                         self.kwargs['container']).find("div", "view-content")

        ele = bs.find('h3')
        tmp_day = ele.text.split(',')[-1].strip()
        tmp_day += str(datetime.today().year)

        while ele.nextSibling:
            ele = ele.nextSibling
            if type(ele) == NavigableString:
                continue
            elif ele.name == 'h3':
                tmp_day = ele.text.split(',')[-1].strip()
                tmp_day += str(datetime.today().year)
            elif ele.name == 'div':
                # Get all div's with a certain class.
                bs_event = ele

                bs_title = bs_event.find(attrs={
                    'class': self.kwargs['cluster_title']
                }).find('a')
                cluster_title = bs_title.string

                tmp_description = bs_event.find('p')
                if tmp_description:
                    cluster_description = strip_tags(
                        unicode(bs_event.find('p')), ['a'])
                else:
                    cluster_description = ""
                if 'url' in self.kwargs:
                    cluster_url = "http://path.princeton.edu" + bs_title['href']
                    cluster_description += (
                        "<p>Note: This event was automatically added from"
                        " <a href='http://path.princeton.edu'>Path to Princeton</a>, and may not"
                        " be fully accurate.  Click <a href='%s'>here</a> for the original event.</p>"
                        % (cluster_url, ))

                # TODO
                tmp_starttime = bs_event.find(
                    attrs={'class': "date-display-start"})
                if tmp_starttime:
                    tmp_starttime = tmp_starttime.text
                    event_date_time_start = parse_time(tmp_day, tmp_starttime)
                    tmp_endtime = bs_event.find(attrs={
                        'class': "date-display-end"
                    }).text
                    event_date_time_end = parse_time(tmp_day, tmp_endtime)
                else:
                    tmp_starttime = bs_event.find(
                        attrs={
                            'class': "date-display-single"
                        }).text
                    event_date_time_start = parse_time(tmp_day, tmp_starttime)
                    event_date_time_end = event_date_time_start + timedelta(
                        hours=1)

                # TODO
                tmp_location = bs_event.find(
                    attrs={'class': self.kwargs['event_location']})
                if tmp_location:
                    event_location_objs = tmp_location.find(
                        attrs={
                            'class': 'field-content'
                        }).findAll('li')
                    if len(event_location_objs) == 1:
                        event_location_str = event_location_objs[0].text
                        success = False
                        if event_location_str in self.locations:
                            event_location = self.locations[event_location_str]
                            if event_location_str in self.alt_locations:
                                event_location_details = event_location_str
                            else:
                                event_location_details = ""
                        else:
                            # Try various methods..
                            for c in [", ", " - "]:
                                if c in event_location_str:
                                    parts = event_location_str.split(c)
                                    for i, els in enumerate(parts):
                                        if els in self.locations:
                                            event_location = self.locations[
                                                els]
                                            parts.pop(i)
                                            event_location_details = c.join(
                                                parts)
                                            success = True
                                if success:
                                    break
                            if not success:
                                parts = event_location_str.split()
                                els = " ".join(parts[:-1])
                                if els in self.locations:
                                    event_location = self.locations[els]
                                    event_location_details = parts[-1]
                                    success = True
                                if not success:
                                    els = " ".join(parts[1:])
                                    if els in self.locations:
                                        event_location = self.locations[els]
                                        event_location_details = parts[0]
                                        success = True
                                    if not success:
                                        event_location = ""
                                        event_location_details = event_location_str
                    else:
                        event_location = ""
                        event_location_details = "; ".join(
                            [elo.text for elo in event_location_objs])
                else:
                    event_location = ""
                    event_location_details = ""

                event_cluster = EventCluster(
                    cluster_title=cluster_title,
                    cluster_description=cluster_description,
                    cluster_user_created=self.user,
                )
                event_cluster.save()
                for cluster_tag in self.cluster_tags:
                    event_cluster.cluster_tags.add(cluster_tag)
                event_cluster.save()
                event = Event(
                    event_cluster=event_cluster,
                    event_date_time_start=event_date_time_start,
                    event_date_time_end=event_date_time_end,
                    event_location=event_location,
                    event_location_details=event_location_details,
                    event_user_last_modified=self.user,
                    event_attendee_count=0,
                )
                event.save()

                print(u"Added event '%s' (%s - %s)" %
                      (cluster_title, event_date_time_start,
                       event_date_time_end)).encode('ascii', 'ignore')
Exemple #22
0
def free_repeat(request):
    if request.method == 'POST':
        # get passed in data
        user = request.user
        event_start = strToDateTime(
            request.POST['start'])  # last date to free (starting from head)
        event_end = strToDateTime(request.POST['end'])
        id = request.POST['sid']
        title = request.POST['title']
        allDay = True if (request.POST['allDay'] == 'true') else False
        rrule = int(request.POST['rrule'])

        # calculate the event length if an end exists
        if event_end:
            event_length = event_end - event_start

        # get the old RepeatEvent object
        repeat = user.repeatevent_set.all().get(pk=id)
        head = repeat.start
        rruleOld = repeat.rrule

        # format the breaks array
        breaks = []
        for _break in repeat.breaks.all():
            breaks.append(_break.date)

        # delete the old RepeatEvent object
        repeat.delete()

        # loop from head to event_start, making new Event objects
        cursor = head
        ids = ''
        while cursor < event_start:
            # check if current date is a break
            if cursor in breaks:
                continue

            # make new event and save
            event = Event(user=user,
                          title=title,
                          start=cursor,
                          end=cursor,
                          allDay=allDay)

            # add length of event if it exists
            if event_end:
                event.end += event_length

            # save the event
            event.save()

            # add id to ids csv string
            ids += str(event.id) + ','

            # move cursor
            cursor = oneForward(cursor, rruleOld)

        # remove last comma
        ids = ids[:-1]

        return HttpResponse(ids)
    else:
        return HttpResponseRedirect('/')
Exemple #23
0
def edit_repeat(request):
    if request.method == 'POST':
        # get passed in data
        user = request.user
        id = request.POST['sid']
        oldStart = strToDateTime(request.POST['oldStart'])
        newStart = strToDateTime(request.POST['start'])
        newEnd = strToDateTime(request.POST['end'])
        type = request.POST['type']
        endRepeat = request.POST['endRepeat']

        # handle datatype conversions
        if endRepeat == 'null':
            endRepeat = None

        # get old RepeatEvent object
        repeat = user.repeatevent_set.get(pk = id)
        breaks = repeat.breaks.all()
        oldEndRepeat = repeat.endRepeat

        # get break events to move to new repeatevent
        breaks_new = []
        for br in breaks:
            if br.date > oldStart:
                # remove from old repeat
                repeat.breaks.remove(br)
                # add to breaks_new array
                breaks_new.append(br)

        # container to hold httpresponse of ids
        ids = ''

        # check whether oldStart is the head
        if oldStart == repeat.start:
            # delete old RepeatEvent
            repeat.delete()

        # check if you are one past the head
        elif oneBack(oldStart, repeat) == repeat.start:
            # make the head of the old RepeatEvent into a new Event object
            event = Event(
                user = user,
                title=repeat.title,
                start=repeat.start,
                end=repeat.end,
                allDay=repeat.allDay
            )
            event.save()

            # add id to container
            ids = str(event.id) + ','

            # delete old RepeatEvent
            repeat.delete()

        # otherwise
        else:
            # set end date of old RepeatEvent to one instance back of the passed in date
            end = oneBack(oldStart,repeat)
            # update old RepeatEvent and save
            repeat.endRepeat = end
            repeat.save()


        # create new Event object if you edited the last in the chain
        # could be editing last in chain and making it a new rrule
        if type == 'event':
            tail = Event(
                user = user,
                title=request.POST['title'],
                start=newStart,
                end=newEnd,
                allDay=request.POST['allDay']
            )
            tail.save()

            # add id to container
            ids += str(tail.id)

        # create new RepeatEvent object otherwise
        else:
            new_repeat = RepeatEvent(
                user = user,
                title=request.POST['title'],
                start=newStart,
                end=newEnd,
                allDay=request.POST['allDay'],
                rrule = int(request.POST['rrule']),
                endRepeat = endRepeat
            )
            new_repeat.save()

            # add id to container
            ids += str(new_repeat.id)

            # move breaks and endRepeat to new chain by delta
            delta = newStart - oldStart
            for br in breaks_new:
                br.date += delta
                br.save()
                new_repeat.breaks.add(br)
            if (oldEndRepeat):
                new_repeat.endRepeat = oldEndRepeat + delta
                new_repeat.save()

        # '3' OR '1,3' where first number is the event id for the head and second is id of new RepeatEvent / Event (if last moved is tail)
        return HttpResponse(ids)
    else:
        return HttpResponseRedirect('/')
Exemple #24
0
def edit_repeat(request):
    user = request.user
    id = request.POST['sid']
    oldStart = strToDateTime(request.POST['oldStart'])
    newStart = strToDateTime(request.POST['start'])
    newEnd = strToDateTime(request.POST['end'])

    # get old RepeatEvent object
    repeat = user.repeatevent_set.get(pk = id)
    breaks = repeat.breaks.all()

    # get break events to move to new repeatevent
    breaks_new = []
    for br in breaks:
        if br.date > oldStart:
            # remove from old repeat
            repeat.breaks.remove(br)
            # save to breaks_new array
            breaks_new.append(br)

    # container to hold httpresponse of ids
    ids = ''

    # check whether oldStart is the head
    if oldStart == repeat.start:
        # delete RepeatEvent
        repeat.delete()
    # check if you are one past the head
    elif oneBack(oldStart, 'rrule') == repeat.start:
        # make the head into a new Event object
        event = Event(
            user = user,
            title=repeat.title,
            start=repeat.start,
            end=repeat.end,
            allDay=repeat.allDay
        )
        event.save()
        # add id to container
        ids = str(event.id) + ','
        # delete RepeatEvent
        repeat.delete()
    # otherwise
    else:
        # set end date to one instance back of the passed in date
        end = oneBack(oldStart,'rrule')
        # update repeat and save
        repeat.endRepeat = end
        repeat.save()

    # create new RepeatEvent object based on new datetimes
    new_repeat = RepeatEvent(
        user = user,
        title=request.POST['title'],
        start=newStart,
        end=newEnd,
        allDay=request.POST['allDay']
    )
    new_repeat.save()

    # add id to container
    ids += str(new_repeat.id)

    # move breaks to new chain by delta
    delta = newStart - oldStart
    for br in breaks_new:
        br.date += delta
        br.save()
        new_repeat.breaks.add(br)

    # '3' OR '1,3' where first number is the event id for the head and second is id of new RepeatEvent
    return HttpResponse(ids)