Ejemplo n.º 1
0
    def renderFileInput(self):
        attrs = {
            'id': self.name + self.idSuffix(self),
        }

        current_file_fmt = """
        <br/>
        <p>
        File: <a href="%(link)s">%(name)s</a><br/>
        Size: %(size)s <br/>
        Uploaded on: %(uploaded)s UTC
        <p>
    """

        current_file = current_file_fmt % {
            'name':
            self.field._file.filename,
            'link':
            self.field._link,
            'size':
            defaultfilters.filesizeformat(self.field._file.size),
            'uploaded':
            dateformat.format(self.field._file.creation, 'M jS Y, h:i:sA'),
        } if getattr(self.field, '_file', False) else ""

        return mark_safe('%s%s%s%s' % (
            self._render_label(),
            self.as_widget(attrs=attrs),
            self._render_note(),
            current_file,
        ))
Ejemplo n.º 2
0
def birthdayURL(user):
    today = datetime.date.today()
    birthday = user.preferences.birthdate

    is_feb29 = False
    if birthday.month == 2 and birthday.day == 29:
        is_feb29 = True
        birthday = birthday.replace(
            month=user.preferences.birthdate.month + 1,
            day=1,
        )

    birthday = birthday.replace(year=today.year)
    if birthday < today:
        birthday = birthday.replace(year=today.year + 1)

    if is_feb29:
        try:
            birthday = birthday.replace(month=2, day=29)
        except ValueError:
            pass

    return 'https://www.timeanddate.com/countdown/birthday?iso={date}T00&msg={username}%27s+birthday'.format(
        date=dateformat.format(birthday, "Ymd"),
        username=user.username,
    )
Ejemplo n.º 3
0
def translate_date(date, language, date_format='DATE_FORMAT'):
    """
    Converts the provided date object into a string, while translating
    its value for the given language.  Both the format of the date
    as well as its values (i.e., name of the Month) are translated.

    If language is Spainish, then the entire date string is returned in
    lowercase. This is used to work around a bug in the Spanish django
    month translations.
    See EDUCATOR-2328 for more details.

    For example:
        date = datetime.datetime(2017, 12, 23)
        date_in_spanish = translate_date(date, 'es')
        assert date_in_spanish == '23 de deciembre de 2017'
    """
    with override(language):
        formatted_date = dateformat.format(
            date,
            get_format(date_format, lang=language, use_l10n=True),

        )
        if language and language.startswith('es'):
            formatted_date = formatted_date.lower()
        return formatted_date
Ejemplo n.º 4
0
def birthdayURL(user):
    if not user.preferences.birthdate:
        return None
    return 'https://www.timeanddate.com/countdown/birthday?iso={date}T00&msg={username}%27s+birthday'.format(
        date=dateformat.format(getNextBirthday(user.preferences.birthdate), "Ymd"),
        username=user.username,
    )
def translate_date(date, language, date_format='DATE_FORMAT'):
    """
    Converts the provided date object into a string, while translating
    its value for the given language.  Both the format of the date
    as well as its values (i.e., name of the Month) are translated.

    If language is Spainish, then the entire date string is returned in
    lowercase. This is used to work around a bug in the Spanish django
    month translations.
    See EDUCATOR-2328 for more details.

    For example:
        date = datetime.datetime(2017, 12, 23)
        date_in_spanish = translate_date(date, 'es')
        assert date_in_spanish == '23 de deciembre de 2017'
    """
    with override(language):
        formatted_date = dateformat.format(
            date,
            get_format(date_format, lang=language, use_l10n=True),

        )
        if language and language.startswith('es'):
            formatted_date = formatted_date.lower()
        return formatted_date
Ejemplo n.º 6
0
  def renderFileInput(self):
    attrs = {
        'id': self.name + self.idSuffix(self),
        }

    current_file_fmt = """
        <br/>
        <p>
        File: <a href="%(link)s">%(name)s</a><br/>
        Size: %(size)s <br/>
        Uploaded on: %(uploaded)s UTC
        <p>
    """
    current_file = current_file_fmt % {
        'name': self.field._file.filename,
        'link': self.field._link,
        'size': defaultfilters.filesizeformat(self.field._file.size),
        'uploaded': dateformat.format(
              self.field._file.creation, 'M jS Y, h:i:sA'),
    } if getattr(self.field, '_file', False) else ""

    return mark_safe('%s%s%s%s%s' % (
        self._render_label(),
        self.as_widget(attrs=attrs),
        self._render_error(),
        self._render_note(),
        current_file,
    ))
Ejemplo n.º 7
0
def may_expire(dt):
    now = datetime.now()

    css_class = 'expired' if dt < now else 'not-expired'
    formatted_datetime = dateformat.format(dt, settings.DATETIME_FORMAT)

    return mark_safe('<span class="%s">%s</span>' %
                     (css_class, formatted_datetime))
Ejemplo n.º 8
0
def birthdayURL(user):
    if not user.preferences.birthdate:
        return None
    return 'https://www.timeanddate.com/countdown/birthday?iso={date}T00&msg={username}%27s+birthday'.format(
        date=dateformat.format(getNextBirthday(user.preferences.birthdate),
                               "Ymd"),
        username=user.username,
    )
Ejemplo n.º 9
0
 def to_fields(self, item, *args, **kwargs):
     fields = super(MemberCollection, self).to_fields(
         item,
         *args,
         icons={
             'name': 'id',
             'japanese_name': 'id',
             'band': 'users',
             'school': 'max-bond',
             'school_year': 'max-bond',
             'CV': 'profile',
             'romaji_CV': 'profile',
             'birthday': 'event',
             'food_likes': 'heart',
             'food_dislikes': 'heart-empty',
             'hobbies': 'star',
             'description': 'id',
             'cards': 'album',
             'fans': 'heart',
         },
         images={
             'astrological_sign':
             '{}img/i_astrological_sign/{}.png'.format(
                 RAW_CONTEXT['static_url'], item.i_astrological_sign),
         },
         **kwargs)
     if 'square_image' in fields:
         del (fields['square_image'])
     setSubField(fields,
                 'birthday',
                 key='value',
                 value=lambda f: dateformat.format(item.birthday, "F d"))
     setSubField(fields, 'band', key='type', value=lambda f: 'image_link')
     setSubField(fields,
                 'band',
                 key='link',
                 value=lambda f: u'/members/?i_band={}'.format(item.i_band))
     setSubField(fields, 'band', key='link_text', value=lambda f: item.band)
     setSubField(fields,
                 'band',
                 key='value',
                 value=lambda f: '{}img/band/{}.png'.format(
                     RAW_CONTEXT['static_url'], item.band))
     setSubField(fields, 'description', key='type', value='long_text')
     if get_language() == 'ja':
         setSubField(fields, 'CV', key='verbose_name', value=_('CV'))
         if 'romaji_CV' in fields:
             del (fields['romaji_CV'])
     if 'description' in fields:
         fields['source'] = {
             'verbose_name': _('Source'),
             'link_text': 'BanGDreaming Tumblr',
             'type': 'link',
             'value': 'https://bangdreaming.tumblr.com/chara',
         }
     return fields
Ejemplo n.º 10
0
 def as_json(self):
     return {
         'pk': self.pk,
         'title': self.title,
         'author': self.author,
         'publication_date': dateformat.format(self.publication_date, 'r'),
         'category': self.category,
         'hero_image': self.hero_image.url,
         'opt_image': self.opt_image.url if self.opt_image else '',
         'content': self.content
     }
Ejemplo n.º 11
0
def setWaktuBerakhir(noAntrian):
    pasien_update = Pasien.objects.get(no_antrian=noAntrian, waktu_berakhir="")
    pasien_update.waktu_berakhir = dateformat.format(datetime.datetime.now(),
                                                     'H:i:s')
    time1 = datetime.datetime.strptime(pasien_update.waktu_mulai, '%H:%M:%S')
    time2 = datetime.datetime.strptime(pasien_update.waktu_berakhir,
                                       '%H:%M:%S')
    durasi = time2 - time1
    d = int(durasi.total_seconds())
    pasien_update.durasi_pengobatan = d
    print(pasien_update)
    pasien_update.save()
Ejemplo n.º 12
0
def translate_date(date, language, date_format='DATE_FORMAT'):
    """
    Converts the provided date object into a string, while translating
    its value for the given language.  Both the format of the date
    as well as its values (i.e., name of the Month) are translated.

    For example:
        date = datetime.datetime(2017, 12, 23)
        date_in_spanish = translate_date(date, 'es')
        assert date_in_spanish = '12 de Deciembre de 2017'
    """
    with override(language):
        return dateformat.format(
            date,
            get_format(date_format, lang=language, use_l10n=True),
        )
Ejemplo n.º 13
0
def setDataSet(noAntrian):
    from api.views import getAge
    dataPasien = DataPasien.objects.get(id=noAntrian.data_pasien.id)
    umur = getAge(dataPasien.tempat_tgl_lahir)
    nama_dokter = getNamaDokter(noAntrian.jenis_pengobatan)
    data = {
        'nama_pasien': noAntrian.data_pasien.nama_pasien,
        'jenis_kelamin': noAntrian.data_pasien.jenis_kelamin,
        'umur': umur,
        'nama_dokter': nama_dokter,
        'jenis_pengobatan': noAntrian.jenis_pengobatan,
        'waktu_mulai': dateformat.format(datetime.datetime.now(), 'H:i:s'),
        'waktu_berakhir': "",
        'durasi_pengobatan': 0,
        'no_antrian': noAntrian,
    }
    Pasien.objects.bulk_create([Pasien(**data)])
Ejemplo n.º 14
0
def _add_upsell_button_information_to_template_context(user, schedule,
                                                       template_context):
    enrollment = schedule.enrollment
    course = enrollment.course

    verified_upgrade_link = _get_link_to_purchase_verified_certificate(
        user, schedule)
    has_verified_upgrade_link = verified_upgrade_link is not None

    if has_verified_upgrade_link:
        template_context['upsell_link'] = verified_upgrade_link
        template_context[
            'user_schedule_upgrade_deadline_time'] = dateformat.format(
                enrollment.dynamic_upgrade_deadline,
                get_format('DATE_FORMAT', lang=course.language, use_l10n=True))

    template_context['show_upsell'] = has_verified_upgrade_link
Ejemplo n.º 15
0
def _upgrade_reminder_schedules_for_bin(site, target_day, bin_num, org_list, exclude_orgs=False):
    beginning_of_day = target_day.replace(hour=0, minute=0, second=0)

    schedules = get_schedules_with_target_date_by_bin_and_orgs(
        schedule_date_field='upgrade_deadline',
        target_date=beginning_of_day,
        bin_num=bin_num,
        num_bins=RECURRING_NUDGE_NUM_BINS,
        org_list=org_list,
        exclude_orgs=exclude_orgs,
    )

    LOG.debug('Upgrade Reminder: Query = %r', schedules.query.sql_with_params())

    for schedule in schedules:
        enrollment = schedule.enrollment
        user = enrollment.user

        course_id_str = str(enrollment.course_id)

        # TODO: group by schedule and user like recurring nudge
        course_id_strs = [course_id_str]
        first_schedule = schedule

        template_context = get_base_template_context(site)
        template_context.update({
            'student_name': user.profile.name,
            'user_personal_address': user.profile.name if user.profile.name else user.username,
            'user_schedule_upgrade_deadline_time': dateformat.format(
                schedule.upgrade_deadline,
                get_format(
                    'DATE_FORMAT',
                    lang=first_schedule.enrollment.course.language,
                    use_l10n=True
                )
            ),

            'course_name': first_schedule.enrollment.course.display_name,
            'course_url': absolute_url(site, reverse('course_root', args=[str(first_schedule.enrollment.course_id)])),

            # This is used by the bulk email optout policy
            'course_ids': course_id_strs,
            'cert_image': absolute_url(site, static('course_experience/images/verified-cert.png')),
        })

        yield (user, first_schedule.enrollment.course.language, template_context)
Ejemplo n.º 16
0
def _get_upsell_information_for_schedule(user, schedule):
    template_context = {}
    enrollment = schedule.enrollment
    course = enrollment.course

    verified_upgrade_link = _get_verified_upgrade_link(user, schedule)
    has_verified_upgrade_link = verified_upgrade_link is not None

    if has_verified_upgrade_link:
        template_context['upsell_link'] = verified_upgrade_link
        template_context[
            'user_schedule_upgrade_deadline_time'] = dateformat.format(
                enrollment.dynamic_upgrade_deadline,
                get_format('DATE_FORMAT', lang=course.language, use_l10n=True))

    template_context['show_upsell'] = has_verified_upgrade_link
    return template_context
Ejemplo n.º 17
0
def _add_upsell_button_information_to_template_context(user, schedule, template_context):
    enrollment = schedule.enrollment
    course = enrollment.course

    verified_upgrade_link = _get_link_to_purchase_verified_certificate(user, schedule)
    has_verified_upgrade_link = verified_upgrade_link is not None

    if has_verified_upgrade_link:
        template_context['upsell_link'] = verified_upgrade_link
        template_context['user_schedule_upgrade_deadline_time'] = dateformat.format(
            enrollment.dynamic_upgrade_deadline,
            get_format(
                'DATE_FORMAT',
                lang=course.language,
                use_l10n=True
            )
        )

    template_context['show_upsell'] = has_verified_upgrade_link
Ejemplo n.º 18
0
def _get_upsell_information_for_schedule(user, schedule):
    template_context = {}
    enrollment = schedule.enrollment
    course = enrollment.course

    verified_upgrade_link = _get_verified_upgrade_link(user, schedule)
    has_verified_upgrade_link = verified_upgrade_link is not None

    if has_verified_upgrade_link:
        template_context['upsell_link'] = verified_upgrade_link
        template_context['user_schedule_upgrade_deadline_time'] = dateformat.format(
            enrollment.dynamic_upgrade_deadline,
            get_format(
                'DATE_FORMAT',
                lang=course.language,
                use_l10n=True
            )
        )

    template_context['show_upsell'] = has_verified_upgrade_link
    return template_context
Ejemplo n.º 19
0
def get_countdown_url(date, days, title):
    new_date = date + relativedelta(days=days)
    return (
        new_date,
        'https://www.timeanddate.com/countdown/birthday?iso={}T11&p0=%3A&msg={}&font=sanserif&csz=1'
        .format(dateformat.format(new_date, "Ymd"), title.replace(' ', '+')))
Ejemplo n.º 20
0
def datetime_str(dt):
    return dateformat.format(dt, settings.DATETIME_FORMAT)
Ejemplo n.º 21
0
def date_str(d):
    return dateformat.format(d, settings.DATE_FORMAT)
Ejemplo n.º 22
0
 def get_time_created_data(self, obj):
     return dateformat.format(obj.date_created, settings.TIME_FORMAT)
Ejemplo n.º 23
0
    def handle(self, *args, **options):

        if len(args) < 7:
            print 'Specify idol name, template banner url, template small banner url, banner url, banner author (cay say "NONE"), pixel idols image (can say "NONE"), prizes banner url (can say "NONE")'
            return
        idol_name = args[0]
        template_banner_url = args[1]
        template_small_banner_url = args[2]
        banner_url = args[3] if args[3] != 'NONE' else None
        banner_author = args[4] if args[4] != 'NONE' else None
        pixel_idols = args[5] if args[5] != 'NONE' else None
        prizes_banner_url = args[6] if args[6] != 'NONE' else None

        idol = models.Idol.objects.exclude(name__contains='Marika').filter(
            Q(name__contains=' {}'.format(idol_name))
            | Q(name__exact=idol_name))[0]
        if idol.name == 'Emma Verde':
            idol.name = 'Verde Emma'
        if idol.name == 'Tsushima Yoshiko':
            idol.name = 'Tsushima Yohane'
        birthday = get_birthday(idol)
        # hashtag = u'{}BirthdayGiveaway{}'.format(idol.short_name, birthday.year)
        hashtag = u'{}FanAwards{}'.format(idol.short_name, birthday.year)
        _idol, still_running_giveaways, voting_ongoing_giveaways, coming_soon_giveaways = get_other_giveaways(
            hashtag)
        days_to_enter, days_to_vote = get_days(idol)
        with_staff_picks = get_with_staff_picks(idol)
        is_main = idol.name not in PDP_IDOLS and idol.main

        end_date, countdown_url = get_countdown_url(
            birthday,
            days_to_enter,
            title='End of {} {} Fan Awards'.format(birthday.year,
                                                   idol.short_name),
        )

        vote_end_date, countdown_vote_url = get_countdown_url(
            birthday,
            days_to_enter + days_to_vote,
            title='{} {} Fan Awards - Votes closing in'.format(
                birthday.year, idol.short_name),
        )

        print '![{} {} Fan Awards]({})'.format(birthday.year, idol.name,
                                               template_banner_url)
        print ''
        print '## **Welcome to {}\'s {} Fan Awards!**'.format(
            idol.name, birthday.year)
        print ''
        print ''
        print 'A celebration of each and everyone of {name}\'s fans, where everyone, community and staff included, is here to love and recognize all fans of our favorite idol: {name}!'.format(
            name=idol.short_name, )
        print ''
        print '***Going all out or casually entering?* We\'re looking forward to see your posts!**'
        print ''
        print '***'
        print ''
        print '# **How to join the celebrations?**'
        print ''
        print '1. [Create an activity on School Idol Tomodachi](https://github.com/SchoolIdolTomodachi/SchoolIdolAPI/wiki/How-to-post-an-activity%3F)'
        print '1. Do something to **show your love for {}** and celebrate her birthday!'.format(
            idol.short_name)
        print '    - *It can be a photo, cosplay, your figures, a song cover, a drawing, a poem, a story or anything else! It can be very short or very long. The only rule is that it has to be about {}!*'.format(
            idol.short_name)
        print '1. Write "**{}**" somewhere in your activity, without spaces.'.format(
            hashtag)
        print '    - *This is how everyone knows you\'re joining the celebrations!*'
        print ''
        print '***'
        print ''
        print '### Tag posting period: {} - {} - *[Countdown]({})*'.format(
            dateformat.format(
                birthday,
                'F jS Y' if birthday.year != end_date.year else 'F jS'),
            dateformat.format(
                end_date,
                'F jS Y' if birthday.month != end_date.month else 'jS Y'),
            countdown_url)
        print ''
        print '### -> [See all participants](http://schoolido.lu/#search={})'.format(
            hashtag)
        print '*right click to open in new tab*'
        print ''
        print '***'
        print ''
        print '# **Bonus prize for a lucky winner!**'
        print ''
        print '![Lucky winner](https://i.imgur.com/tpQXUQo.png)'
        print 'As a little bonus and thank you from the staff, we will give away a prize to a lucky winner, selected randomly!'
        print ''
        print '- **If you want to be eligible for a prize:**'
        print '    - *You are only allowed to post **up to 3** full size pictures.*'
        print '        - *If you want to post more, use our [gallery generator](http://imgur.gallery.db0.company/).*'
        print '        - *If you append multiple images **vertically** in a single image, they\'ll still count as **multiple** images.*'
        print '        - *If you append multiple images **horizontally** in a single image, they\'ll count as **one image**, as they won\'t make the post longer.*'
        print '    - *If you post artworks, only post official artworks or artworks you own.*'
        print '        - *Fan artworks by other artists are not allowed.*'
        print '    - *You can post pictures of your **merch or SIF cards collection** if you\'d like, but they won\'t be taken into account in the judging phase to ensure fairness for those who can\'t afford them.*'
        print '- **Otherwise**:'
        print '    - *You\'re more than welcome to post using the tag to join in the celebration even when you don\'t want to get a prize. Just let us know by writing "**JustForFun**" anywhere in your entry.*'
        print ''
        print 'Winner will be announced **[after the end of the awards entry period]({})**.'.format(
            countdown_url, )
        print ''
        print '# **Prize**'
        print ''
        print '- 1 custom commissioned {} graphic edit of your choice: wallpaper, avatar, Twitter header, ...'.format(
            idol.short_name)
        print ''
        print '![Comissioned graphic edit](https://i.imgur.com/8GMA2Dt.png)'
        print ''
        print '***'
        print '***'
        print '***'
        print ''
        print '# **![Stretch goals](https://i.imgur.com/btOF5QS.png)**'
        print ''
        print 'Introducing **stretch goals**: starting now, we will add more winners and more prizes based on how many people enter our Fan Awards!'
        print ''
        print 'More participants? More fun!'
        print ''
        print '### **If we get 15 participants or more:**'
        print ''
        print 'We will add another winner, elected by the community!'
        print ''
        print '# ![#1 Crowd\'s Favorite Winner - elected by the community](https://i.imgur.com/0jKB10n.png)'
        print ''
        print 'Make everyone fall in love with {} thanks to your entry and they\'ll leave a like! The most liked entry at the end of the awards will get **a commissioned graphic edit of their choice**.'.format(
            idol.short_name)
        print ''
        print '*Crowd\'s Favorite winner is not eligible to be the Lucky winner.*'
        print ''
        print '### **If we get 30 participants or more:**'
        print ''
        print 'We will get a special judges panel to pick the Grand winner!'
        print ''
        print '![#1 Grand winner - elected by our judges panel](https://i.imgur.com/FP0cMmw.png)'
        print ''
        print 'Our [judges panel](https://goo.gl/forms/42sCU6SXnKbqnag23) will pay attention to:'
        print ''
        print '- Creativity & Originality'
        print '- Effort'
        print '- Passion'
        print ''
        print 'Learn more about [how judging works](https://github.com/MagiCircles/Circles/wiki/Giveaways-FAQ#how-do-judges-pick-entries) or [how to become a judge](https://goo.gl/forms/42sCU6SXnKbqnag23).'
        print ''
        print '**All** winners will be announced **[{} days after the end of the awards entry period]({})**, to give the judges time to vote.'.format(
            days_to_vote,
            countdown_vote_url,
        )
        print ''
        print 'The Grand winner will get a prize of their choice between:'
        print ''
        print '- 1 {} physical prize (official merch)'.format(
            'Love Live!' if not is_main else idol.short_name)
        print '- 1 custom comissioned art of {} with outfit and text of your choice'.format(
            idol.short_name)
        print '- 1 custom commissioned {} graphic edit of your choice: wallpaper, avatar, Twitter header, ...'.format(
            idol.short_name)
        print ''
        print '![Physical prize](https://i.imgur.com/CWEgyLu.png)'
        print '![Custom drawing](https://i.imgur.com/hUHFYHc.png)'
        print ''
        if pixel_idols:
            print '- 1 custom {} **square keychain** by [shinylyni](http://schoolido.lu/user/shinylyni/)'.format(
                idol.short_name)
            print '- 1 custom {} **round keychain** by [shinylyni](http://schoolido.lu/user/shinylyni/)'.format(
                idol.short_name)
            print '- 1 custom {} **badge** by [shinylyni](http://schoolido.lu/user/shinylyni/)'.format(
                idol.short_name)
            print ''
            print '![Example of keychain / badges](http://i.imgur.com/CJkU0q8.jpg)'
            if pixel_idols:
                print ''
                print '![Chibi pixel idols]({})'.format(pixel_idols)
                print ''
            print ''
        print ''
        print ''
        print '*Subject to availability*'
        print ''
        if prizes_banner_url:
            print '![Prizes]({})'.format(prizes_banner_url)
            print ''

        print ''
        print '*Grand winner is not eligible to be the Crowd\'s Favorite winner or the Lucky winner.*'
        print ''
        print '### **If we get 50 participants or more:**'
        print ''
        print '![#2 Grand winner - Runner up](https://i.imgur.com/T0JEn99.png)'
        print ''
        print 'We will add a runner-up Grand winner picked by our judges panel.'
        print ''
        print 'The runner-up Grand winner will get a prize of their choice between a physical of digital prize.'
        print ''
        print '*Runner-up Grand winner is not eligible to be the Crowd\'s Favorite winner or the Lucky winner.*'
        print ''
        print '### **If we get even more:**'
        print ''
        print 'We will add more stretch goals!'
        print ''
        print '***'
        print ''
        print '# **![Got some merch you don\'t need?](https://i.imgur.com/VG1KvNd.png)**'
        print ''
        print 'Our giveaways are organized by fans and for fans! We accept donations of hand-made gifts or official merch!'
        print ''
        print 'If you have something to donate and want to support our giveaways, [join our Discord](https://discord.gg/fmc6fef) and in the channel #ask_us_anything, mention @db0'
        print ''
        print 'We cover shipping costs for you!'
        print ''
        print '# **![Artist or graphic editor?](https://i.imgur.com/MLZvqbW.png)**'
        print ''
        print 'Join our team to help make prizes for winners!'
        print ''
        print '[Join our Discord](https://discord.gg/mehDTsv) and in the channel #ask_for_roles, say "Graphic designer" or "Artist"'
        print ''
        print '***'
        print ''
        print_support_us()
        print ''
        if banner_url:
            print '***'
            print ''
            print '![{} Birthday Giveaway]({})'.format(idol.name, banner_url)
            if banner_author:
                print '###### Banner by [{}](https://schoolido.lu/user/{}/)'.format(
                    banner_author, banner_author)
            print ''
            print '***'
            print ''
        print '# **![F.A.Q.](https://i.imgur.com/vghSFuS.png)**'
        print ''
        print '- **I\'m not popular, can I win?**'
        print '    - Yes! The Lucky winner is selected randomly, so you have the same chances as everyone. The Grand winner (if any) will be picked based on effort, creativity, originality and passion. So do your best, you can do it :)'
        print '- **Does it matter if I win or not?**'
        print '    - The awards are first of all a celebration of our love for {name}. The prizes are just here to recognize those who went all out, and do not invalidate you as a {name} fan <3'.format(
            name=idol.short_name)
        print '- **Is it international?**'
        print '    - Yes'
        print '- **Do I have to pay for shipping?**'
        print '    - No'
        print '- **I can\'t give you my address, can I join?**'
        print '    - Yes. If you win a physical prize, we will give you a digital prize instead.'
        print '- **Can I re-use something I didn\'t make specifically for this contest?**'
        print '    - Yes, but only if you didn\'t use it in a Circles contest before.'
        print '- **How can I include images, audio and videos in my entry?**'
        print '    - For images, [follow this guide](https://github.com/MagiCircles/Circles/wiki/Activity-images). For anything else, include an external link.'
        print '- **Do I have to post in English?**'
        print '    - No, any language is accepted.'
        print '- **How can  I thank you for your amazing work organizing these contests?**'
        print '    - We always appreciate sweet comments below, and if you want to push it a little further, we have a [Patreon](https://patreon.com/db0company/) open for donations <3'
        print '- **More questions?**'
        print '    - Read the [Giveaways FAQ](https://github.com/MagiCircles/Circles/wiki/Giveaways-FAQ) and ask your questions in the comments.'

        print ''
        print '***'
        print '***'
        print '***'
        print ''
        if still_running_giveaways or voting_ongoing_giveaways or coming_soon_giveaways:
            print_still_running_and_coming_soon(still_running_giveaways,
                                                voting_ongoing_giveaways,
                                                coming_soon_giveaways,
                                                idol,
                                                with_icons=True)
            print ''
            print '***'
            print ''
        print ''
        print '###### {}'.format(hashtag)
        print '[]({}#small)'.format(template_small_banner_url)
        print ''
        print ''
        print '--------- END OF POST TO COPY'
        print ''
        banners = [
            {
                'url':
                'https://schoolido.lu/activities/ID/',
                'image':
                template_small_banner_url,
                'name':
                u'{} Fan Awards - Why do you love {}? Tell us and win prizes! Keychains, badges, custom art and more!'
                .format(idol.name, idol.short_name),
            },
        ]
        if prizes_banner_url:
            banners.append({
                'url':
                'https://schoolido.lu/activities/ID/',
                'image':
                prizes_banner_url,
                'name':
                u'{} Fan Awards - Why do you love {}? Tell us and win prizes! Keychains, badges, custom art and more!'
                .format(idol.name, idol.short_name),
            })
        if banner_url:
            banners.append({
                'url':
                'https://schoolido.lu/activities/ID/',
                'image':
                banner_url,
                'name':
                u'{} Birthday Giveaway - Why do you love {}? Tell us and win prizes! Keychains, badges, custom art and more!'
                .format(idol.name, idol.short_name),
            })
        pprint(banners)
        print ''
        print ''
Ejemplo n.º 24
0
 def get_time_start_data(self, obj):
     if obj.time_start:
         return dateformat.format(obj.time_start, settings.TIME_FORMAT)
     return None
Ejemplo n.º 25
0
 def get_date_end_data(self, obj):
     if obj.date_end:
         return dateformat.format(obj.date_end, settings.SHORT_DATE_FORMAT)
     return None
Ejemplo n.º 26
0
 def get_time_end_data(self, obj):
     if obj.time_end:
         return dateformat.format(obj.time_end, settings.TIME_FORMAT)
     return None
Ejemplo n.º 27
0
    def handle(self, *args, **options):

        if len(args) < 4:
            print 'Specify idol name, banner url, banner author (cay say "NONE"), pixel idols image (can say "NONE")'
            return
        idol_name = args[0]
        banner_url = args[1]
        banner_author = args[2] if args[2] != 'NONE' else None
        pixel_idols = args[3] if args[3] != 'NONE' else None

        today = datetime.date.today()
        in_300_days = today + relativedelta(days=300)

        idol = models.Idol.objects.filter(name__icontains=idol_name)[0]
        end_of_giveaway = get_next_birthday(
            idol.birthday) + relativedelta(days=16)
        if end_of_giveaway >= in_300_days:
            end_of_giveaway = end_of_giveaway.replace(end_of_giveaway.year - 1)

        countdown_url = 'https://www.timeanddate.com/countdown/birthday?iso={}T00&p0=%3A&msg=End+of+School+Idol+Tomodachi+{}+Birthday+Giveaway&font=sanserif&csz=1'.format(
            dateformat.format(end_of_giveaway, "Ymd"),
            idol.short_name,
        )

        print '![{} Birthday Giveaway]({})'.format(idol.name, banner_url)
        if banner_author:
            print '###### Banner by [{}](https://schoolido.lu/user/{}/)'.format(
                banner_author, banner_author)
        print ''
        print '# **Support our giveaways!**'
        print ''
        print 'These giveaways are made possible thanks to the support of our warm-hearted donators. If you wish to support School Idol Tomodachi for both our future giveaways and to cover the cost of our expensive servers in which our site run, please consider [donating on Patreon](http://patreon.com/db0company).'
        print ''
        print '[![Support us on Patreon](https://i.imgur.com/YYwkEhP.png)](http://patreon.com/db0company)'
        print ''
        print '***'
        print ''
        print '## Let\'s celebrate {}\'s birthday together!'.format(
            idol.short_name)
        print ''
        print '# -> [Countdown before the end of the giveaway]({})'.format(
            countdown_url)
        print '# -> [See all entries](http://schoolido.lu/#search={}BirthdayGiveaway2018)'.format(
            idol.short_name, )
        print ''
        print '# Enter our giveaway to win:'
        print ''
        if pixel_idols:
            print '- 1 custom {} keychain'.format(idol.name)
            print '    - The keychain is going to be hand made and will have a pixel illustration of {} made by [shinylyni](http://schoolido.lu/user/shinylyni/)~'.format(
                idol.short_name)
            print '    - [Example of keychain (from previous giveaway)](https://i.imgur.com/1EfFpeB.jpg)'
            print ''
            print '- 1 custom {} badge'.format(idol.name)
            print '    - The badge is going to be hand made and will have a pixel illustration of {} made by [shinylyni](http://schoolido.lu/user/shinylyni/)~'.format(
                idol.short_name)
            print '    - [Example of badges (from previous giveaway)](https://i.imgur.com/jHzqJQR.jpg)'
            print ''
            print '![]({})'.format(pixel_idols)
            print ''
            print '![](http://i.imgur.com/CJkU0q8.jpg)'
            print ''
        print '- 1 Custom {} drawing with outfit and text of your choice'.format(
            idol.name)
        print ''
        print '- 1 Custom {} wallpaper, avatar, Twitter header, or any other graphic edit of your choice'.format(
            idol.name)
        print ''
        print '- More prizes may be announced later!'
        print ''
        print 'If you wish to help support this giveaway or other giveaways in the future and you have something to give away, we\'d be more than happy to add you to the list of prizes!:'
        print ''
        print '- Digital art or edit: [Join our Discord](https://discord.gg/mehDTsv) and in the channel #ask_permissions_to_join, say "Graphic designer" or "Artist"'
        print '- Physical hand-made gift or official merch: [Join our Discord](https://discord.gg/fmc6fef) and in the channel #chat_lovelive, mention @db0 (note: we cover shipping costs for you!)'
        print ''
        print '# **How to enter?**'
        print ''
        print '1. [Create an activity on School Idol Tomodachi](https://github.com/SchoolIdolTomodachi/SchoolIdolAPI/wiki/How-to-post-an-activity%3F)'
        print '1. Do something to celebrate {}\'s birthday: it can be a photo, cosplay, your figures, a song cover, a drawing, a poem, a story or anything else! It can be very short or very long. The only rule is that it has to be about {}!'.format(
            idol.short_name, idol.short_name)
        print '1. If you post artworks, only post official artworks, artworks you own, or fan artworks that are approved by the artist and credited.'
        print '1. Write "{}BirthdayGiveaway2018" somewhere in your activity, without spaces (this is how we\'ll know you\'re entering the giveaway!)'.format(
            idol.short_name)
        print '1. To confirm that your entry is in, [check this link](http://schoolido.lu/#search={}BirthdayGiveaway2018) (you may need to wait a few days to get it approved by either our staff teams or by the community by getting enough likes)'.format(
            idol.short_name)
        print ''
        print '# **How to win?**'
        print ''
        print '1. The judges are going to be all of you, the members of the site!'
        print '    - You have until the end of the [countdown]({}) to get as many "likes" as you can on your activity.'.format(
            countdown_url)
        print '1. At the end of the [countdown]({}), the top 3 activities with the most likes will be the winners!'.format(
            countdown_url)
        print '    - #1 and #2 winners get a physical prize. #3 winner gets a digital prize.'
        print '1. Our staff and contributors will also hand pick 1 extra winner who gets a physical prize, regardless of likes. They will pay attention to:'
        print '    - Creativity & Originality'
        print '    - Effort'
        print '    - Passion'
        print '1. We will send you a private message on School Idol Tomodachi to ask for your address to send you the prize.'
        print ''
        print ''
        print '# FAQ'
        print ''
        print '- **Is it international?**'
        print '    - Yes'
        print '- **Do I have to pay for shipping?**'
        print '    - No'
        print '- **I can\'t give you my address, can I join?**'
        print '    - Yes. If you win a physical prize, we will give you a digital prize instead.'
        print '- **I\'m not popular, can I win?**'
        print '    - Yes! The staff team picks a winner based on effort, creativity, originality and passion so do your best, you can do it~'
        print '- **Can I enter multiple times or combine multiple giveaway entries into one?**'
        print '    - Yes, but you\'ll only get one prize if you win.'
        print '- **Can I re-use something I didn\'t make specifically for this contest?**'
        print '    - Yes, but only if you didn\'t use it in a Circles contest before.'
        print '- **How can I include images, audio and videos in my entry?**'
        print '    - For images, [follow this guide](https://github.com/MagiCircles/Circles/wiki/Activity-images). For anything else, include an external link.'
        print '- **Do I have to post in English?**'
        print '    - No, any language is fine.'
        print '- **I posted and I can\'t see my activity on the homepage?**'
        print '    - After posting, scroll back to the form to post to get the direct link (or see errors if any). For your safety, only 18+ y/o users can see non-moderated activities on the homepage (in "new" tab). Wait for it to be approved by either our staff teams or by the community by getting enough likes.'
        print '- **How can  I thank you for your amazing work organizing these giveaways?**'
        print '    - We always appreciate sweet comments below, and if you want to push it a little further, we have a [Patreon](https://patreon.com/db0company/) open for donations <3'
Ejemplo n.º 28
0
 def get_time_open_data(self, obj):
     return dateformat.format(obj.date_open, settings.TIME_FORMAT)
Ejemplo n.º 29
0
 def get_date_created_data(self, obj):
     return dateformat.format(obj.date_created, settings.SHORT_DATE_FORMAT)
Ejemplo n.º 30
0
 def get_time_end_data(self, obj):
     if obj.time_end:
         return dateformat.format(obj.time_end, settings.TIME_FORMAT)
     return None
Ejemplo n.º 31
0
def dashboard_detail(request):
    v2_folder = ''
    user_logo = avatar_print_url(request.user, 200)

    headerparam_dict = {
        p: request.GET.get(p, '')
        for p in ['hideuserinfo', 'lang'] if p in request.GET
    }
    headerparam = urllib.urlencode(headerparam_dict)

    bodyparam_dict = {}
    if not request.GET.get('lang'):
        bodyparam_dict['lang'] = str(translation.get_language())
    bodyparam = urllib.urlencode(bodyparam_dict)

    # add '?page=baseline' to url if none exist
    if not request.GET.get('page'):
        currenturl = request.build_absolute_uri()
        return redirect(set_query_parameter(currenturl, 'page', 'baseline'))

    if 'pdf' in request.GET:
        try:
            domainpath = 'asdc.immap.org' + request.META.get('PATH_INFO')
            date_string = dateformat.format(datetime.date.today(), "Y-m-d")

            # create an API client instance
            client = pdfcrowd.Client(getattr(settings, 'PDFCROWD_UNAME'),
                                     getattr(settings, 'PDFCROWD_UPASS'))
            client.setPageWidth('8.3in')
            client.setPageHeight('11.7in')
            # client.setPageMargins('1in', '1in', '1in', '1in')
            client.setVerticalMargin("0.75in")
            client.setHorizontalMargin("0.25in")
            client.setHeaderUrl(
                'http://asdc.immap.org/static/isdc/head_print/rep_header_vector.html?onpdf='
                + user_logo['onpdf'] + '&userlogo=' + user_logo['logo_url'] +
                '&name=' + request.user.first_name + ' ' +
                request.user.last_name + '&cust_title=&organization=' +
                (request.user.organization or '') + '&isodate=' + date_string +
                '&' + headerparam)
            # convert a web page and store the generated PDF to a variable
            pdf = client.convertURI('http://' + str(domainpath) + 'print?' +
                                    request.META.get('QUERY_STRING') +
                                    '&user='******'&' +
                                    bodyparam)
            # set HTTP response headers
            response = HttpResponse(content_type="application/pdf")
            response["Cache-Control"] = "no-cache"
            response["Accept-Ranges"] = "none"
            response[
                "Content-Disposition"] = 'attachment; filename="' + request.GET[
                    'page'] + '_' + date_string + '.pdf"'

            # send the generated PDF
            response.write(pdf)

        except pdfcrowd.Error, why:
            options = {
                'quiet':
                '',
                'page-size':
                'A4',
                'page-width':
                '2550px',
                'page-height':
                '3300px',
                'dpi':
                300,
                # 'margin-left': 10,
                # 'margin-right': 10,
                'margin-bottom':
                10,
                'margin-top':
                25,
                # 'viewport-size':'800x600',
                'header-html':
                'http://' + request.META.get('HTTP_HOST') +
                '/static/isdc/head_print/rep_header_vector.html?onpdf=' +
                user_logo['onpdf'] + '&userlogo=' + user_logo['logo_url'] +
                '&name=' + request.user.first_name + ' ' +
                request.user.last_name + '&cust_title=&organization=' +
                (request.user.organization or '') + '&' + headerparam,
                # 'header-html': 'http://'+request.META.get('HTTP_HOST')+'/static/rep_header(v2).html?name='+request.user.first_name+'-'+request.user.last_name+'&cust_title=&organization='+request.user.organization,
                # 'lowquality':'-'
                # 'disable-smart-shrinking':'-',
                # 'print-media-type':'-',
                # 'no-stop-slow-scripts':'-',
                # 'enable-javascript':'-',
                # 'javascript-delay': 30000,
                # 'window-status': 'ready',
            }
            if re.match('^/v2', request.path):
                options['viewport-size'] = '1240x800'
            domainpath = request.META.get('HTTP_HOST') + request.META.get(
                'PATH_INFO')
            url = 'http://' + str(domainpath) + 'print?' + request.META.get(
                'QUERY_STRING') + '&user='******'&' + bodyparam
            pdf = pdfkit.from_url(url, False, options=options)
            date_string = dateformat.format(datetime.date.today(), "Y-m-d")
            response = HttpResponse(pdf, content_type='application/pdf')
            response[
                'Content-Disposition'] = 'attachment; filename="' + request.GET[
                    'page'] + '_' + date_string + '.pdf"'

        return response
Ejemplo n.º 32
0
 def get_time_created_data(self, obj):
     return dateformat.format(obj.date_created, settings.TIME_FORMAT)
Ejemplo n.º 33
0
def dashboard_detail(request):
	v2_folder = ''
	# user_logo = avatar_print_url(request.user,200)
	user_logo = {}

	headerparam_dict = {p: request.GET.get(p, '') for p in ['hideuserinfo','lang'] if p in request.GET}
	headerparam_dict.update({
		'onpdf': user_logo.get('onpdf'),
		'userlogo': user_logo.get('logo_url'),
		'name': request.user.first_name+' '+request.user.last_name,
		'cust_title': '%s %s'%('Dashboard',request.GET.get('page', '').title()),
		'organization': (request.user.organization or ''),
	})
	headerparam = urllib.urlencode(headerparam_dict)

	bodyparam_dict = {}
	if not request.GET.get('lang'):
		bodyparam_dict['lang'] = str(translation.get_language())
	bodyparam = urllib.urlencode(bodyparam_dict)

	# add '?page=baseline' to url if none exist
	if not request.GET.get('page'):
		currenturl = request.build_absolute_uri()
		return redirect(set_query_parameter(currenturl, 'page', 'baseline'))

	if 'pdf' in request.GET:
		try:
			domainpath = 'asdc.immap.org'+request.META.get('PATH_INFO')
			date_string = dateformat.format(datetime.date.today(), "Y-m-d")

			# create an API client instance
			client = pdfcrowd.Client(getattr(settings, 'PDFCROWD_UNAME', ''), getattr(settings, 'PDFCROWD_UPASS', ''))
			client.setPageWidth('8.3in')
			client.setPageHeight('11.7in')
			# client.setPageMargins('1in', '1in', '1in', '1in')
			client.setVerticalMargin("0.75in")
			client.setHorizontalMargin("0.25in")
			client.setHeaderUrl('http://asdc.immap.org/static/isdc/head_print/rep_header_vector.html?onpdf='+user_logo.get('onpdf','')+'&userlogo='+user_logo.get('logo_url','')+'&name='+request.user.first_name+'+'+request.user.last_name+'&cust_title=&organization='+(request.user.organization or '')+'&isodate='+date_string+'&'+headerparam)
			# convert a web page and store the generated PDF to a variable
			pdf = client.convertURI('http://'+str(domainpath)+'print?'+request.META.get('QUERY_STRING')+'&user='******'&'+bodyparam)
			 # set HTTP response headers
			response = HttpResponse(content_type="application/pdf")
			response["Cache-Control"] = "no-cache"
			response["Accept-Ranges"] = "none"
			response["Content-Disposition"] = 'attachment; filename="'+request.GET['page']+'_'+date_string+'.pdf"'

			# send the generated PDF
			response.write(pdf)


		except pdfcrowd.Error, why:
			options = {

				# wkhtmltopdf settings
				# 'quiet': '',
				# 'page-size': 'A4',
				# 'page-width': '2550px',
				# 'page-height': '3300px',
				# 'dpi':300,
				# 'margin-left': 10,
				# 'margin-right': 10,
				# 'margin-bottom':10,
				# 'margin-top':25,
				# 'viewport-size':'800x600',
				# 'header-html': 'http://%s/static/isdc/head_print/rep_header.html?%s'%(request.META.get('HTTP_HOST'),headerparam),
				# 'header-html': 'http://'+request.META.get('HTTP_HOST')+'/static/rep_header(v2).html?name='+request.user.first_name+'-'+request.user.last_name+'&cust_title=&organization='+request.user.organization,
				# 'lowquality':'-'
				# 'disable-smart-shrinking':'-',
				# 'print-media-type':'-',
				# 'no-stop-slow-scripts':'-',

				# 'enable-javascript':'-',
				# 'window-status': 'ready',

				# pychrome settings
				# match screen to print layout and resolution as close as possible
				# in order for the map to scale correctly
				# for print debugging, uncomment ruler.png in custombase.html,
				# resolution in pixel, size in inches, time in seconds
				'screen-width':1024, # resolution when loading the page
				'screen-height':1024, # resolution when loading the page
				'paperWidth':8.27,
				'paperHeight':11.69,
				'marginTop':0.78,
				'marginBottom':0.45,
				'marginLeft':0.3,
				'marginRight':0.3,
				'scale':0.71, # 0.71 roughly equal to 1024 px print width on 1024 screen-width
				'after-document-loaded-delay': 1, # in seconds
				'timeout': 60, # in seconds
				'header-html': 'http://%s/static/epr_bgd/head_print/rep_header_chrome.html?%s'%(request.META.get('HTTP_HOST'),headerparam),
				'headerparam':headerparam_dict,
			}
			# if re.match('^/v2', request.path):
			# 	options['viewport-size'] = '1240x800'
			domainpath = request.META.get('HTTP_HOST')+request.META.get('PATH_INFO')
			url = 'http://'+str(domainpath)+'print?'+request.META.get('QUERY_STRING')+'&user='******'&'+bodyparam
			# pdf = pdfkit.from_url(url, False, options=options)
			pdf = print_from_urls([url], print_option=options)
			date_string = dateformat.format(datetime.date.today(), "Y-m-d")
			response = HttpResponse(pdf,content_type='application/pdf')
			response['Content-Disposition'] = 'attachment; filename="'+request.GET['page']+'_'+date_string+'.pdf"'

		return response
Ejemplo n.º 34
0
 def get_date_end_data(self, obj):
     if obj.date_end:
         return dateformat.format(obj.date_end, settings.SHORT_DATE_FORMAT)
     return None
Ejemplo n.º 35
0
def aboutDefaultContext(request):
    context = getGlobalContext(request)
    context['about_description_template'] = 'include/about_description'
    context['about_photo'] = ABOUT_PHOTO
    context['site_long_description'] = SITE_LONG_DESCRIPTION
    context['feedback_form'] = FEEDBACK_FORM
    context['contact_methods'] = [
        ('Discord', 'discord', CONTACT_DISCORD),
        ('Twitter', 'twitter',
         u'https://twitter.com/{}/'.format(TWITTER_HANDLE)
         if TWITTER_HANDLE else None),
        ('Reddit', 'reddit',
         u'https://www.reddit.com/user/{}/'.format(CONTACT_REDDIT)
         if CONTACT_REDDIT else None),
        ('Facebook', 'facebook',
         u'https://facebook.com/{}/'.format(CONTACT_FACEBOOK)
         if CONTACT_FACEBOOK else None),
        (_('Email'), 'flaticon-contact',
         CONTACT_EMAIL if CONTACT_EMAIL else None),
        ('GitHub', 'github', u'https://github.com/{}/{}/'.format(
            GITHUB_REPOSITORY[0], GITHUB_REPOSITORY[1])
         if GITHUB_REPOSITORY else None),
        ('Bug tracker', 'flaticon-album',
         BUG_TRACKER_URL if BUG_TRACKER_URL and not FEEDBACK_FORM else None),
    ]
    context['franchise'] = _(
        '{site} is not a representative and is not associated with {game}. Its logos and images are Trademarks of {company}.'
    ).format(site=_(SITE_NAME),
             game=_(GAME_NAME),
             company=_('the company that owns {game}').format(game=GAME_NAME))
    context['staff'] = models.User.objects.filter(
        is_staff=True).select_related(
            'preferences', 'staff_details').prefetch_related(
                Prefetch(
                    'links',
                    queryset=models.UserLink.objects.order_by('-i_relevance'),
                    to_attr='all_links'),
            ).extra(
                select={
                    'length_of_groups':
                    'Length(c_groups)',
                    'is_manager':
                    'CASE WHEN c_groups LIKE "%%manager%%" THEN 1 ELSE 0 END',
                }).order_by('-is_manager', '-length_of_groups')

    try:
        my_timezone = request.user.staff_details.timezone if request.user.is_staff else None
    except ObjectDoesNotExist:
        my_timezone = None
    for staff_member in context['staff']:
        # Add staff member location URL
        if staff_member.preferences.location:
            latlong = '{},{}'.format(
                staff_member.preferences.latitude, staff_member.preferences.
                longitude) if staff_member.preferences.latitude else None
            staff_member.location_url = u'/map/?center={}&zoom=10'.format(
                latlong
            ) if 'map' in context[
                'all_enabled'] and latlong else u'https://www.google.com/maps?q={}'.format(
                    staff_member.preferences.location)

        # Add staff member birthday URL and formatting
        if staff_member.preferences.birthdate:
            staff_member.formatted_birthday = dateformat.format(
                staff_member.preferences.birthdate, "F d")
            today = datetime.date.today()
            birthday = staff_member.preferences.birthdate.replace(
                year=today.year)
            if birthday < today:
                birthday = birthday.replace(year=today.year + 1)
            staff_member.birthday_url = 'https://www.timeanddate.com/countdown/birthday?iso={date}T00&msg={username}%27s+birthday'.format(
                date=dateformat.format(birthday, "Ymd"),
                username=staff_member.username)

        # Availability calendar
        try:
            staff_member.has_staff_details = bool(
                staff_member.staff_details.id
            ) if staff_member.is_staff else None
        except models.StaffDetails.DoesNotExist:
            staff_member.has_staff_details = False
            staff_member.staff_details = models.StaffDetails()
        if request.user.is_staff and staff_member.has_staff_details and (
                staff_member.staff_details.d_availability
                or staff_member.staff_details.d_weekend_availability):
            staff_member.show_calendar = True
            if my_timezone and staff_member.staff_details.timezone:
                staff_member.availability_calendar = staff_member.staff_details.availability_calendar_timezone(
                    my_timezone)
                staff_member.calendar_with_timezone = True
            else:
                staff_member.availability_calendar = staff_member.staff_details.availability_calendar
                staff_member.calendar_with_timezone = False

        # Stats
        staff_member.stats = {}
        for group, details in staff_member.preferences.groups_and_details.items(
        ):
            stats = details.get('stats', [])
            staff_member.stats[group] = []
            if stats:
                for stat in stats:
                    model = getattr(models, stat['model'])
                    total = model.objects.filter(
                        **{
                            stat.get('selector_to_owner',
                                     model.selector_to_owner()):
                            staff_member
                        }).filter(**(stat.get('filters', {}))).count()
                    if total:
                        staff_member.stats[group].append(
                            mark_safe(
                                unicode(stat['template']).format(
                                    total=u'<strong>{}</strong>'.format(
                                        total))))

    context['now'] = timezone.now()
    context['api_enabled'] = False
    context['contribute_url'] = CONTRIBUTE_URL
    context['other_sites'] = [s for s in other_sites if s['name'] != SITE_NAME]
    context['other_sites_colsize'] = int(
        math.ceil(12 / (len(context['other_sites']))))
    context['ajax'] = context['current_url'].startswith('/ajax/')
    context['extends'] = 'base.html' if not context['ajax'] else 'ajax.html'
    return context
Ejemplo n.º 36
0
 def get_date_created_data(self, obj):
     return dateformat.format(obj.date_created, settings.SHORT_DATE_FORMAT)
Ejemplo n.º 37
0
 def translated_name(self):
     if self.donation_month_id:
         return _(u'{month} Donator').format(
             month=dateformat.format(self.date, "F Y"))
     return self.name
Ejemplo n.º 38
0
def Dashboard(request):
    bodyparam_dict = {}
    bodyparam = urlencode(bodyparam_dict)

    headerparam_dict = {
        p: request.GET.get(p, '')
        for p in ['hideuserinfo', 'lang'] if p in request.GET
    }
    headerparam_dict.update({
        # 'onpdf': user_logo.get('onpdf'),
        # 'userlogo': user_logo.get('logo_url'),
        # 'name': request.user.first_name+' '+request.user.last_name,
        # 'cust_title': '%s %s'%('Dashboard',request.GET.get('page', '').title()),
        # 'organization': (request.user.organization or ''),
    })
    headerparam = urllib.parse.urlencode(headerparam_dict)

    currenturl = request.build_absolute_uri()
    if not request.GET.get('page'):
        return redirect(replace_query_param(currenturl, 'page', 'dashboard'))

    # if no source_type in url then redirect with added source_type=DEFAULT_SOURCE_ID
    if not request.GET.get('source_type'):
        # DEFAULT_SOURCE_NAME = 'master'
        # return redirect(replace_query_param(currenturl, 'source_type', DEFAULT_SOURCE_NAME))
        master_id = IncidentSource.objects.before_min_id()
        return redirect(
            replace_query_param(currenturl, 'source_type', master_id))
        # source_row = IncidentSource.objects.filter(name=DEFAULT_SOURCE_NAME).first() or IncidentSource.objects.first()
        # if source_row:
        #     return redirect(replace_query_param(currenturl, 'source_type', source_row.id))

    if 'pdf' in request.GET:
        options = {
            # pychrome settings
            # match screen to print layout and resolution as close as possible
            # in order for the map to scale correctly
            # for print debugging, uncomment ruler.png in custombase.html,
            # resolution in pixel, size in inches, time in seconds
            'screen-width': 1024,  # resolution when loading the page
            'screen-height': 1024,  # resolution when loading the page
            'paperWidth': 8.27,
            'paperHeight': 11.69,
            # 'marginTop': 0.78,
            'marginTop': 0.90,
            'marginBottom': 0.45,
            'marginLeft': 0.3,
            'marginRight': 0.3,
            'scale':
            0.71,  # 0.71 roughly equal to 1024 px print width on 1024 screen-width
            'after-document-loaded-delay': 1,  # in seconds
            'timeout': 60,  # in seconds
            # 'header-html': 'http://%s/static/epr_bgd/head_print/rep_header_chrome.html?%s'%(request.META.get('HTTP_HOST'),headerparam),
            'header-html': 'http://' + request.META.get('HTTP_HOST') +
            '/static/print/header_chrome.html',
            'headerparam': headerparam_dict,
        }
        # if re.match('^/v2', request.path):
        # 	options['viewport-size'] = '1240x800'
        domainpath = request.META.get('HTTP_HOST') + request.META.get(
            'PATH_INFO')
        url = 'http://' + str(domainpath) + 'print?' + request.META.get(
            'QUERY_STRING') + '&user='******'&' + bodyparam
        print('print url', url)
        # pdf = pdfkit.from_url(url, False, options=options)
        pdf = print_from_urls([url], print_option=options)
        date_string = dateformat.format(datetime.now(), "Y-m-d")
        response = HttpResponse(pdf, content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename="' + \
            request.GET['page']+'_'+date_string+'.pdf"'
        return response

    elif 'csv' in request.GET:
        date_string = dateformat.format(datetime.now(), "Y-m-d")
        rows = csv_response(request)
        pseudo_buffer = Echo()
        writer = csv.writer(pseudo_buffer)
        response = HttpResponse((writer.writerow(row) for row in rows),
                                content_type='text/csv')
        name_parts = [
            (str(request.GET.get('page')) or '').title(),
            IncidentSource.objects.get_name(request.GET.get('source_type')),
            date_string
        ]
        filename = '_'.join(list(filter(None, name_parts))) + '.csv'
        response['Content-Disposition'] = 'attachment; filename="%s"' % (
            filename)
        return response

    else:
        response = Common(request)
        template = "dashboard/dashboard_content.html"
        return render(request, template, response)
Ejemplo n.º 39
0
def dashboard_detail(request):
	v2_folder = ''
	user_logo = avatar_print_url(request.user,200)

	headerparam_dict = {p: request.GET.get(p, '') for p in ['hideuserinfo','lang'] if p in request.GET}
	headerparam = urllib.urlencode(headerparam_dict)

	bodyparam_dict = {}
	if not request.GET.get('lang'):
		bodyparam_dict['lang'] = str(translation.get_language())
	bodyparam = urllib.urlencode(bodyparam_dict)

	def set_query_parameter(url, param_name, param_value):
	    """Given a URL, set or replace a query parameter and return the
	    modified URL.

	    >>> set_query_parameter('http://example.com?foo=bar&biz=baz', 'foo', 'stuff')
	    'http://example.com?foo=stuff&biz=baz'

	    """
	    scheme, netloc, path, query_string, fragment = urlsplit(url)
	    query_params = parse_qs(query_string)

	    query_params[param_name] = [param_value]
	    new_query_string = urllib.urlencode(query_params, doseq=True)

	    return urlunsplit((scheme, netloc, path, new_query_string, fragment))

	# add '?page=baseline' to url if none exist
	if not request.GET.get('page'):
	    currenturl = request.build_absolute_uri()
	    return redirect(set_query_parameter(currenturl, 'page', 'baseline'))

	if 'pdf' in request.GET:
		try:
			domainpath = 'asdc.immap.org'+request.META.get('PATH_INFO')
			date_string = dateformat.format(date.today(), "Y-m-d")

			# create an API client instance
			client = pdfcrowd.Client(getattr(settings, 'PDFCROWD_UNAME'), getattr(settings, 'PDFCROWD_UPASS'))
			client.setPageWidth('8.3in')
			client.setPageHeight('11.7in')
			# client.setViewport('2480px', '3508px')
			# client.setPageMargins('1in', '1in', '1in', '1in')
			client.setVerticalMargin("0.75in")
			client.setHorizontalMargin("0.25in")
			client.setHeaderUrl('http://asdc.immap.org/static/'+v2_folder+'rep_header_vector.html?onpdf='+user_logo['onpdf']+'&userlogo='+user_logo['logo_url']+'&name='+request.user.first_name+' '+request.user.last_name+'&cust_title=&organization='+request.user.organization+'&isodate='+date_string+'&'+headerparam)
			# convert a web page and store the generated PDF to a variable
			pdf = client.convertURI('http://'+str(domainpath)+'print?'+request.META.get('QUERY_STRING')+'&user='******'&'+bodyparam)
			 # set HTTP response headers
			response = HttpResponse(mimetype="application/pdf")
			response["Cache-Control"] = "no-cache"
			response["Accept-Ranges"] = "none"
			response["Content-Disposition"] = 'attachment; filename="'+request.GET['page']+'_'+date_string+'.pdf"'

			# send the generated PDF
			response.write(pdf)


		except pdfcrowd.Error, why:
			options = {
			    'quiet': '',
			    'page-size': 'A4',
				'page-width': '2480px',
				'page-height': '3508px',
				'dpi':300,
			    # 'margin-left': 10,
			    # 'margin-right': 10,
			    'margin-bottom':10,
			    'margin-top':30,
			    # 'viewport-size':'800x600',
			    'header-html': 'http://'+request.META.get('HTTP_HOST')+'/static/'+v2_folder+'rep_header.html?onpdf='+user_logo['onpdf']+'&userlogo='+user_logo['logo_url']+'&name='+request.user.first_name+' '+request.user.last_name+'&cust_title=&organization='+request.user.organization+'&'+headerparam,
			    # 'header-html': 'http://'+request.META.get('HTTP_HOST')+'/static/rep_header(v2).html?name='+request.user.first_name+'-'+request.user.last_name+'&cust_title=&organization='+request.user.organization,
			    # 'lowquality':'-'
			    # 'disable-smart-shrinking':'-',
			    # 'print-media-type':'-',
			    # 'no-stop-slow-scripts':'-',
			    # 'enable-javascript':'-',
			    # 'javascript-delay': 30000,
			    # 'window-status': 'ready',
			}
			if re.match('^/v2', request.path):
			    options['viewport-size'] = '1240x800'
			domainpath = request.META.get('HTTP_HOST')+request.META.get('PATH_INFO')
			url = 'http://'+str(domainpath)+'print?'+request.META.get('QUERY_STRING')+'&user='******'&'+bodyparam
			pdf = pdfkit.from_url(url, False, options=options)
			date_string = dateformat.format(date.today(), "Y-m-d")
			response = HttpResponse(pdf,content_type='application/pdf')
			response['Content-Disposition'] = 'attachment; filename="'+request.GET['page']+'_'+date_string+'.pdf"'

		return response
Ejemplo n.º 40
0
def dashboard_multiple(request):
    user_logo = avatar_print_url(request.user, 200)
    urls = []
    # data = request.POST
    data = json.loads(request.body)
    domainpath = request.META.get('HTTP_HOST')
    domainpath += '/v2' if re.match('^/v2', request.path) else ''
    v2_folder = ''

    headerparam_dict = {
        p: request.GET.get(p, '')
        for p in ['hideuserinfo', 'lang'] if p in request.GET
    }
    headerparam = urllib.urlencode(headerparam_dict)

    bodyparam_dict = {}
    bodyparam_dict['lang'] = request.GET.get('lang') or str(
        translation.get_language())
    bodyparam = urllib.urlencode(bodyparam_dict)

    try:
        print request.META.get('HTTP_HOST'), request.META.get('PATH_INFO')
        date_string = dateformat.format(datetime.date.today(), "Y-m-d")

        # create an API client instance
        client = pdfcrowd.Client(getattr(settings, 'PDFCROWD_UNAME'),
                                 getattr(settings, 'PDFCROWD_UPASS'))
        client.setPageWidth('8.3in')
        client.setPageHeight('11.7in')
        # client.setPageMargins('1in', '1in', '1in', '1in')
        client.setVerticalMargin("0.75in")
        client.setHorizontalMargin("0.25in")
        client.setHeaderUrl('http://' + request.META.get('HTTP_HOST') +
                            '/static/' + v2_folder +
                            'rep_header_vector.html?onpdf=' +
                            user_logo['onpdf'] + '&userlogo=' +
                            user_logo['logo_url'] + '&name=' +
                            request.user.first_name + ' ' +
                            request.user.last_name + '&cust_title=' +
                            quote(data['mapTitle'].encode('utf-8')) +
                            '&organization=' + request.user.organization +
                            '&isodate=' + date_string + '&' + headerparam)
        # convert a web page and store the generated PDF to a variable

        # get map pdf
        req = urllib2.Request(data['mapUrl'])
        req.add_unredirected_header(
            'User-Agent',
            'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.107 Safari/537.36'
        )
        fh = urllib2.urlopen(req)
        f = fh.read()

        merger = PdfFileMerger()

        merger.append(StringIO(f))

        for i in data['urls']:
            if i is not None and i != '':
                # urls.append(str('http://'+domainpath+'/dashboard/print'+i+'&user='******'http://' + domainpath + '/dashboard/print' + i +
                        '&user='******'&' + bodyparam))
                merger.append(StringIO(pdf))

        # set HTTP response headers
        # response = HttpResponse(content_type="application/pdf")
        # response["Cache-Control"] = "no-cache"
        # response["Accept-Ranges"] = "none"
        # response["Content-Disposition"] = 'attachment; filename="'+data['fileName']+'.pdf"'

        # send the generated PDF
        # merger.write(response)
        # return response
        merger.write(
            getattr(settings, 'PRINT_CACHE_PATH') +
            data['mapUrl'].split('/')[-1])
        return HttpResponse(json.dumps(
            {'filename': data['mapUrl'].split('/')[-1]}),
                            content_type='application/json')

    except pdfcrowd.Error, why:
        options = {
            'quiet':
            '',
            'page-size':
            'A4',
            'page-width':
            '2550px',
            'page-height':
            '3300px',
            'dpi':
            300,
            # 'margin-left': 10,
            # 'margin-right': 10,
            'margin-bottom':
            10,
            'margin-top':
            25,
            # 'viewport-size':'800x600',
            'header-html':
            'http://' + request.META.get('HTTP_HOST') + '/static/' +
            v2_folder + 'rep_header.html?onpdf=' + user_logo['onpdf'] +
            '&userlogo=' + user_logo['logo_url'] + '&name=' +
            request.user.first_name + ' ' + request.user.last_name +
            '&cust_title=' + quote(data['mapTitle'].encode('utf-8')) +
            '&organization=' + request.user.organization + '&' + headerparam,
            # 'lowquality':'-',
            # 'disable-smart-shrinking':'-',
            # 'print-media-type':'-',
            # 'no-stop-slow-scripts':'-',
            # 'enable-javascript':'-',
            'javascript-delay':
            25000,
            # 'window-status': 'ready',
            'encoding':
            "UTF-8",
        }

        # f = urllib.request.urlopen(data['mapUrl']).read()
        req = urllib2.Request(data['mapUrl'])
        req.add_unredirected_header(
            'User-Agent',
            'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.107 Safari/537.36'
        )
        fh = urllib2.urlopen(req)
        f = fh.read()

        merger = PdfFileMerger()
        merger.append(StringIO(f))

        for i in data['urls']:
            if i is not None and i != '':
                urls.append(
                    str('http://' + domainpath + '/dashboard/print' + i +
                        '&user='******'&' + bodyparam))

        pdf = pdfkit.from_url(urls, False, options=options)
        merger.append(StringIO(pdf))

        # resp = HttpResponse(pdf,content_type='application/pdf')
        # resp = HttpResponse(content_type="application/pdf")
        # resp["Cache-Control"] = "no-cache"
        # resp["Accept-Ranges"] = "none"
        # resp['Content-Disposition'] = 'attachment; filename="'+data['fileName']+'.pdf"'

        merger.write(
            getattr(settings, 'PRINT_CACHE_PATH') +
            data['mapUrl'].split('/')[-1])
        return HttpResponse(json.dumps(
            {'filename': data['mapUrl'].split('/')[-1]}),
                            content_type='application/json')
Ejemplo n.º 41
0
def dashboard_multiple(request):
	user_logo = avatar_print_url(request.user,200)
	urls = []
	# data = request.POST
	data = json.loads(request.body)
	domainpath = request.META.get('HTTP_HOST')
	domainpath += '/v2' if re.match('^/v2', request.path) else ''
	v2_folder = ''

	headerparam_dict = {p: request.GET.get(p, '') for p in ['hideuserinfo','lang'] if p in request.GET}
	headerparam = urllib.urlencode(headerparam_dict)

	bodyparam_dict = {}
	bodyparam_dict['lang'] = request.GET.get('lang') or str(translation.get_language())
	bodyparam = urllib.urlencode(bodyparam_dict)

	try:
		print request.META.get('HTTP_HOST'), request.META.get('PATH_INFO')
		date_string = dateformat.format(datetime.now(), "Y-m-d")

		# create an API client instance
		client = pdfcrowd.Client(getattr(settings, 'PDFCROWD_UNAME'), getattr(settings, 'PDFCROWD_UPASS'))
		client.setPageWidth('8.3in')
		client.setPageHeight('11.7in')
		# client.setPageMargins('1in', '1in', '1in', '1in')
		client.setVerticalMargin("0.75in")
		client.setHorizontalMargin("0.25in")
		client.setHeaderUrl('http://'+request.META.get('HTTP_HOST')+'/static/'+v2_folder+'rep_header_vector.html?onpdf='+user_logo['onpdf']+'&userlogo='+user_logo['logo_url']+'&name='+request.user.first_name+' '+request.user.last_name+'&cust_title='+quote(data['mapTitle'].encode('utf-8'))+'&organization='+request.user.organization+'&isodate='+date_string+'&'+headerparam)
		# convert a web page and store the generated PDF to a variable

		# get map pdf
		req = urllib2.Request(data['mapUrl'])
		req.add_unredirected_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.107 Safari/537.36')
		fh = urllib2.urlopen(req)
		f = fh.read()

		merger = PdfFileMerger()

		merger.append(StringIO(f))

		for i in data['urls']:
			if i is not None and i != '':
				# urls.append(str('http://'+domainpath+'/dashboard/print'+i+'&user='******'http://'+domainpath+'/dashboard/print'+i+'&user='******'&'+bodyparam))
				merger.append(StringIO(pdf))

		 # set HTTP response headers
		# response = HttpResponse(mimetype="application/pdf")
		# response["Cache-Control"] = "no-cache"
		# response["Accept-Ranges"] = "none"
		# response["Content-Disposition"] = 'attachment; filename="'+data['fileName']+'.pdf"'

		# send the generated PDF
		# merger.write(response)
		# return response
		merger.write(getattr(settings, 'PRINT_CACHE_PATH')+data['mapUrl'].split('/')[-1])
		return HttpResponse(json.dumps({'filename':data['mapUrl'].split('/')[-1]}), mimetype='application/json')

	except pdfcrowd.Error, why:
		options = {
		    'quiet': '',
		    'page-size': 'A4',
			'page-width': '2550px',
			'page-height': '3300px',
			'dpi':300,
		    # 'margin-left': 10,
		    # 'margin-right': 10,
		    'margin-bottom':10,
		    'margin-top':30,
		    # 'viewport-size':'800x600',
		    'header-html': 'http://'+request.META.get('HTTP_HOST')+'/static/'+v2_folder+'rep_header.html?onpdf='+user_logo['onpdf']+'&userlogo='+user_logo['logo_url']+'&name='+request.user.first_name+' '+request.user.last_name+'&cust_title='+quote(data['mapTitle'].encode('utf-8'))+'&organization='+request.user.organization+'&'+headerparam,
			# 'lowquality':'-',
		    # 'disable-smart-shrinking':'-',
		    # 'print-media-type':'-',
		    # 'no-stop-slow-scripts':'-',
		    # 'enable-javascript':'-',
		    'javascript-delay': 25000,
		    # 'window-status': 'ready',
		    'encoding': "UTF-8",
		}

		# f = urllib.request.urlopen(data['mapUrl']).read()
		req = urllib2.Request(data['mapUrl'])
		req.add_unredirected_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.107 Safari/537.36')
		fh = urllib2.urlopen(req)
		f = fh.read()

		merger = PdfFileMerger()
		merger.append(StringIO(f))

		for i in data['urls']:
			if i is not None and i != '':
				urls.append(str('http://'+domainpath+'/dashboard/print'+i+'&user='******'&'+bodyparam))

		pdf = pdfkit.from_url(urls, False, options=options)
		merger.append(StringIO(pdf))


		# resp = HttpResponse(pdf,content_type='application/pdf')
		# resp = HttpResponse(mimetype="application/pdf")
		# resp["Cache-Control"] = "no-cache"
		# resp["Accept-Ranges"] = "none"
		# resp['Content-Disposition'] = 'attachment; filename="'+data['fileName']+'.pdf"'

		merger.write(getattr(settings, 'PRINT_CACHE_PATH')+data['mapUrl'].split('/')[-1])
		return HttpResponse(json.dumps({'filename':data['mapUrl'].split('/')[-1]}), mimetype='application/json')
Ejemplo n.º 42
0
 def get_date_open_data(self, obj):
     return dateformat.format(obj.date_open, settings.SHORT_DATE_FORMAT)
Ejemplo n.º 43
0
 def get_time_start_data(self, obj):
     if obj.time_start:
         return dateformat.format(obj.time_start, settings.TIME_FORMAT)
     return None