Exemplo n.º 1
0
class View(View):
    logs = ['self.__init__']
    started = round(time.time())
    show_log = True
    space_name = Config('BASICS.NAME').value
    admin_url = Secret('DJANGO.ADMIN_URL').value
    path = ''

    def log(self, text):
        import os
        self.logs.append(text)
        if self.show_log == True:
            Log().print('{}'.format(text), os.path.basename(__file__),
                        self.started)
Exemplo n.º 2
0
    def import_from_discourse(self,
                              DISCOURSE_URL=Secret(
                                  'DISCOURSE.DISCOURSE_URL').value):
        from _apis.models import Discourse
        import time
        import requests
        from _setup.models import Log

        if DISCOURSE_URL:
            Log().show_message(
                '✅ Found DISCOURSE.DISCOURSE_URL - start importing persons from Discourse.'
            )
            time.sleep(2)

            if requests.get(DISCOURSE_URL).status_code == 200:
                users = Discourse(url=DISCOURSE_URL).get_users()
                Log().print('--> process {} users'.format(len(users)))
                for user in users:
                    Person().create(
                        json_content={
                            'str_name_en_US':
                            user['user']['name'] if user['user']['name']
                            and user['user']['name'] != '' else user['user']
                            ['username'],
                            'url_featured_photo':
                            DISCOURSE_URL + user['user']
                            ['avatar_template'].replace('{size}', '240'),
                            'url_discourse':
                            DISCOURSE_URL + 'u/' + user['user']['username'],
                            'text_description_en_US':
                            user['user']['title']
                            if user['user']['title'] != '' else None
                        })
            else:
                Log().show_message(
                    'WARNING: I can\'t access your Discourse page. Is the URL correct? Will skip Discourse for now.'
                )
                time.sleep(4)
        else:
            Log().show_message(
                'WARNING: Can\'t find the DISCOURSE.DISCOURSE_URL in your secrets.json. Will skip Discourse for now.'
            )
            time.sleep(4)
Exemplo n.º 3
0
    def setup_config(self):
        from _setup.models.setup_functions.new_functions.languages import SetupLanguages
        from _setup.models.setup_functions.new_functions.riseuppad import SetupNewRiseupPad
        from _setup.models.setup_functions.new_functions.location import SetupNewLocation
        from _setup.models.setup_functions.new_functions.latlon_timezone import SetupNewLatLonTimezone
        from _setup.models.setup_functions.new_functions.event_footer import SetupNewEventFooter

        later_then_config = 'Guess later then... Open your config.json at any time to make changes.'

        self.config = Secret().set_secret(
            SetupTestConfig('BASICS.NAME').value if self.test else 'input',
            self.config, later_then_config,
            'First: What is the name of your hackspace?', 'BASICS', 'NAME')
        self.config = SetupLanguages(self.config, self.test).config
        self.config = SetupNewRiseupPad(self.config).config
        self.config = SetupNewLocation(self.config, later_then_config,
                                       self.test).config
        self.config = SetupNewLatLonTimezone(self.config).config

        self.config = Secret().set_secret(
            SetupTestConfig('SOCIAL.HASHTAG').value if self.test else 'input',
            self.config, later_then_config,
            'What #hashtag do people use when they talk online about your hackspace on Twitter or Instagram? (Example: #noisebridge)',
            'SOCIAL', 'HASHTAG')
        self.config = Secret().set_secret(
            SetupTestConfig('BASICS.DONATION_URLs.MONEY').value
            if self.test else 'input', self.config, later_then_config,
            'Do you have a donation page, where people can donate money online? If yes, please enter the url. (or press Enter to skip)',
            'BASICS', 'DONATION_URLs', 'MONEY')
        self.config = Secret().set_secret(
            None if self.test else 'input', self.config, later_then_config,
            'Did you clone the HackspaceOS template and want people to make changes to your clone? Then enter the GIT URL now (for example from Github).',
            'WEBSITE', 'WEBSITE_GIT')
        self.config = Secret().set_secret(
            SetupTestConfig('WEBSITE.DOMAIN').value, self.config,
            later_then_config,
            'What domain will you use for your new hackspace website? (Just the domain. Example: "noisebridge.net")',
            'WEBSITE', 'DOMAIN')

        self.config = SetupNewEventFooter(self.config).config

        self.config = Secret().set_secret(
            SetupTestConfig('CSS.PRIMARY_COLOR').value, self.config,
            later_then_config,
            'And the last question: What should be your website\'s primary color (for buttons for example). Recommended: a color in your hackspace logo?',
            'CSS', 'PRIMARY_COLOR')

        with open('_setup/config.json', 'w') as outfile:
            json.dump(self.config, outfile, indent=4)
Exemplo n.º 4
0
    def import_from_discourse(self,
                              url=Secret('DISCOURSE.DISCOURSE_URL').value):
        Log().print('Event.objects.import_from_discourse(self)')
        from _apis.models import Discourse
        from dateutil.parser import parse
        from datetime import datetime
        from django.db.models import Q
        from _database.models import Event

        events = Discourse(url=url).get_category_posts('events', True)
        now = datetime.now()
        for event in events:
            if 'event' in event:
                date_start = parse(event['event']['start'])
                if date_start.year >= now.year and date_start.month >= now.month and date_start.day >= now.day:
                    if Event.objects.filter(
                            Q(str_name_en_US=event['title'])
                            | Q(str_name_he_IL=event['title'])).exists(
                            ) == False:
                        event['description'] = Discourse(
                            url=url).get_post_details(event['slug'])['cooked']
                        self.createEvent(event)
Exemplo n.º 5
0
    def __init__(self, email, password, client_id, client_secret,
                 redirect_uri):
        self.logs = ['self.__init__']
        self.started = round(time.time())
        self.email = email
        self.password = password
        self.client_id = client_id
        self.client_secret = client_secret,
        self.redirect_uri = redirect_uri

        # check if still usable token is saved in secrets.json - else get new one
        if Secret('MEETUP.ACCESS_TOKEN').value and Secret(
                'MEETUP.ACCESS_TOKEN_VALID_UPTO').value > time.time() + 60:
            self.value = Secret('MEETUP.ACCESS_TOKEN').value

        # check if required fields exist
        if not self.client_id or not self.client_secret or not self.redirect_uri or not self.email or not self.password:
            self.log('-> ERROR: Meetup secrets incomplete!')
            self.value = None

        else:
            # else: following steps to get an API token - see https://www.meetup.com/meetup_api/auth/

            # Step 1: Get code to get access token, by loggin into meetup account
            login_page = Scraper(
                'https://secure.meetup.com/oauth2/authorize?scope=basic+event_management&client_id={}&response_type=code&redirect_uri={}'
                .format(self.client_id, self.redirect_uri),
                scraper_type='selenium',
                auto_close_selenium=False)
            login_page.selenium.find_element(By.LINK_TEXT, 'Continue').click()
            login_page.selenium.find_element_by_id('email').send_keys(
                self.email)
            login_page.selenium.find_element_by_id('password').send_keys(
                self.password)
            login_page.selenium.find_element_by_id('loginFormSubmit').click()
            time.sleep(10)
            code = login_page.selenium.current_url.split('code=')[1]
            login_page.selenium.close()

            # Step 2: get access token
            self.response_json = requests.post(
                'https://secure.meetup.com/oauth2/access',
                params={
                    'client_id': self.client_id,
                    'client_secret': self.client_secret,
                    'code': code,
                    'response_type': 'code',
                    'grant_type': 'authorization_code',
                    'redirect_uri': self.redirect_uri,
                    'scope': ['basic', 'event_management']
                }).json()

            if 'access_token' in self.response_json:
                with open('_setup/secrets.json') as json_file:
                    secrets = json.load(json_file)
                secrets['MEETUP']['ACCESS_TOKEN'] = self.response_json[
                    'access_token']
                secrets['MEETUP']['ACCESS_TOKEN_VALID_UPTO'] = round(
                    time.time() + self.response_json['expires_in'])
                with open('_setup/secrets.json', 'w') as outfile:
                    json.dump(secrets, outfile, indent=4)
                self.value = self.response_json['access_token']
            else:
                self.log('-> ERROR: Failed to get Access Token - {}'.format(
                    self.response_json))
                self.value = None
Exemplo n.º 6
0
from django.contrib import admin
from django.urls import path
from django.views.generic.base import RedirectView

from _apis.urls import urlpatterns as api_urls
from _setup.models import Secret, Startup
from _website import views

startup = Startup()
startup.check_code_update()
startup.check_config_uptodate('config')
startup.check_config_uptodate('secrets')
startup.check_mode_testing()

urlpatterns = [
    path(Secret('DJANGO.ADMIN_URL').value + '/', admin.site.urls),
    path('', views.LandingpageView.as_view(), name='landingpage'),
    path('values', views.ValuesView.as_view(), name='values'),
    path('values/',
         RedirectView.as_view(url='values', permanent=False),
         name='values/'),
    path('ourvalues',
         RedirectView.as_view(url='values', permanent=False),
         name='ourvalues/'),
    path('ourvalues/',
         RedirectView.as_view(url='values', permanent=False),
         name='ourvalues'),
    path('meetings', views.MeetingsView.as_view(path='all'), name='meetings'),
    path('meeting',
         RedirectView.as_view(url='meetings', permanent=False),
         name='meeting'),
Exemplo n.º 7
0
 def config(self):
     return Secret('TELEGRAM').value
Exemplo n.º 8
0
    def __init__(self, request=None):
        from _apis.models import Notify
        from _database.models import Helper, Event, Space, Guilde, Person
        from _setup.models import Config
        from _setup.models import Secret
        from django.http import JsonResponse

        DOMAIN = Config('WEBSITE.DOMAIN').value

        int_UNIXtime_event_start = Helper().INT__UNIX_from_date_and_time_STR(
            request.POST.get('date', None), request.POST.get('time', None))
        int_minutes_duration = Helper().INT__duration_minutes(
            request.POST.get('duration', None))

        try:
            if request.FILES[
                    'images[0]'].content_type == 'image/jpeg' or request.FILES[
                        'images[0]'].content_type == 'image/png':
                image = request.FILES['images[0]']
            else:
                image = None
        except:
            image = None

        uploaded_photo_url = request.POST.get('photo', None)

        new_event = Event(
            boolean_approved=request.user.is_authenticated,
            str_name_en_US=request.POST.get('name_english', None),
            str_name_he_IL=request.POST.get('name_hebrew', None),
            int_UNIXtime_event_start=int_UNIXtime_event_start,
            int_minutes_duration=int_minutes_duration,
            int_UNIXtime_event_end=int_UNIXtime_event_start +
            (60 * int_minutes_duration),
            url_featured_photo=uploaded_photo_url
            if 'https' in uploaded_photo_url else None,
            image_featured_photo=image,
            text_description_en_US=request.POST.get('description_english',
                                                    None),
            text_description_he_IL=request.POST.get('description_hebrew',
                                                    None),
            one_space=Space.objects.QUERYSET__by_name(
                request.POST.get('space', None)),
            one_guilde=Guilde.objects.QUERYSET__by_name(
                request.POST.get('guilde', None)),
            str_crowd_size=request.POST.get('expected_crowd', None),
            str_welcomer=request.POST.get('event_welcomer', None),
            boolean_looking_for_volunteers=True if request.POST.get(
                'volunteers', None) == 'yes' else False)
        if request.POST.get('location', None):
            if request.POST.get('location',
                                None) != Config('BASICS.NAME').value:
                if request.POST.get('location', None).lower() == 'online':
                    new_event.boolean_online_meetup = True
                else:
                    new_event.str_location = request.POST.get('location', None)

        if request.POST.get('repeating', None):
            # if repeating, mark as such and auto generate new upcoming events with "update_database" command
            str_repeating_how_often = request.POST.get('repeating', None)
            str_repeating_up_to = request.POST.get('repeating_up_to', None)

            if str_repeating_how_often and str_repeating_how_often != '':
                new_event.int_series_startUNIX = new_event.int_UNIXtime_event_start
                new_event.str_series_repeat_how_often = str_repeating_how_often

            if str_repeating_up_to and str_repeating_up_to != '':
                new_event.int_series_endUNIX = Helper(
                ).INT__UNIX_from_date_and_time_STR(
                    str_repeating_up_to, request.POST.get('time', None))

        new_event.save()

        hosts = request.POST.get('hosts', None)
        if hosts:
            if hosts.startswith(','):
                hosts = hosts[1:]
            hosts = hosts.split(',')
            for host in hosts:
                new_event.many_hosts.add(Person.objects.by_url_discourse(host))

        # if loggedin user: share event to other platforms (Meetup, Discourse, etc.)
        if request.user.is_authenticated:
            new_event.create_discourse_event()
            new_event.create_meetup_event()

        # else (if event created via live website) inform via slack about new event and give community chance to delete it or confirm it
        elif 'HTTP_HOST' in request.META and request.META[
                'HTTP_HOST'] == DOMAIN:
            Notify().send(
                'A website visitor created a new event via our website.\n' +
                'If no one deletes it within the next 24 hours, it will be automatically published and appears in our website search'
                + (', meetup group' if Secret('MEETUP.ACCESS_TOKEN').
                   value else '') +
                (' and discourse' if Secret('DISCOURSE.API_KEY').exists ==
                 True else '') + '.\n' +
                '🚫-> Does this event already exist or is it spam? Open on the following event link and click "Delete event".\n'
                +
                '✅-> You have a user account for our website and want to publish the event directly? Open on the following event link and click "Approve event".\n'
                + 'https://' + DOMAIN + '/' + new_event.str_slug)
        else:
            print(
                '--> Request not sent via hackerspace domain. Skipped notifying via Slack.'
            )

        # if event is repeating, create upcoming instances
        new_event = new_event.create_upcoming_instances()

        # if user is signed in and event autoapproved - direct to event page, else show info
        self.value = JsonResponse({'url_next': '/' + new_event.str_slug})
Exemplo n.º 9
0
 def config(self):
     return Secret('SLACK').value
Exemplo n.º 10
0
    def __init__(self, backup_files, test=False):
        self.backup_files = backup_files
        self.test = test

        folders = os.listdir()
        folder_options = ''
        counter = 1
        backups = []
        for file_name in folders:
            if 'setup_backup__' in file_name:
                backups.append(file_name)
                if self.test and file_name == 'setup_backup__unittest.zip':
                    unittest_zip_counter = counter

                if counter > 1:
                    folder_options += ', '
                folder_options += str(counter)+' - ' + \
                    file_name.split('setup_backup__')[1].split('.zip')[0]
                counter += 1

        if counter == 1:
            Log().show_message('No backups found.')
        else:
            Log().show_message(
                'Which setup would you like to import? '+folder_options)
            selected_folder = unittest_zip_counter if self.test else input()

            # test if folder exist
            try:
                from zipfile import ZipFile

                selected_num = int(selected_folder)-1
                folder_name = backups[selected_num]

                # first delete existing files
                for file_path in self.backup_files:
                    if os.path.exists(file_path):
                        os.remove(file_path)

                # copy files into folder
                with ZipFile(folder_name, 'r') as zip:
                    # extracting all the files
                    zip.extractall()

            except:
                Log().show_message(
                    'ERROR: The folder doesnt exist. Please enter a correct number.')

            # make sure cronjobs are also setup
            Cronjob().setup()

            # test if superuser already exists
            User = get_user_model()
            if User.objects.count() == 0:
                username = Config('BASICS.NAME').value+'SuperMember'
                password = secrets.token_urlsafe(50)
                User.objects.create_superuser(username, None, password)
                self.secrets = Secret().value
                self.secrets['DJANGO']['ADMIN_USER']['USERNAME'] = username
                self.secrets['DJANGO']['ADMIN_USER']['PASSWORD'] = password
                with open('_setup/secrets.json', 'w') as outfile:
                    json.dump(self.secrets, outfile, indent=4)
                Log().show_message('Created admin user (see _setup/secrets.json for the login details)')

            Log().show_message('✅Done! Imported "'+folder_name.split('setup_backup__')
                               [1].split('.zip')[0] + '" ('+self.get_size(folder_name)+') and created cronjobs to keep your database up to date!')
Exemplo n.º 11
0
 def config(self):
     return Secret('AWS').value
Exemplo n.º 12
0
def key_exists(str_key_name):
    return Secret(str_key_name).exists
Exemplo n.º 13
0
def get_key(str_key_name):
    return Secret(str_key_name).value
Exemplo n.º 14
0
 def config(self):
     return Secret('DISCOURSE').value
Exemplo n.º 15
0
    SECURE_SSL_REDIRECT = True
    SESSION_COOKIE_SECURE = True
    CSRF_COOKIE_SECURE = True
    ALLOWED_HOSTS = [Config('WEBSITE.DOMAIN').value]
else:
    DEBUG = True
    ALLOWED_HOSTS = ['*']

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = Secret('DJANGO.SECRET_KEY').value

# Application definition

INSTALLED_APPS = [
    '_apis',
    '_database',
    '_website',
    '_setup',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]