Exemple #1
0
def get_auth(settings_file="settings.yaml", webauth=False):
    gauth = GoogleAuth(settings_file=settings_file)
    if webauth:
        gauth.LocalWebserverAuth()
    else:
        gauth.CommandLineAuth()
    return gauth
Exemple #2
0
def authenticate_and_authorize(options, settings_file=None, method="local"):
    gauth = GoogleAuth(settings_file=settings_file)

    gauth.LoadCredentials()
    if gauth.credentials is not None:
        raise RuntimeError(
            "Error: credentials found at %s and it's already authenticated; skipping..."
            % gauth.settings.get("save_credentials_file"))

    if method == "local":
        gauth.LocalWebserverAuth(host_name=options.hostname,
                                 port_numbers=options.ports)
    elif method == "command_line":
        gauth.CommandLineAuth()
    else:
        raise ValueError(
            "Error: received --method=%s, but --method can only be either 'local' or 'command_line'."
            % method)

    if gauth:
        print()
        print("Finished authentication and authorizion.")
        print(
            "Please configure google drive client with gdrive-config if you have not done so yet."
        )
        print("Then, use gdrive -h for more information.")

    return gauth
def main(argv):
    root_directory = os.getcwd()
    parent_id = ''

    try:
        opts, args = getopt.getopt(argv, 'i:d:h', ["directory="])
    except getopt.GetoptError as err:
        print(err)
        usage()
        sys.exit(2)

    for o, a in opts:
        if o == "-i":
            parent_id = a
        elif o == "-d":
            root_directory = a
        elif o == "-h":
            usage()
        else:
            assert False, "unhandled option"

    if parent_id is not '':
        gauth = GoogleAuth()
        gauth.LocalWebserverAuth()
        drive = GoogleDrive(gauth)

        if not os.path.exists(root_directory):
            os.makedirs(root_directory)

        tree = listFolder(parent_id, drive)
        downloadAndStore(tree, root_directory)
Exemple #4
0
 def __init__(self, local_repo_path, model_id):
     self.repo_path = local_repo_path
     self.model_id = model_id
     GoogleAuth = set_secrets_file()
     gauth = GoogleAuth()
     gauth.LocalWebserverAuth()
     self.drive = GoogleDrive(gauth)
Exemple #5
0
def drive_login() -> GoogleAuth:
    cwd = change_dir(
    )  # temp solution until we know what will be the working directory

    gauth = GoogleAuth()
    gauth.LocalWebserverAuth()

    os.chdir(cwd)

    return gauth
Exemple #6
0
 def test_01_LocalWebserverAuthWithClientConfigFromFile(self):
     # Delete old credentials file
     delete_file("credentials/1.dat")
     # Test if authentication works with config read from file
     ga = GoogleAuth(settings_file_path("test_oauth_test_01.yaml"))
     ga.LocalWebserverAuth()
     self.assertEqual(ga.access_token_expired, False)
     # Test if correct credentials file is created
     self.CheckCredentialsFile("credentials/1.dat")
     time.sleep(1)
Exemple #7
0
 def test_02_LocalWebserverAuthWithClientConfigFromSettings(self):
   # Delete old credentials file
   delete_file('credentials/2.dat')
   # Test if authentication works with config read from settings
   ga = GoogleAuth('pydrive2/test/settings/test_oauth_test_02.yaml')
   ga.LocalWebserverAuth()
   self.assertEqual(ga.access_token_expired, False)
   # Test if correct credentials file is created
   self.CheckCredentialsFile('credentials/2.dat')
   time.sleep(1)
Exemple #8
0
 def test_03_LocalWebServerAuthWithNoCredentialsSaving(self):
   # Delete old credentials file
   delete_file('credentials/4.dat')
   # Provide wrong credentials file
   ga = GoogleAuth('pydrive2/test/settings/test_oauth_test_03.yaml')
   ga.LocalWebserverAuth()
   self.assertEqual(ga.access_token_expired, False)
   # Test if correct credentials file is created
   self.CheckCredentialsFile('credentials/4.dat', no_file=True)
   time.sleep(1)
 def __init__(self):
     gauth = GoogleAuth()
     gauth.LoadCredentialsFile("google_credentials.txt")
     if gauth.credentials is None:
         gauth.LocalWebserverAuth()
     elif gauth.access_token_expired:
         gauth.Refresh()
     else:
         gauth.Authorize()
     gauth.SaveCredentialsFile("google_credentials.txt")
     self.drive = GoogleDrive(gauth)
Exemple #10
0
def access():
    gauth = GoogleAuth()
    gauth.LoadCredentialsFile("credentials.json") # load credentials
    if gauth.credentials is None: # if failed, get them
        gauth.LocalWebserverAuth()
    elif gauth.access_token_expired: # or if expired, refresh
        gauth.Refresh()
    else:
        gauth.Authorize() # good
    gauth.SaveCredentialsFile("credentials.json") # save
    return GoogleDrive(gauth)
Exemple #11
0
    def __init__(self):
        ##vars to use later
        self.lastScheduleUpdateTime = datetime.datetime.min
        self.scheduleData = []

        ##load important stuff
        self.root = LOAD_ENV_VARS.ENV_VARS['root']
        self.access_token = LOAD_ENV_VARS.ENV_VARS['gd_access_token']
        self.client_secret = LOAD_ENV_VARS.ENV_VARS['gd_client_secret']
        self.client_id = LOAD_ENV_VARS.ENV_VARS['gd_client_id']
        self.refresh_token = LOAD_ENV_VARS.ENV_VARS['gd_refresh_token']
        self.token_expiry = LOAD_ENV_VARS.ENV_VARS['gd_token_expiry']
        if True:
            ##make client creds
            Text = """{"access_token": %s, "client_id": %s, "client_secret": %s, "refresh_token": %s, "token_expiry": %s, "token_uri": "https://oauth2.googleapis.com/token", "user_agent": null, "revoke_uri": "https://oauth2.googleapis.com/revoke", "id_token": null, "id_token_jwt": null, "token_response": {"access_token": %s, "expires_in": 3600, "refresh_token": %s, "scope": "https://www.googleapis.com/auth/drive", "token_type": "Bearer"}, "scopes": ["https://www.googleapis.com/auth/drive"], "token_info_uri": "https://oauth2.googleapis.com/tokeninfo", "invalid": false, "_class": "OAuth2Credentials", "_module": "oauth2client.client"}""" % (
                self.access_token, self.client_id, self.client_secret,
                self.refresh_token, self.token_expiry, self.access_token,
                self.refresh_token)
            f = open("mycreds.txt", "w+")
            f.write(Text)
            f.close()
            ##make client secrets from enviromental variables
            Text = '''{"installed":{"client_id":%s,"project_id":"quickstart-1564436220867","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://oauth2.googleapis.com/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":%s,"redirect_uris":["urn:ietf:wg:oauth:2.0:oob","http://localhost"]}}''' % (
                self.client_id, self.client_secret)
            f = open("client_secrets.json", "w+")
            f.write(Text)
            f.close()
        else:
            self.root = 'Python Bot Test'

        # Try to load saved client credentials
        gauth = GoogleAuth()
        gauth.LoadCredentialsFile("mycreds.txt")
        if gauth.credentials is None:
            # Authenticate if they're not there
            gauth.LocalWebserverAuth()
        elif gauth.access_token_expired:
            # Refresh them if expired
            gauth.Refresh()
        else:
            # Initialize the saved creds
            gauth.Authorize()
        # Save the current credentials to a file
        gauth.SaveCredentialsFile("mycreds.txt")
        self.UpdateEnvVars()
        #initialize drive object
        self.drive = GoogleDrive(gauth)
        ##Setup sechdule
        self.loadSchedule()
Exemple #12
0
def login():
    GoogleAuth.DEFAULT_SETTINGS['client_config_file'] = credencials_directory
    gauth = GoogleAuth()
    gauth.LoadCredentialsFile(credencials_directory)

    if gauth.credentials is None:
        gauth.LocalWebserverAuth(port_numbers=[8092])
    elif gauth.access_token_expired:
        gauth.Refresh()
    else:
        gauth.Authorize()

    gauth.SaveCredentialsFile(credencials_directory)
    credentials = GoogleDrive(gauth)
    return credentials
def main():
    gauth = GoogleAuth()
    # Try to load saved client credentials
    gauth.LoadCredentialsFile("secret.json")
    if gauth.credentials is None:
        # Authenticate if they're not there
        gauth.LocalWebserverAuth()
    elif gauth.access_token_expired:
        # Refresh them if expired
        gauth.Refresh()
    else:
        # Initialize the saved credentials
        gauth.Authorize()
    # Save the current credentials to a file
    gauth.SaveCredentialsFile("secret.json")
Exemple #14
0
def Upload_To_GDrive():
    global File_Name
    gauth = GoogleAuth()

    gauth.LoadCredentialsFile("mycreds.txt")
    if gauth.credentials is None:

        gauth.GetFlow()
        gauth.flow.params.update({'access_type': 'offline'})
        gauth.flow.params.update({'approval_prompt': 'force'})

        gauth.LocalWebserverAuth()
    elif gauth.access_token_expired:
        try:
            gauth.Refresh()
        except Exception as e:
            print(e)
    else:
        gauth.Authorize()

    gauth.SaveCredentialsFile("mycreds.txt")
    drive = GoogleDrive(gauth)

    folder_id = [
        'Folder_String_A', 'Folder_String_B', 'Folder_String_C',
        'Folder_String_D'
    ]

    for k in range(len(File_Name)):
        try:

            f = drive.CreateFile({
                'title':
                f'{File_Name[k]}.csv',
                "parents": [{
                    "kind": "drive#fileLink",
                    "id": folder_id[k]
                }]
            })
            f.SetContentFile(f'./Data/{File_Name[k]}.csv')
            f.Upload()
            print("Uploading succeeded!")
        except:
            print("Uploading failed.")

    print(time.ctime())
    def __authenticate(self):
        credentials_full_path = os.path.join(self._credentials_path,
                                             'credentials.json')
        token = os.path.join(self._credentials_path, 'credentials')

        gauth = GoogleAuth()
        gauth.LoadClientConfigFile(credentials_full_path)

        if os.path.exists(token):
            gauth.LoadCredentialsFile(token)

        cred = gauth.credentials
        if not cred or cred.invalid:
            if cred and cred.access_token_expired and cred.refresh_token:
                gauth.Refresh()
            else:
                gauth.LocalWebserverAuth()
            gauth.SaveCredentialsFile(token)
        return gauth
Exemple #16
0
def initial_gdrive():
    '''
    Authorize and refresh Google Drive token.
    Reference: https://stackoverflow.com/a/24542604/10114014
    '''
    gauth = GoogleAuth()
    # Try to load saved client credentials
    gauth.LoadCredentialsFile("mycreds.txt")
    if gauth.credentials is None:
        # Authenticate if they're not there
        gauth.LocalWebserverAuth()
    elif gauth.access_token_expired:
        # Refresh them if expired
        gauth.Refresh()
    else:
        # Initialize the saved creds
        gauth.Authorize()
    # Save the current credentials to a file
    gauth.SaveCredentialsFile("mycreds.txt")
    return GoogleDriveWithBytes(gauth)
Exemple #17
0
    def __init__(self, destination_root_directory=DEFAULT_DESTINATION_ROOT):
        """
        Initialize logging and Google Drive authentication.
        """

        # Enable logging
        logging.basicConfig(
            format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            level=logging.INFO)

        self.logger = logging.getLogger(__name__)

        # self.destination_root_directory = destination_root_directory
        self.destination_root_directory = self.DEFAULT_DESTINATION_ROOT
        # TODO make directory name configurable
        # this will require a parsing of the directory path
        # all concerned subfolders will have to be looked up recursively in the file_exists function

        gauth = GoogleAuth()
        gauth.LocalWebserverAuth()
        self.drive = GoogleDrive(gauth)
Exemple #18
0
class Drive(object):
    def __init__(self):
        self.logger = logging.getLogger(__name__)
        self.login()

    def login(self):
        self.gauth = GoogleAuth()

        self.gauth.LoadCredentialsFile("mycreds.txt")
        self.logger.debug("Loading credentials")

        if self.gauth.credentials is None:
            self.logger.debug("First authentication")
            # Authenticate if they're not there
            self.gauth.LocalWebserverAuth()
        elif self.gauth.access_token_expired:
            self.logger.debug("Token has expired, refreshing")
            # Refresh them if expired
            self.gauth.Refresh()
        else:
            self.logger.debug("Connected")
            # Initialize the saved creds
            self.gauth.Authorize()
        # Save the current credentials to a file
        self.gauth.SaveCredentialsFile("mycreds.txt")

        # Create GoogleDrive instance with authenticated GoogleAuth instance
        self.drive = GoogleDrive(self.gauth)

    def find_folders(self, folder_name):
        file_list = self.drive.ListFile({
            "q":
            "title='{}' and mimeType contains 'application/vnd.google-apps.folder' and trashed=false"
            .format(folder_name)
        }).GetList()
        return file_list

    def create_subfolder(self, folder, sub_folder_name):
        new_folder = self.drive.CreateFile({
            "title":
            "{}".format(sub_folder_name),
            "mimeType":
            "application/vnd.google-apps.folder",
        })
        if folder is not None:
            new_folder["parents"] = [{u"id": folder["id"]}]
        new_folder.Upload()
        self.logger.debug("Folder created {}/{}".format(
            folder, sub_folder_name))
        return new_folder

    def upload_files_to_folder(self, fnames, folder):
        for fname in fnames:
            nfile = self.drive.CreateFile({
                "title": os.path.basename(fname),
                "parents": [{
                    u"id": folder["id"]
                }]
            })
            nfile.SetContentFile(fname)
            nfile.Upload()
Exemple #19
0
 def test_05_ConfigFromSettingsWithoutOauthScope(self):
   # Test if authentication works without oauth_scope
   ga = GoogleAuth('pydrive2/test/settings/test_oauth_test_05.yaml')
   ga.LocalWebserverAuth()
   self.assertEqual(ga.access_token_expired, False)
   time.sleep(1)
Exemple #20
0
# /////////////////////////
# MAIN ////////////////////
# /////////////////////////

print("*******************************************************************************************")
print("running microprojectgallery.py with CWD: " + os.getcwd())

if downloadCSV:
    
    # grab CSV from gdrive
    # --------------------

    # authenticate
    gauth = GoogleAuth()
    gauth.LocalWebserverAuth() # Creates local webserver and auto handles authentication.
    drive = GoogleDrive(gauth)

    # Create GoogleDriveFile instance with file id of file1.
    sheet = drive.CreateFile({'id': spreadsheetID})
    print('title: %s, exportLink: %s' % (sheet['title'], sheet['exportLinks']['text/csv']))
    # print(sheet.GetContentString())

    downloadCSVURL = sheet['exportLinks']['text/csv']
    r = requests.get(downloadCSVURL, allow_redirects=True)
    open(savedSheetName, 'wb').write(r.content)

    imageTest = drive.CreateFile({'id': "1hAcgM_VgLbkZgloqu0iC5V2-nVTyWe2J"})

# load dataframe
df = pd.read_csv(savedSheetName)
Exemple #21
0
from pydrive2.auth import GoogleAuth
from pydrive2.drive import GoogleDrive

gauth = GoogleAuth()
gauth.LocalWebserverAuth(
)  # client_secrets.json need to be in the same directory as the script
drive = GoogleDrive(gauth)
 def Press_Authenticate(self, instance):
     gauth = GoogleAuth()
     gauth.LocalWebserverAuth()
     GDrive = GoogleDrive(gauth)  # Google Drive Class Object
     return
def authenticate():
    gauth = GoogleAuth(settings_file="maintenance/settings.yaml")
    gauth.LocalWebserverAuth()
    return GoogleDrive(gauth)
Exemple #24
0
class GDriveServerNode(object):
    folder_mime_type = 'application/vnd.google-apps.folder'
    folder_url_format = 'https://drive.google.com/drive/folders/{}'
    file_url_format = 'https://drive.google.com/uc?id={}'

    def __init__(self):
        settings_yaml = rospy.get_param('~settings_yaml', None)
        self.share_type = rospy.get_param('~share_type', 'anyone')
        self.share_value = rospy.get_param('~share_value', 'anyone')
        self.share_role = rospy.get_param('~share_role', 'reader')
        self.share_with_link = rospy.get_param('~share_with_link', True)
        auth_max_trial = rospy.get_param('~auth_max_trial', -1)
        auth_wait_seconds = rospy.get_param('~auth_wait_seconds', 10.0)
        if settings_yaml is not None:
            self.gauth = GoogleAuth(settings_yaml)
        else:
            rospy.logerr('param: ~settings_yaml is not correctly set.')
            sys.exit(1)

        rospy.loginfo('Google drive authentication starts.')
        auth_success = False
        auth_count = 0
        while (not auth_success
               and (auth_max_trial < 0 or auth_count < auth_max_trial)):
            try:
                self.gauth.LocalWebserverAuth()
                auth_success = True
            except ServerNotFoundError as e:
                rospy.logerr('Authentication failed: {}'.format(e))
                auth_count = auth_count + 1
                time.sleep(auth_wait_seconds)
        if not auth_success:
            rospy.logerr(
                'Authentication failed {} times.'.format(auth_max_trial))
            sys.exit(1)
        self.gdrive = GoogleDrive(self.gauth)
        rospy.loginfo('Google drive authentication finished.')
        self.upload_server = rospy.Service('~upload', Upload, self._upload_cb)
        self.upload_multi_server = rospy.Service('~upload_multi',
                                                 MultipleUpload,
                                                 self._upload_multi_cb)
        rospy.loginfo('Finish initialization, Server started.')

    def _upload_cb(self, req):
        timestamp = '{0:%Y%m%d%H%M%S}'.format(datetime.datetime.now())
        parents_path = req.parents_path
        parents_id = req.parents_id

        # response initialization
        res = UploadResponse()
        res.success = False
        res.file_id = ''
        res.file_url = ''

        if parents_id and parents_path:
            rospy.logerr('parents_path and parents_id is both set.')
            rospy.logerr(
                'parents_id: {} is selected to upload.'.format(parents_id))
            parents_path = ''

        if parents_path:
            try:
                parents_id = self._get_parents_id(parents_path, mkdir=True)
            except (ValueError, ApiRequestError, ServerNotFoundError) as e:
                rospy.logerr(e)
                rospy.logerr(
                    'Failed to get parents_id: {}'.format(parents_path))
                return res
        # root
        elif parents_id == '' and parents_path == '':
            parents_id = ''

        if req.use_timestamp_folder:
            try:
                parents_id = self._get_parents_id([timestamp],
                                                  parents_id=parents_id,
                                                  mkdir=True)
            except (ValueError, ApiRequestError, ServerNotFoundError) as e:
                rospy.logerr(e)
                rospy.logerr('Failed to get parents_id: {} in {}'.format(
                    timestamp, self.folder_url_format.format(parents_id)))
                return res

        success, file_id, file_url = self._upload_step(
            req.file_path, req.file_title, parents_id,
            req.use_timestamp_file_title, timestamp)
        res.success = success
        res.file_id = file_id
        res.file_url = file_url
        res.parents_id = parents_id
        res.parents_url = self.folder_url_format.format(parents_id)
        return res

    def _upload_multi_cb(self, req):
        timestamp = '{0:%Y%m%d%H%M%S}'.format(datetime.datetime.now())
        parents_path = req.parents_path
        parents_id = req.parents_id

        # response initialization
        res = MultipleUploadResponse()
        res.successes = [False] * len(req.file_titles)
        res.file_ids = [''] * len(req.file_titles)
        res.file_urls = [''] * len(req.file_titles)

        if parents_id and parents_path:
            rospy.logerr('parents_path and parents_id is both set.')
            rospy.logerr(
                'parents_id: {} is selected to upload.'.format(parents_id))
            parents_path = ''

        if parents_path:
            try:
                parents_id = self._get_parents_id(parents_path, mkdir=True)
            except (ValueError, ApiRequestError, ServerNotFoundError) as e:
                rospy.logerr(e)
                rospy.logerr(
                    'Failed to get parents_id: {}'.format(parents_path))
                return res
        # root
        elif parents_id == '' and parents_path == '':
            parents_id = ''

        if req.use_timestamp_folder:
            try:
                parents_id = self._get_parents_id([timestamp],
                                                  parents_id=parents_id,
                                                  mkdir=True)
            except (ValueError, ApiRequestError, ServerNotFoundError) as e:
                rospy.logerr(e)
                rospy.logerr('Failed to get parents_id: {} in {}'.format(
                    timestamp, self.folder_url_format.format(parents_id)))
                return res

        for i, (file_path,
                file_title) in enumerate(zip(req.file_paths, req.file_titles)):
            success, file_id, file_url = self._upload_step(
                file_path, file_title, parents_id,
                req.use_timestamp_file_title, timestamp)
            res.successes[i] = success
            res.file_ids[i] = file_id
            res.file_urls[i] = file_url
        res.parents_id = parents_id
        res.parents_url = self.folder_url_format.format(parents_id)
        return res

    def _upload_step(self,
                     file_path,
                     file_title,
                     parents_id,
                     use_timestamp_file_title=False,
                     timestamp=None):
        file_title = file_title if file_title else file_path.split('/')[-1]
        file_path = os.path.expanduser(file_path)
        if use_timestamp_file_title:
            file_title = '{}_{}'.format(timestamp, file_title)

        success = False
        file_id = ''
        file_url = ''
        folder_url = self.folder_url_format.format(parents_id)
        try:
            file_id = self._upload_file(file_path,
                                        file_title,
                                        parents_id=parents_id)
            file_url = self.file_url_format.format(file_id)
            success = True
            rospy.loginfo('Success to upload: {} -> {}'.format(
                file_path, file_url))
        except (OSError, ApiRequestError, ServerNotFoundError) as e:
            rospy.logerr(e)
            rospy.logerr('Failed to upload: {} -> {}'.format(
                file_path, folder_url))
        return success, file_id, file_url

    def _upload_file(self, file_path, file_title, parents_id=None):
        if not os.path.exists(file_path):
            raise OSError('File not found: {}'.format(file_path))
        rospy.loginfo('Start uploading a file: {}'.format(file_title))
        if parents_id:
            gfile = self.gdrive.CreateFile({'parents': [{'id': parents_id}]})
        else:
            gfile = self.gdrive.CreateFile()
        gfile.SetContentFile(file_path)
        gfile['title'] = file_title
        gfile.Upload()
        gfile.InsertPermission({
            'type': self.share_type,
            'value': self.share_value,
            'role': self.share_role,
            'withLink': self.share_with_link,
        })
        rospy.loginfo('Finish uploading a file: {}'.format(file_title))
        return gfile['id']

    def _upload_folder(self, folder_title, parents_id=None):
        rospy.loginfo('Start making a folder: {}'.format(folder_title))
        if parents_id:
            gfolder = self.gdrive.CreateFile({
                'title':
                folder_title,
                'parents': [{
                    'id': parents_id
                }],
                'mimeType':
                'application/vnd.google-apps.folder'
            })
        else:
            gfolder = self.gdrive.CreateFile({
                'title':
                folder_title,
                'mimeType':
                'application/vnd.google-apps.folder'
            })
        gfolder.Upload()
        rospy.loginfo('Finish making a folder: {}'.format(folder_title))
        return gfolder['id']

    def _get_parents_id(self, parents_path, parents_id=None, mkdir=False):
        if parents_path == '':
            return None

        if not isinstance(parents_path, list):
            parents_path = [p for p in parents_path.split('/') if p != '']

        folder_title = parents_path[0]
        parent = parents_id if parents_id else 'root'
        gfiles = self.gdrive.ListFile(
            {'q': "'{}' in parents and trashed=false".format(parent)})
        gfiles = gfiles.GetList()
        gfolders = []
        for gf in gfiles:
            if (gf['mimeType'] == self.folder_mime_type
                    and gf['title'] == folder_title):
                gfolders.append(gf)

        if len(parents_path) == 1:
            if len(gfolders) > 0:
                return gfolders[0]['id']
            if mkdir:
                folder_id = self._upload_folder(folder_title,
                                                parents_id=parents_id)
                return folder_id
            else:
                raise ValueError(
                    'Folder is not found: {}'.format(folder_title))
        else:
            if len(gfolders) > 0 or mkdir:
                if len(gfolders) > 0:
                    next_parents_id = gfolders[0]['id']
                elif mkdir:
                    next_parents_id = self._upload_folder(
                        folder_title, parents_id=parents_id)
                folder_id = self._get_parents_id(parents_path[1:],
                                                 parents_id=next_parents_id,
                                                 mkdir=mkdir)
                return folder_id
            else:
                raise ValueError('folder is not found: {}', folder_title)
Exemple #25
0
class Pinguin(QMainWindow):
    login_signal = pyqtSignal()

    def __init__(self):
        super().__init__()
        self.db = PinguinDB()
        self.trello = Trello()
        self.auth = None
        self.google_client = GoogleClient()
        self.login_signal.connect(self.login_success)
        self.login_menu = Login_Window(self.login_signal, self.db, self.trello)
        self.main_window = Main_Menu(self.db, self.trello, self.google_client)

        #self.mutex = QMutex()

    @pyqtSlot()
    def login_success(self):
        self.main_window.show()
        self.login_menu.close()
        if self.trello.client == None:
            print("setting up trello client")
            print(self.db.user.user_id)
            self.trello.action_setup2(self.db.user.user_id)
            print("trello client all set")

        print("setting up google auth")
        #print(self.main_window.ui.google_client)
        self.auth = GoogleAuth()
        #print(auth)
        # Try to load saved client credentials
        self.auth.LoadCredentialsFile("Credentials.json")

        if self.auth.credentials is None:
            print("no creds")
            # Authenticate if they're not there
            self.auth.LocalWebserverAuth()

        elif self.auth.access_token_expired:
            print("creds expired")
            # Refresh them if expired
            self.auth.LocalWebserverAuth()
            #self.auth.Refresh()

            print("creds renewed")

        else:
            print("new creds")
            # Initialize the saved creds
            self.auth.Authorize()

        # Save the current credentials to a file
        #self.auth.SaveCredentialsFile("Credentials.json")
        print("authorization complete")

        self.google_client.set_client(self.auth)
        self.main_window.ui.google_client = self.google_client
        #print(self.main_window.ui.google_client)
        #self.main_window.ui.set_google_client(GoogleClient(self.auth))
        #self.main_window.show()
        print("heresdasd")
        self.main_window.ui.widgets_refresh()
        self.main_window.ui.widgets_timer.start(30000)

    def run(self):
        self.login_menu.show()
from pydrive2.auth import GoogleAuth #potrebna knjiđnica PyDrive2, ki se jo dobi z pip install pydrive2
from pydrive2.drive import GoogleDrive

gauth = GoogleAuth() #Potrebno je imeti na kompu ali client_secrets.json ali pa mycreds.txt, ki ne pridejo s knjižnco zraven
# Try to load saved client credentials
gauth.LoadCredentialsFile("mycreds.txt")
if gauth.credentials is None:
    # Authenticate if they're not there
    gauth.LocalWebserverAuth()
elif gauth.access_token_expired:
    # Refresh them if expired
    gauth.Refresh()
else:
    # Initialize the saved creds
    gauth.Authorize()
# Save the current credentials to a file
gauth.SaveCredentialsFile("mycreds.txt")

drive = GoogleDrive(gauth)

##FUNKCIJE
def delete_file(file_id):
  file1 = drive.CreateFile({'parents': [{'id': '1eeA-y9DjF4zOuH4z5wkOB5nSehRtGneV'}],'id': file_id})
  file1.Delete()

def create_file(name,content):
  file1 = drive.CreateFile({'title': name,'parents': [{'id': '1eeA-y9DjF4zOuH4z5wkOB5nSehRtGneV'}]})  # Create GoogleDriveFile instance with title 'Hello.txt'.
  file1.SetContentString(content,encoding="utf-8")
  file1.Upload()
  print("File was created under the id %s" %(file1['id']))
  return file1
Exemple #27
0
          'https://www.googleapis.com/auth/drive.file',
          'https://www.googleapis.com/auth/youtube.force-ssl']

url = ['https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable']
id ='*****@*****.**'
key = base64.b64decode(open("configs\private_key.json", "r").read())
live_3d = False
# creds = Credentials.from_json_keyfile_name('client_secrets.json', scopes)
# service = build('drive', 'v2', credentials=creds)

g_login = GoogleAuth()
#g_login.creds = creds
g_login.LoadCredentialsFile('configs\mycreds.txt')

if g_login.credentials is None:
    g_login.LocalWebserverAuth()
elif g_login.access_token_expired:
    g_login.Refresh()
else:
    g_login.Authorize()

g_login.SaveCredentialsFile('configs\mycreds.txt')
drive = GoogleDrive(g_login)
folder_id = '1eAnQD9mV0xhqaMVoeSGA06NrU1R6ik7Y'

#====polling loop for youtube; update manually for now.====
def poll_loop(channel_id):
    # Disable OAuthlib's HTTPS verification when running locally.
    # *DO NOT* leave this option enabled in production.
    os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"