Example #1
0
    def _export(self):
        if self.name:
            folder_name = self.name
        else:
            show_messages([
                'Hello! It seems you want to export your current settings? (your config.json, secrets.json and important images)'
            ])

            show_message(
                'If that\'s the case, enter now a name for the exported folder. (or press Enter to exit)'
            )

            folder_name = input()

        if not folder_name:
            show_message('Ok, got it. Maybe another time.')
            exit()
        else:
            from zipfile import ZipFile, ZIP_DEFLATED

            # copy files into folder
            with ZipFile('setup_backup__' + folder_name + '.zip', 'w',
                         ZIP_DEFLATED) as zip:
                # writing each file one by one
                for file in self.backup_files:
                    try:
                        zip.write(file)
                    except:
                        pass

                show_message('✅Done! Exported "' + folder_name + '" (' +
                             get_size('setup_backup__' + folder_name +
                                      '.zip') + ')')
Example #2
0
    def import_from_twitter_hashtag(self):
        log('import_from_twitter_hashtag()')
        from hackerspace.models.meetingnotes import startChrome
        import time
        import requests
        from getConfig import get_config

        # check if hastag exists
        HASHTAG = get_config('SOCIAL.HASHTAG')

        # check if instagram tag is saved in settings
        if HASHTAG:
            show_message(
                '✅ Found SOCIAL.HASHTAG - Start importing photos from Twitter with your hashtag ...'
            )
            time.sleep(2)
            if requests.get('https://twitter.com/hashtag/{}?f=image'.format(
                    HASHTAG.split('#')[1])).status_code == 200:
                browser = startChrome(
                    True, 'https://twitter.com/hashtag/{}?f=image'.format(
                        HASHTAG.split('#')[1]))
            else:
                show_message(
                    'WARNING: I can\'t access your SOCIAL.HASHTAG on Twitter. Is the hashtag correct? Will skip importing photos from Twitter with your hashtag for now.'
                )
                time.sleep(4)
                return
        else:
            show_message(
                'WARNING: Can\'t find SOCIAL.HASHTAG in your config.json. Will skip importing photos from Twitter with your hashtag for now.'
            )
            time.sleep(4)
            return

        save_twitter_photos(browser)
Example #3
0
    def import_from_twitter(self):
        log('import_from_twitter()')
        from hackerspace.models.meetingnotes import startChrome
        import time
        import requests
        from getConfig import get_config

        # check if twitter is saved in social channels
        for entry in get_config('SOCIAL.SOCIAL_NETWORKS'):
            if 'twitter.com/' in entry['url']:
                show_message(
                    '✅ Found Twitter in SOCIAL.SOCIAL_NETWORKS - Start importing photos from your Twitter page ...'
                )
                time.sleep(2)
                if requests.get(entry['url']).status_code == 200:
                    browser = startChrome(True, entry['url'] + '/media')
                else:
                    show_message(
                        'WARNING: I can\'t access your Twitter page. Is the URL correct? Will skip importing photos from Twitter for now.'
                    )
                    time.sleep(4)
                    return
                break
        else:
            show_message(
                'WARNING: Can\'t find Twitter in SOCIAL.SOCIAL_NETWORKS in your config.json. Will skip importing photos from Twitter for now.'
            )
            time.sleep(4)
            return

        save_twitter_photos(browser)
Example #4
0
    def _import(self):
        import os

        folders = os.listdir()
        folder_options = ''
        counter = 1
        backups = []
        for file_name in folders:
            if 'setup_backup__' in file_name:
                backups.append(file_name)
                if counter > 1:
                    folder_options += ', '
                folder_options += str(counter)+' - ' + \
                    file_name.split('setup_backup__')[1].split('.zip')[0]
                counter += 1

        if counter == 1:
            show_message('No backups found.')
        else:
            show_message('Which setup would you like to import? ' +
                         folder_options)
            selected_folder = 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()

                show_message(
                    '✅Done! Imported "' +
                    folder_name.split('setup_backup__')[1].split('.zip')[0] +
                    '" (' + get_size(folder_name) + ')')

            except:
                show_message(
                    'ERROR: The folder doesnt exist. Please enter a correct number.'
                )
Example #5
0
    def import_from_discourse(self):
        print('import_from_discourse()')
        from hackerspace.models import Person
        from dateutil import parser
        from getKey import STR__get_key
        import time
        import requests
        from asci_art import show_message

        DISCOURSE_URL = STR__get_key('DISCOURSE.DISCOURSE_URL')
        if DISCOURSE_URL:
            show_message(
                '✅ Found DISCOURSE.DISCOURSE_URL - start importing Consensus Items from Discourse.'
            )
            time.sleep(2)

            if requests.get(DISCOURSE_URL +
                            '/c/consensus-items').status_code == 200:
                consensus_items = get_category_posts(
                    category='consensus-items', all_pages=True)
                print('process {} consensus-items'.format(
                    len(consensus_items)))
                for consensus_item in consensus_items:
                    if consensus_item[
                            'title'] != 'About the Consensus Items category':
                        Consensus().create(
                            json_content={
                                'str_name_en_US':
                                consensus_item['title'],
                                'url_discourse':
                                STR__get_key('DISCOURSE.DISCOURSE_URL') +
                                't/' + consensus_item['slug'],
                                'text_description_en_US':
                                consensus_item['excerpt'],
                                'int_UNIXtime_created':
                                round(
                                    datetime.timestamp(
                                        parser.parse(
                                            consensus_item['created_at']))),
                                'one_creator':
                                Person.objects.get_discourse_creator(
                                    consensus_item['slug']),
                            })
            else:
                show_message(
                    'WARNING: Can\'t find the "consensus-items" category on your Discourse. Skipped importing Consensus Items from Discourse.'
                )
                time.sleep(4)
        else:
            show_message(
                'WARNING: Can\'t find the DISCOURSE.DISCOURSE_URL in your secrets.json. Will skip Discourse for now.'
            )
            time.sleep(4)
Example #6
0
    def handle(self, *args, **options):
        from hackerspace.models import Event, Consensus, Person, Wish, Photo, Project
        from getConfig import get_config
        from getKey import STR__get_key
        from asci_art import show_message
        import time
        import requests

        show_message(
            'I will now start to update your database, based on your secrets.json and config.json. Depending on your settings, amount of events & photos & Discourse entries from your hackerspace this can take everything from seconds to hours (?). But you can already test your website - by opening a new terminal window and run "python manage.py runserver 0.0.0.0:8000" - and open 0.0.0.0:8000 in your web browser.'
        )
        time.sleep(8)

        # import data from Discourse
        Person.objects.import_from_discourse()
        Consensus.objects.import_from_discourse()
        Project.objects.import_from_discourse()
        # TODO Adding Wishlist
        # Wish.objects.import_from_discourse()

        # import events from Meetup
        Event.objects.import_from_meetup()
        extra_groups = get_config('EVENTS.EXTRA_MEETUP_GROUPS')
        if extra_groups:
            show_message('Import events from additional Meetup groups ...')
            time.sleep(2)
            for group in extra_groups:
                Event.objects.import_from_meetup(group)

        # import photos
        show_message('Start importing your existing photos from the web ...')
        time.sleep(2)

        Photo.objects.import_from_google_photos()
        Photo.objects.import_from_twitter()
        Photo.objects.import_from_twitter_hashtag()
        Photo.objects.import_from_wiki()
        Photo.objects.import_from_instagram()
        Photo.objects.import_from_instagram_tag()
        Photo.objects.import_from_flickr()

        show_message('✅ Done! I updated the database')
        time.sleep(2)
Example #7
0
    def _delete(self):
        import os
        show_message(
            'WARNING: Are you sure you want to delete your current setup? This will delete the config.json, secrets.json and your logos & favicons. Enter "delete" to delete the current setup.'
        )
        confirm = input()
        if confirm == 'delete':
            for file_path in self.backup_files:
                if os.path.exists(file_path):
                    os.remove(file_path)

            show_message('✅Done! I deleted the current setup.')

        else:
            show_message('Ok. I won\'t delete anything.')
Example #8
0
    def import_from_discourse(self):
        from hackerspace.APIs.discourse import get_users
        from getKey import STR__get_key
        import time
        import requests
        from asci_art import show_message

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

            if requests.get(DISCOURSE_URL).status_code == 200:
                users = get_users()
                log('--> 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:
                show_message(
                    'WARNING: I can\'t access your Discourse page. Is the URL correct? Will skip Discourse for now.'
                )
                time.sleep(4)
        else:
            show_message(
                'WARNING: Can\'t find the DISCOURSE.DISCOURSE_URL in your secrets.json. Will skip Discourse for now.'
            )
            time.sleep(4)
Example #9
0
    def import_from_instagram_tag(self):
        log('import_from_instagram_tag()')
        from hackerspace.models.meetingnotes import startChrome
        import time
        import requests
        from getConfig import get_config

        HASHTAG = get_config('SOCIAL.HASHTAG')

        # check if instagram tag is saved in settings
        if HASHTAG:
            show_message(
                '✅ Found SOCIAL.HASHTAG - Start importing photos from Instagram with your hashtag ...'
            )
            time.sleep(2)
            if requests.get(
                    'https://www.instagram.com/explore/tags/{}/'.format(
                        HASHTAG.split('#')[1])).status_code == 200:
                browser = startChrome(
                    True, 'https://www.instagram.com/explore/tags/{}/'.format(
                        HASHTAG.split('#')[1]))
            else:
                show_message(
                    'WARNING: I can\'t access your SOCIAL.HASHTAG on Instagram. Is the hashtag correct? Will skip importing photos from Instagram with your hashtag for now.'
                )
                time.sleep(4)
                return
        else:
            show_message(
                'WARNING: Can\'t find SOCIAL.HASHTAG in your config.json. Will skip importing photos from Instagram with your hashtag for now.'
            )
            time.sleep(4)
            return

        # open image in overlay
        browser.execute_script("window.scrollTo(0, 150);")
        time.sleep(2)
        browser.find_elements_by_class_name('v1Nh3.kIKUG._bz0w')[0].click()

        # save photos
        save_instagram_photos(browser)
Example #10
0
    def import_from_meetup(self, slug=get_config('EVENTS.MEETUP_GROUP')):
        log('Event.objects.import_from_meetup(self,slug={})'.format(slug))
        import requests
        from getConfig import get_config
        import time

        if slug:
            show_message(
                '✅ Start importing existing events from "'+slug+'" on Meetup.')
            time.sleep(2)

            if requests.get('https://meetup.com/'+slug).status_code == 200:
                json_our_group = requests.get('https://api.meetup.com/'+slug+'/events',
                                            params={
                                                'fields': [
                                                    'featured_photo',
                                                    'series',
                                                    'simple_html_description',
                                                    'rsvp_sample',
                                                    'description_images',
                                                ],
                                                'photo-host': 'public'
                                            }).json()

                log('--> Saving '+str(len(json_our_group)) +
                    ' events from our hackerspace group')

                for event in json_our_group:
                    if slug == get_config('EVENTS.MEETUP_GROUP') or get_config('BASICS.NAME') in event['name']:
                        createEvent(event)

                log('--> Done! Saved '+str(len(json_our_group)) + ' events from Meetup')

            else:
                show_message(
                    'WARNING: I can\'t access the Meetup group. Is the URL correct? Will skip the Meetup group for now.')
                time.sleep(4)
        else:
            show_message(
                'WARNING: Can\'t find the Meetup group in your config.json. Will skip the Meetup group for now.')
            time.sleep(4)
Example #11
0
    def import_from_discourse(self):
        print('import_from_discourse()')
        from hackerspace.models import Person
        from hackerspace.APIs.discourse import get_category_posts
        from datetime import datetime
        from dateutil import parser
        from getKey import STR__get_key
        from asci_art import show_message
        import time
        import requests

        DISCOURSE_URL = STR__get_key('DISCOURSE.DISCOURSE_URL')
        if DISCOURSE_URL:
            show_message(
                '✅ Found DISCOURSE.DISCOURSE_URL - start importing projects from Discourse.')
            time.sleep(2)

            if requests.get(DISCOURSE_URL+'/c/projects').status_code == 200:
                projects = get_category_posts(
                    category='projects', all_pages=True)
                log('--> process {} projects'.format(len(projects)))
                for project in projects:
                    if project['title'] != 'About the Projects category':
                        Project().create(json_content={
                            'str_name_en_US': project['title'],
                            'url_featured_photo': project['image_url'] if project['image_url'] and '/uploads' in project['image_url'] else None,
                            'url_discourse': STR__get_key('DISCOURSE.DISCOURSE_URL') + 't/'+project['slug'],
                            'text_description_en_US': project['excerpt'] if 'excerpt' in project else None,
                            'one_creator': Person.objects.get_discourse_creator(project['slug']),
                            'int_UNIXtime_created': round(datetime.timestamp(parser.parse(project['created_at'])))
                        }
                        )
            else:
                show_message(
                    'WARNING: Can\'t find the "projects" category on your Discourse. Skipped importing Consensus Items from Discourse.')
                time.sleep(4)
        else:
            show_message(
                'WARNING: Can\'t find the DISCOURSE.DISCOURSE_URL in your secrets.json. Will skip Discourse for now.')
            time.sleep(4)
Example #12
0
    def import_from_instagram(self):
        log('import_from_instagram()')
        from hackerspace.models.meetingnotes import startChrome
        import time
        import requests
        from getConfig import get_config

        # check if instagram is saved in social channels
        for entry in get_config('SOCIAL.SOCIAL_NETWORKS'):
            if 'instagram.com/' in entry['url']:
                show_message(
                    '✅ Found Instagram in SOCIAL.SOCIAL_NETWORKS - Start importing photos from your Instagram page ...'
                )
                time.sleep(2)
                if requests.get(entry['url']).status_code == 200:
                    browser = startChrome(True, entry['url'])
                else:
                    show_message(
                        'WARNING: I can\'t access your Instagram page. Is the URL correct? Will skip importing photos from your Instagram page for now.'
                    )
                    time.sleep(4)
                    return
                break
        else:
            show_message(
                'WARNING: Can\'t find Instagram in SOCIAL.SOCIAL_NETWORKS in your config.json. Will skip importing photos from your Instagram page for now.'
            )
            time.sleep(4)
            return

        # open image in overlay
        browser.execute_script("window.scrollTo(0, 450);")
        time.sleep(2)
        browser.find_elements_by_class_name('v1Nh3.kIKUG._bz0w')[0].click()

        # save photos
        save_instagram_photos(browser)

        log('--> Finished!!')
Example #13
0
    def import_from_wiki(self):
        # API documentation: https://www.mediawiki.org/wiki/API:Allimages
        log('import_from_wiki()')
        from getConfig import get_config
        import requests
        import time

        WIKI_API_URL = get_config('BASICS.WIKI.API_URL')

        if WIKI_API_URL:
            show_message(
                '✅ Found BASICS.WIKI.API_URL - Start importing photos from your Wiki ...'
            )
            time.sleep(2)
            if requests.get(WIKI_API_URL).status_code != 200:
                show_message(
                    'WARNING: I can\'t access your Wiki. Is the API_URL correct? Will skip importing photos from your Wiki for now.'
                )
                time.sleep(4)
                return
        else:
            show_message(
                'WARNING: Can\'t find BASICS.WIKI.API_URL in your config.json. Will skip importing photos from your Wiki for now.'
            )
            time.sleep(4)
            return

        parameter = {
            'action': 'query',
            'format': 'json',
            'list': 'allimages',
            'list': 'allimages',
            'aisort': 'timestamp',
            'aidir': 'descending',
            'ailimit': '500',
            'aiminsize':
            '50000',  # minimum 50kb size, to filter out small logos/icons
            'aiprop': 'timestamp|canonicaltitle|url|user'
        }
        response_json = requests.get(WIKI_API_URL, params=parameter).json()

        skipped_photos_counter = 0

        # for every photo...
        for photo in response_json['query']['allimages']:
            if skipped_photos_counter < 5:
                status = save_wiki_photo(photo)
                if status == 'Skipped':
                    skipped_photos_counter += 1

        while 'continue' in response_json and 'aicontinue' in response_json[
                'continue'] and skipped_photos_counter < 5:
            response_json = requests.get(
                WIKI_API_URL,
                params={
                    **parameter,
                    **{
                        'aicontinue': response_json['continue']['aicontinue']
                    }
                }).json()

            for photo in response_json['query']['allimages']:
                status = save_wiki_photo(photo)
                if status == 'Skipped':
                    skipped_photos_counter += 1

        if skipped_photos_counter >= 5:
            log('No new photos it seems.')

        log('Complete! All photos processed! Now {} photos'.format(
            Photo.objects.count()))
Example #14
0
    def import_from_flickr(self):
        log('import_from_flickr()')
        from hackerspace.models.meetingnotes import startChrome
        import time
        from dateutil.parser import parse
        from datetime import datetime
        from getConfig import get_config
        import requests

        FLICKR_URL = get_config('SOCIAL.FLICKR_URL')

        # check if instagram tag is saved in settings
        if FLICKR_URL:
            show_message(
                '✅ Found SOCIAL.FLICKR_URL - Start importing photos from Flickr ...'
            )
            time.sleep(2)

            if requests.get(FLICKR_URL).status_code == 200:
                browser = startChrome(True, FLICKR_URL)
            else:
                show_message(
                    'WARNING: I can\'t access your FLICKR_URL. Is the URL correct? Will skip importing photos from Flickr for now.'
                )
                time.sleep(4)
                return
        else:
            show_message(
                'WARNING: Can\'t find SOCIAL.FLICKR_URL in your config.json. Will skip importing photos from Flickr for now.'
            )
            time.sleep(4)
            return

        processed_images = 0

        time.sleep(5)
        no_images_found_counter = 0

        while boolean_element_exists(browser,
                                     'view.photo-list-photo-view.awake'
                                     ) == True or no_images_found_counter < 5:
            # if no photo found... click "load more" button if exists, else scroll down and wait
            if boolean_element_exists(
                    browser, 'view.photo-list-photo-view.awake') == False:
                while boolean_element_exists(
                        browser, 'view.photo-list-photo-view.awake') == False:
                    # see if load more button exists
                    if boolean_element_exists(
                            browser, 'infinite-scroll-load-more') == True:
                        browser.find_element_by_class_name(
                            'infinite-scroll-load-more').click()
                    else:
                        # else scroll down
                        browser.execute_script(
                            "window.scrollTo(0, document.body.scrollHeight);")

                    time.sleep(5)

                    no_images_found_counter += 1
                    if no_images_found_counter == 5:
                        log('--> No more images left. Exit code.')
                        exit()

            # get the first image
            photo = browser.find_elements_by_class_name(
                'view.photo-list-photo-view.awake')[0]

            # get image url, name and post url
            url_image = 'https://' + \
                photo.get_attribute("style").split('url("//')[1].split('"')[0]
            str_titel = photo.find_elements_by_css_selector(
                "*")[0].find_elements_by_css_selector(
                    "*")[0].find_elements_by_css_selector(
                        "*")[0].get_attribute('aria-label')
            url_post = photo.find_elements_by_css_selector(
                "*")[0].find_elements_by_css_selector(
                    "*")[0].find_elements_by_css_selector(
                        "*")[0].get_attribute('href')

            if Photo.objects.filter(url_post=url_post).exists() == False:
                # open photo in new tab, switch to new tab, get created date, close tab & switch to previous tab
                new_window = startChrome(True, url_post)
                int_UNIXtime = round(
                    datetime.timestamp(
                        parse(
                            new_window.find_element_by_class_name(
                                'date-taken-label').text.split('on ')[1])))
                new_window.close()

                # save photo
                Photo(
                    text_description_en_US=url_post,
                    url_image=url_image,
                    url_post=url_post,
                    str_source='Flickr',
                    int_UNIXtime_created=int_UNIXtime,
                ).save()
                log('--> New photo saved')
            else:
                log('--> Photo exist. Skipped...')

            # delete image from feed and go to next one
            browser.execute_script("""
            document.getElementsByClassName(
                'view photo-list-photo-view awake')[0].outerHTML=''
            """)

            processed_images += 1
            log('-> processed_images: ' + str(processed_images))
Example #15
0
    def _new(self):
        import secrets
        import json
        from asci_art import show_messages, set_secret, set_secrets, show_message
        from googletrans import Translator
        translator = Translator()

        show_messages(['Let\'s setup your new hackerspace website!'])

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

        show_message('First: What is the name of your hackerspace?')
        self.name = input()
        if self.name:
            self.config['BASICS']['NAME'] = self.name
            show_message(
                'Ok, great! Give me a seconds, so I can try to setup your RISEUPPAD_MEETING_PATH, and MEETUP_GROUP as well...'
            )

            # if hackerspace name saved, also save other config defaults based on name
            self.config['MEETINGS']['RISEUPPAD_MEETING_PATH'] = self.name.lower() + \
                '-meetings'
            if requests.get('https://www.meetup.com/' +
                            self.name.lower()).status_code == 200:
                self.config['EVENTS']['MEETUP_GROUP'] = self.name.lower()

        self.config = set_secret(
            self.config, later_then_config,
            'Ok, great. And in what city is your hackerspace? (Just the city name itself)',
            'PHYSICAL_SPACE', 'ADDRESS', 'CITY')
        if self.config['PHYSICAL_SPACE']['ADDRESS']['CITY']:
            self.config['BASICS']['HACKERSPACE_IS_SENTENCES']['english'][
                0] = self.config['BASICS']['HACKERSPACE_IS_SENTENCES'][
                    'english'][0].replace(
                        '{{ CITY }}',
                        self.config['PHYSICAL_SPACE']['ADDRESS']['CITY'])
            self.config['BASICS']['HACKERSPACE_IS_SENTENCES']['hebrew'][
                0] = self.config['BASICS']['HACKERSPACE_IS_SENTENCES'][
                    'hebrew'][0].replace(
                        '{{ CITY }}',
                        translator.translate(text=self.config['PHYSICAL_SPACE']
                                             ['ADDRESS']['CITY'],
                                             dest='he').text)

        self.config = set_secret(
            self.config, later_then_config,
            'Enter your hackerspace street & house number.', 'PHYSICAL_SPACE',
            'ADDRESS', 'STREET')
        self.config = set_secret(self.config, later_then_config,
                                 'Enter your hackerspace ZIP code.',
                                 'PHYSICAL_SPACE', 'ADDRESS', 'ZIP')
        self.config = set_secret(
            self.config, later_then_config,
            'Enter your hackerspace state. (California for example)',
            'PHYSICAL_SPACE', 'ADDRESS', 'STATE')
        self.config = set_secret(
            self.config, later_then_config,
            'Enter your hackerspace country code (US or DE for example)',
            'PHYSICAL_SPACE', 'ADDRESS', 'COUNTRYCODE')
        self.config = set_secret(
            self.config, later_then_config,
            'Anything else people have to know to find your hackerspace?',
            'PHYSICAL_SPACE', 'ADDRESS', 'HOW_TO_FIND_US__english')
        self.config = set_secret(
            self.config, later_then_config,
            'Please enter the URL of your embedded map, to show people where your hackerspace is. My suggestion: go to https://www.google.com/maps - select your hackerspace, press the "Share" button -> "Embed a map" and enter here the "scr" URL of the iframe code.',
            'BASICS', 'EMBEDDED_MAP_URL')

        # save lat/lon based on address
        if self.config['PHYSICAL_SPACE']['ADDRESS']['STREET'] and self.config[
                'PHYSICAL_SPACE']['ADDRESS']['CITY']:
            show_message(
                'Ok, great! Give me a seconds, so I can try to find and save the matching LAT_LON and TIMEZONE_STRING as well...'
            )
            location, lat, lon = get_lat_lon_and_location(
                self.config['PHYSICAL_SPACE']['ADDRESS']['STREET'] + ', ' +
                self.config['PHYSICAL_SPACE']['ADDRESS']['CITY'] +
                (', ' + self.config['PHYSICAL_SPACE']['ADDRESS']['STATE'] if
                 self.config['PHYSICAL_SPACE']['ADDRESS']['STATE'] else '') +
                (', ' + self.config['PHYSICAL_SPACE']['ADDRESS']['COUNTRYCODE']
                 if self.
                 config['PHYSICAL_SPACE']['ADDRESS']['COUNTRYCODE'] else ''))
            if lat != None:
                self.config['PHYSICAL_SPACE']['LAT_LON'] = [lat, lon]

                # also save timezone string based on lat/lon
                self.config['PHYSICAL_SPACE'][
                    'TIMEZONE_STRING'] = STR__get_timezone_from_lat_lon(
                        lat, lon)
                show_message('It worked!')

        self.config = set_secret(
            self.config, later_then_config,
            'What #hashtag do people use when they talk online about your hackerspace on Twitter or Instagram? (Example: #noisebridge)',
            'SOCIAL', 'HASHTAG')
        self.config = set_secret(
            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 = set_secret(
            self.config, later_then_config,
            'Where is your hackerspace GIT repo hosted? So others can suggest changes to your code. (please enter the full URL)',
            'WEBSITE', 'WEBSITE_GIT')
        self.config = set_secret(
            self.config, later_then_config,
            'What domain will you use for your new hackerspace website? (Just the domain. Example: "noisebridge.net")',
            'WEBSITE', 'DOMAIN')

        show_message('One second...')
        # auto generate the event footer for discourse and meetup
        if self.config['WEBSITE']['DOMAIN'] and self.config['BASICS']['NAME']:
            self.config['EVENTS']['DISCOURSE_AND_MEETUP_EVENT_FOOTER_HTML'] =\
                '<br>------------------<br>'\
                '<br>'+self.config['BASICS']['NAME']+' is funded by YOUR donations. '\
                'So if you want to support '+self.config['BASICS']['NAME']+' - donations are always welcomed - '\
                'money, hardware or time (by organizing or volunteering an event). '\
                'Visit https://' + \
                self.config['WEBSITE']['DOMAIN']+' for more details.'

        # try to auto find the wiki api url, else ask for it
        if self.config['WEBSITE']['DOMAIN'] and requests.get(
                'https://' + self.config['WEBSITE']['DOMAIN'] +
                '/api.php').status_code == 200:
            self.config['BASICS']['WIKI']['API_URL'] = 'https://' + \
                self.config['WEBSITE']['DOMAIN']+'/api.php'
        else:
            self.config = set_secret(
                self.config, later_then_config,
                'Do you have a wiki? What is the API URL?', 'BASICS', 'WIKI',
                'API_URL')
        self.config = set_secret(
            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 hackerspace logo?',
            'CSS', 'PRIMARY_COLOR')

        # then setup secrets.json
        later_then_secrets = 'Guess later then... Open your secrets.json at any time to make changes.'

        self.secrets['DJANGO']['SECRET_KEY'] = secrets.token_urlsafe(50)
        self.secrets['DJANGO']['ADMIN_URL'] = secrets.token_urlsafe(20)

        show_messages([
            'Awesome! Let\'s complete the setup by saving your secrets (API keys, etc.)',
            'Starting with: AWS (needed to enable users to upload event images when they create a new event via your new website)'
        ])

        self.secrets = set_secrets(self.secrets, later_then_secrets, 'AWS')

        show_messages([
            'Does your hackerspace use Discourse? It\'s a great forum software used by many hackerspaces & other communities.',
            'Let\'s setup your Discourse secrets, so we can automatically post new user generated events from your website to your Discourse page.',
        ])

        self.secrets = set_secrets(self.secrets, later_then_secrets,
                                   'Discourse')

        show_messages([
            'Does your hackerspace have a Meetup group? Meetup.com is super useful to make more people aware of your events!',
            'Let\'s setup your Meetup secrets, so we can automatically post new user generated events from your website to your Meetup group.',
        ])

        self.secrets = set_secrets(self.secrets, later_then_secrets, 'Meetup')

        show_messages([
            'Does your hackerspace use Slack? Slack is both useful for chats within the community - but also for notifications from automated scripts.',
            'Let\'s setup your Slack API_TOKEN, so we can automatically inform you if a visitor created an event. So people in your community have the chance to reject the event and prevent it from automatically getting posted.',
        ])

        self.secrets = set_secrets(self.secrets, later_then_secrets, 'Slack')

        with open('config.json', 'w') as outfile:
            json.dump(self.config, outfile, indent=4)

        with open('secrets.json', 'w') as outfile:
            json.dump(self.secrets, outfile, indent=4)

        show_messages([
            '✅ Yeahh we are done! I saved your config.json and secrets.json files in the main directory. So you can easily change them any time.',
        ])
Example #16
0
    def _menu(self):
        import os
        options = ['Create a new website']
        options_string = '1 - Create a new website'
        counter = 1

        # build options string

        # if any file in self.backup_files exist, show "export setup" and "delete current setup"
        if self.boolean_files_exist == True:
            counter += 1
            new_option = 'Export current setup'
            options.append(new_option)
            options_string += ', ' + str(counter) + ' - ' + new_option

            counter += 1
            new_option = 'Delete current setup'
            options.append(new_option)
            options_string += ', ' + str(counter) + ' - ' + new_option

        # if any folders in "backup" folder, show "import backup"
        folders = os.listdir()
        folder_options = ''
        backups_counter = 1
        for file_name in folders:
            if 'setup_backup__' in file_name:
                backups_counter += 1

        if backups_counter > 1:
            counter += 1
            new_option = 'Import backup'
            options.append(new_option)
            options_string += ', ' + str(counter) + ' - ' + new_option

        # if only "Create a new website" as an option, auto proceed with that
        if counter == 1:
            self._new()
        else:
            show_message('Welcome! How can I help you? (enter a number) ' +
                         options_string)
            selection_processedd = False
            while selection_processedd == False:
                try:
                    selection = input()
                    selector_number = int(selection) - 1
                    if options[selector_number] == 'Create a new website':
                        self._new()
                        selection_processedd = True
                    elif options[selector_number] == 'Export current setup':
                        self._export()
                        selection_processedd = True
                    elif options[selector_number] == 'Delete current setup':
                        self._delete()
                        selection_processedd = True
                    elif options[selector_number] == 'Import backup':
                        self._import()
                        selection_processedd = True
                    else:
                        show_message(
                            'ERROR: That option doesn\'t exist. How can I help you? (enter a number) '
                            + options_string)
                except KeyboardInterrupt:
                    exit()
                except:
                    show_message(
                        'ERROR: That option doesn\'t exist. How can I help you? (enter a number) '
                        + options_string)
Example #17
0
    def import_from_google_photos(self):
        log('import_from_google_photos()')
        from hackerspace.models.meetingnotes import startChrome
        import time
        import requests
        from getConfig import get_config
        from dateutil.parser import parse
        from datetime import datetime
        from selenium.webdriver.common.action_chains import ActionChains
        from selenium.webdriver.common.keys import Keys

        # check if google photos urls exist
        GOOGLE_URLS = get_config('SOCIAL.GOOGLE_PHOTOS_ALBUM_URLS')
        if len(GOOGLE_URLS) > 0:
            show_message(
                '✅ Found GOOGLE_PHOTOS_ALBUM_URLS - Start importing photos from Google Photos ...'
            )
            time.sleep(2)
        else:
            show_message(
                'WARNING: Can\'t find GOOGLE_PHOTOS_ALBUM_URLS in your config.json. Will skip importing photos from Google Photos for now.'
            )
            time.sleep(4)
            return

        for URL in GOOGLE_URLS:
            if requests.get(URL).status_code == 200:
                browser = startChrome(True, URL)

                # open first image
                browser.find_elements_by_class_name('rtIMgb.fCPuz')[0].click()
                time.sleep(4)

                # open info window
                browser.find_element_by_xpath('//*[@title="Info"]').click()
                time.sleep(4)

                already_saved_counter = 0

                while boolean_element_exists(
                        browser, '//*[@aria-label="View next photo"]'
                ) == True and already_saved_counter < 5:

                    info_window = browser.find_element_by_class_name(
                        'Q77Pt.eejsDc')
                    str_date = info_window.find_element_by_class_name(
                        'R9U8ab').get_attribute('innerHTML')
                    str_time = info_window.find_element_by_class_name(
                        'sprMUb').get_attribute('innerHTML').replace(
                            'Yesterday, ', '').replace('Today, ', '')

                    # get image
                    url_image = browser.find_element_by_xpath(
                        '//*[@jsname="uLHQEd"]').get_attribute('src').split(
                            '=w')[0]

                    # get date
                    image_date = parse(str_date + ', ' + str_time)

                    if Photo.objects.filter(
                            url_image=url_image).exists() == False:
                        Photo(url_image=url_image,
                              url_post=browser.current_url,
                              str_source='Google Photos',
                              int_UNIXtime_created=round(
                                  datetime.timestamp(image_date))).save()
                        log('--> New photo saved')
                    else:
                        log('--> Photo exist. Skipped...')
                        already_saved_counter += 1

                    # next photo
                    actions = ActionChains(browser)
                    actions.send_keys(Keys.RIGHT)
                    actions.perform()
                    time.sleep(6)

                if already_saved_counter >= 5:
                    log('--> No new photos it seems.')

                log('--> Done! saved all photos.')

            else:
                show_message(
                    'WARNING: I can\'t access your Google Album. Is the URL correct? Will skip importing photos from this album for now.'
                )
                time.sleep(4)