Пример #1
0
def download(file_id, path=DOWNLOAD_PATH):
    gauth = GoogleAuth()
    gauth.LocalWebserverAuth()
    drive = GoogleDrive(gauth)

    file_list = drive.ListFile({'q':"'%s' in parents and trashed=false" % file_id}).GetList()
    for file1 in file_list:
        if file1['title'].lower().endswith(('.jpg','.jpeg','.png')):
            imgf = drive.CreateFile({'id':file1['id']})
            imgf.GetContentFile(DOWNLOAD_PATH + '/'+ file1['title'])
Пример #2
0
def googleTrends():
    pictureName = 'trendLine.png'
    ######### search keywords and trends #########
    pytrends = TrendReq(hl='en-MY')
    #Keyword to compare
    kw_list = ["Thermometer", 'Sanitizer', "Face mask"]
    #configuration
    pytrends.build_payload(kw_list,
                           cat=0,
                           timeframe='today 12-m',
                           geo='MY',
                           gprop='')
    #get trendline
    data = pytrends.interest_over_time()
    #remove 'isPartial' column
    data = data.drop(labels=['isPartial'], axis='columns')
    image = data.plot(title='Trendline of Keywords')
    fig = image.get_figure()
    fig.savefig(pictureName)

    ######## Authentication and trendline upload ########
    g_login = GoogleAuth()
    #try to load credentials
    g_login.LoadCredentialsFile("mycreds.txt")
    if g_login.credentials is None:
        # Authenticate if they're not there
        g_login.LocalWebserverAuth()
    elif g_login.access_token_expired:
        #refresh if expired
        g_login.Refresh()
    else:
        #Initialize creds
        g_login.Authorize()
    g_login.SaveCredentialsFile("mycreds.txt")

    #removing old file and replacing with updated
    drive = GoogleDrive(g_login)
    file_list = drive.ListFile({
        'q': "'' in parents and trashed=False"
    }).GetList()
    for files in file_list:
        print(files['title'])
        if files['title'] == pictureName:
            files.Delete()
            trendLine = drive.CreateFile({'parents': [{'id': ''}]})
            trendLine.SetContentFile(pictureName)
            trendLine.Upload()
            break
        else:
            trendLine = drive.CreateFile({'parents': [{'id': ''}]})
            trendLine.SetContentFile(pictureName)
            trendLine.Upload()
            break
    print('Created file %s with mimeType %s' %
          (trendLine['title'], trendLine['mimeType']))
Пример #3
0
def get_all_ids():
    from pydrive.auth import GoogleAuth
    from pydrive.drive import GoogleDrive

    GoogleAuth.DEFAULT_SETTINGS["client_config_file"] = os.path.join(
        settings.ROOT_DIR.root, r"secrets/GoogleSheetsClient_id.json")
    GoogleAuth.DEFAULT_SETTINGS["save_credentials_backend"] = "file"
    GoogleAuth.DEFAULT_SETTINGS["save_credentials"] = True
    GoogleAuth.DEFAULT_SETTINGS["save_credentials_file"] = os.path.join(
        settings.ROOT_DIR.root, r"secrets/GoogleSheetsClient_id_out.json")
    print(GoogleAuth.DEFAULT_SETTINGS)
    gauth = GoogleAuth()
    gauth.LocalWebserverAuth()
    NATIONALS_FOLDER = "0BwvK5gYQ6D4nTDRtY1prZG12UU0"
    # Create GoogleDrive instance with authenticated GoogleAuth instance
    drive = GoogleDrive(gauth)
    # Search parameters:
    #     https://developers.google.com/drive/api/v3/search-parameters
    national_folders = drive.ListFile({
        "q": f"'{NATIONALS_FOLDER}' in parents"
    }).GetList()
    for region_folder in national_folders:
        print(f"title: {region_folder['title']}, id: {region_folder['id']}")
        print(region_folder)
        REGION_ID = region_folder["id"]
        regional_folders = drive.ListFile({
            "q": f"'{REGION_ID}' in parents"
        }).GetList()
        if not regional_folders:
            continue
        for chapter_folder in regional_folders:
            print(
                f"    title: {chapter_folder['title']}, id: {chapter_folder['id']}"
            )
            CHAPTER_ID = chapter_folder["id"]
            chapter_items = drive.ListFile({
                "q": f"'{CHAPTER_ID}' in parents"
            }).GetList()
            if not chapter_items:
                continue
            for item in chapter_items:
                print(f"        title: {item['title']}, id: {item['id']}")
Пример #4
0
 def test_01_Files_List_GetList(self):
   drive = GoogleDrive(self.ga)
   flist = drive.ListFile({'q': "title = '%s' and trashed = false"
                                % self.title})
   files = flist.GetList()  # Auto iterate every file
   for file1 in self.file_list:
     found = False
     for file2 in files:
       if file1['id'] == file2['id']:
         found = True
     self.assertEqual(found, True)
Пример #5
0
def priv_get_file_from_drive(title):
    gauth = GoogleAuth()
    gauth.LocalWebserverAuth()
    drive = GoogleDrive(gauth)
    file_list = drive.ListFile({
        'q': "'root' in parents and trashed=false"
    }).GetList()
    for files in file_list:
        if files['title'] == title:
            return files
    return 0
Пример #6
0
def importGoogleDriveFile(fileName):
    auth.authenticate_user()
    gauth = GoogleAuth()
    gauth.credentials = GoogleCredentials.get_application_default()
    drive = GoogleDrive(gauth)
    file_list = drive.ListFile({
        'q': "'root' in parents and trashed=false"
    }).GetList()
    for file in file_list:
        if file['title'] == fileName:
            file.GetContentFile(fileName)
Пример #7
0
def ListFile(folder_id):
    gauth = GoogleAuth()
    scope = ['https://www.googleapis.com/auth/drive']
    gauth.credentials = ServiceAccountCredentials.from_json_keyfile_name(
        'ClipFetcher-SERVICE-ACCOUNT.json', scope)
    drive = GoogleDrive(gauth)

    query = '\'' + folder_id + '\' in parents and trashed=false'
    file_list = drive.ListFile({'q': query}).GetList()
    for file in file_list:
        print('Title: %s, ID: %s' % (file['title'], file['id']))
Пример #8
0
def Download(nome_arquivo): 

    gauth = GoogleAuth()
    gauth.LocalWebserverAuth() #client_secrets.json need to be in the same directory as the script
    drive = GoogleDrive(gauth)
    arquivo = "'"+nome_arquivo+"'"
    files = drive.ListFile({'q': "title:" + arquivo}).GetList()
    for item in files:
        print('%s Downloaded' % (item['title']))
        download_mimetype = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        item.GetContentFile(item['title']+"_COPIA.xlsx", mimetype = download_mimetype)
Пример #9
0
    def test_last_photos_picker_gdrive_uploader(self, filters, expected_files):
        """
        Test with LastPhotosPicker and GDriveUploader

        :param array filters: filters to use
        :param dict expected_files: expected files with hash of their content
        """
        if not os.path.isfile(self.gdrive_creds_filepath):
            txt = "mycreds.json file is missing"
            raise SkipTest(txt)

        gauth = self.create_gdrive_auth()
        picker = LastPhotosPicker(self.sample_dir, 5, -1)
        uploader = GDriveUploader(gauth, self.remote_test_dir)

        photo_picker = PhotosPicker(picker, filters, uploader)
        photo_picker.run()

        gdrive = GoogleDrive(gauth)

        query = "mimeType = 'application/vnd.google-apps.folder'" \
                + " and title = '{dir}' and trashed=false"
        query = query.format(dir=self.remote_test_dir)
        folders = gdrive.ListFile({"q": query}).GetList()

        self.assertEqual(1, len(folders))

        query = "'{folder_id}' in parents and trashed=false"
        files = gdrive.ListFile({
            "q": query.format(folder_id=folders[0]['id'])
        }).GetList()
        actual_files = {}
        for file_metadata in files:
            gd_file = gdrive.CreateFile({'id': file_metadata['id']})
            fullpath = self.target_dir + '/' + file_metadata['title']
            gd_file.GetContentFile(fullpath)
            md5 = self._compute_file_md5(fullpath)
            actual_files[file_metadata['title']] = md5
            os.remove(fullpath)

        self.assertEqual(expected_files, actual_files)
Пример #10
0
class DriveHandler:
    def __init__(self):
        self.gauth = GoogleAuth()
        self.drive = GoogleDrive(self.gauth)

    def get_list(self, parent_id: str):
        return self.drive.ListFile({
            'q':
            f"'{parent_id}' in parents and trashed=false"
        }).GetList()

    def search_file(self, file_name: str, parent_id: str) -> Optional[str]:
        file_list = self.get_list(parent_id)

        for file in file_list:
            if file['title'] == f"{file_name}.mp3":
                return file['id']

        return None

    def upload_file(self, file_path: Path, parent_id: str):
        print(f"Uploading {file_path.name}")
        self.delete_file(file_path.name, parent_id)

        file = self.drive.CreateFile({
            'parents': [{
                'kind': 'drive#childList',
                'id': parent_id
            }],
            'title':
            str(file_path.name)
        })
        file.SetContentFile(str(file_path.absolute()))
        file.Upload()

    def copy_dir(self, directory: Path, parent_id: str):
        file_paths: List[Path] = []
        for file in directory.iterdir():
            if file.is_file():
                file_paths.append(file)

        for file in file_paths:
            self.upload_file(file, parent_id)

    def delete_file(self, file_name: str, parent_id: str) -> bool:
        search_result = self.search_file(file_name, parent_id)

        if search_result is not None:
            file_to_be_deleted = self.drive.CreateFile({'id': search_result})

            file_to_be_deleted.Trash()

        return bool(search_result)
Пример #11
0
def list(request):
    gauth = GoogleAuth()
    gauth.DEFAULT_SETTINGS[
        'client_config_file'] = settings.GOOGLE_DRIVE_STORAGE_JSON_KEY_FILE
    # Creates local webserver and auto handles authentication.
    gauth.LocalWebserverAuth()
    drive = GoogleDrive(gauth)
    file_list = drive.ListFile({
        'q': "'root' in parents and trashed=false"
    }).GetList()
    pprint(file_list)
    return render(request, 'list.html', {'files': file_list})
Пример #12
0
def tester():
    folderid = None
    gauth = GoogleAuth()
    gauth.LocalWebserverAuth()
    drive = GoogleDrive(gauth)
    file_list = drive.ListFile({
        'q': "'root' in parents and trashed=false"
    }).GetList()
    for file in file_list:
        if (file['title'] == "vira"):
            folderid = file['id']
            break
    file_list2 = drive.ListFile({
        'q':
        "'%s' in parents  and trashed=false" % folderid
    }).GetList()
    file_list2 = list(file_list2)
    print(len(file_list2))
    print(file_list2[1]['id'])
    file = drive.CreateFile({'id': file_list2[1]['id']})
    file.GetContentFile('download/' + file_list2[1]['title'])
def auth_google():
    # Google Oauth 認証を行う
    gauth = GoogleAuth()

    gauth.LoadCredentialsFile('credentials.json')
    if gauth.credentials is None:
        # Authenticate if they're not there
        # gauth.LocalWebserverAuth()
        gauth.CommandLineAuth()
    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('credentials.json')

    drive = GoogleDrive(gauth)

    """
    # Git > WeatherExtractor 内のファイル一覧を ID と共に表示
    drive_folder_id = '1X_lNjACsoUWbnz3Y-PSoP5e4hplV_f4d'
    query = '"{0}" in parents and trashed=false'.format(drive_folder_id)
    file_list = drive.ListFile({'q': query}).GetList()
    for file1 in file_list:
        print('title: %s, id: %s' % (file1['title'], file1['id']))
        print(file1)
    """

    # WeatherResult.csv を操作してみる
    # drive_csv_id = '1sCCMDIAMfHTt013R28lVxQj31VlgMopV'
    # file = drive.CreateFile({'id': drive_csv_id})
    # file = drive.CreateFile({'title': 'a.csv',
    #                          'parents': [{'id': '1X_lNjACsoUWbnz3Y-PSoP5e4hplV_f4d'}]})
    drive_folder_id = '1X_lNjACsoUWbnz3Y-PSoP5e4hplV_f4d'
    query = '"{0}" in parents and trashed=false'.format(drive_folder_id)
    file_list = drive.ListFile({'q': query}).GetList()
    for file in file_list:
        if file['title'] == 'WeatherResult.csv':  # WeatherResult.csv を取得してダウンロードする
            content = file.GetContentString()
            file2 = file
            # print(file2)
            break
    # print(content)
    # print(type(content))
    file2.GetContentFile('a.csv')  # csv ファイルとしてダウンロード
    file2.Trash()  # WeatherResult.csv をゴミ箱に移動
    file2.UnTrash()  # ゴミ箱の外に移動?
    file2.Delete()  # Hard Delete
    # file.GetContentFile('a.txt')

    return drive
Пример #14
0
	def getgooglefileid(self,title):

		print os.getcwd()
		self.ga = GoogleAuth(self.DBConfig.googleyaml)
		self.ga.LocalWebserverAuth()
		drive = GoogleDrive(self.ga)
		flist = drive.ListFile({'q': "title = '%s' and trashed = false"%title})
		files = flist.GetList() 
		if len(files)==0:
			return False
		else:
			return files[0]['id']
Пример #15
0
class GdriveUploader:
    def __init__(self):
        self.gauth = GoogleAuth()
        # Try to load saved client credentials
        self.gauth.LoadCredentialsFile("mycreds.txt")
        if self.gauth.credentials is None:
            # Authenticate if they're not there
            self.gauth.LocalWebserverAuth()
        elif self.gauth.access_token_expired:
            # Refresh them if expired
            self.gauth.Refresh()
        else:
            # Initialize the saved creds
            self.gauth.Authorize()
        # Save the current credentials to a file
        self.gauth.SaveCredentialsFile("mycreds.txt")

        self.drive = GoogleDrive(self.gauth)

    def upload(self, filename, path, destination_folder):
        directory = self.get_drive_folder(destination_folder)
        f = self.drive.CreateFile({
            "title": filename,
            "parents": [{
                "id": directory
            }]
        })
        f.SetContentFile(path)
        f.Upload()

    def get_folder_id(self, foldername):
        file_list = self.drive.ListFile({
            "q":
            "'root' in parents and trashed=false"
        }).GetList()
        id = None
        for file1 in file_list:
            if file1["title"] == foldername:
                id = file1["id"]
        return id

    def get_drive_folder(self, foldername):
        id = self.get_folder_id(foldername)
        if id == None:
            new_folder = self.drive.CreateFile({
                "title":
                foldername,
                "mimeType":
                "application/vnd.google-apps.folder"
            })
            new_folder.Upload()
            id = self.get_folder_id(foldername)
        return id
Пример #16
0
def download(drive_folder_id):
    gauth = GoogleAuth()
    gauth.LocalWebserverAuth()  # client_secrets.json need to be in the same directory as the script
    drive = GoogleDrive(gauth)
    files = drive.ListFile({'q': f"'{drive_folder_id}' in parents and trashed=false"}).GetList()

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

    for i, file1 in enumerate(sorted(files, key=lambda x: x['title'])):
        print('Downloading {} from GDrive ({}/{})'.format(file1['title'], i, len(files)))
        file1.GetContentFile(os.path.join(DATA_DIR, file1['title']))
Пример #17
0
class PlayEvent(object):
    def __init__(self):
        self.folderid = None    
        gauth = GoogleAuth()
        gauth.LocalWebserverAuth()
        self.liveThreads = []
        self.drive = GoogleDrive(gauth)
        file_list = self.drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList()                            
        for file in file_list:
            if(file['title'] == "vira"):
                folderid = file['id']
                break
        file_list2 = self.drive.ListFile({'q': "'%s' in parents  and trashed=false" % folderid}).GetList()
        self.cursor = list(file_list2)
           
    def download(self, id, title):
        if(os.path.exists('buffer/'+title)):
            return 'buffer/'+title
        file = self.drive.CreateFile({'id' : id})
        file.GetContentFile('buffer/'+title)
        return 'buffer/'+title
Пример #18
0
def fileOperation(table, data, filename, operation, gauth):
    try:
        print("-- PROCESS %s --" % filename)

        gauth.LocalWebserverAuth()
        drive = GoogleDrive(gauth)
        try:
            filepath = './tokobackup/' + filename
            with open(filepath,'r') as f:
                try:
                    datajson = json.load(f)
                except:
                    datajson = {}
                    datajson[table] = []
        except:
                datajson = {}
                datajson[table] = []
        if(operation != "delete"):
            datajson[table].append({
                'operation': operation,
                'id_transaksi': str(data[0]),
                'no_rekening': str(data[1]),
                'tgl_transaksi': str(data[2]),
                'total_transaksi': str(data[3]),
                'status': str(data[4])
            })
        else:
            datajson[table].append({
                'operation': operation,
                'id_transaksi': str(data[0])
            })
        with open(filepath, 'w') as outfile:
            json.dump(datajson, outfile)

        file_list = drive.ListFile({'q': "'%s' in parents" % folder_toko}).GetList()
        try:
            for file1 in file_list:
                if file1['title'] == filename:
                    file1.Delete()
        except:
            pass

        print("-- PROCESS %s --" % filename)

        file1 = drive.CreateFile({'title': filename, 'parents':
            [{"kind": "drive#fileLink", "id": folder_toko}]})
        file1.SetContentString(json.dumps(datajson))
        file1.Upload()

    except (pymysql.Error, pymysql.Warning) as e:
        print(e)

    return 1
Пример #19
0
def getlist():
    gauth = GoogleAuth()
    gauth.LocalWebserverAuth(
    )  # Creates local webserver and auto handles authentication.

    drive = GoogleDrive(gauth)
    file_list = drive.ListFile({
        'q':
        "'{}' in parents and trashed=false".format(
            app_settings['gdrive_parent_folder'])
    }).GetList()
    return file_list
Пример #20
0
    def upload_file_to_gdrive(filepath, gdrive_dir=''):

        if filepath == '':
            return

        filename = filepath.split('/')[-1]

        GoogleAuth.DEFAULT_SETTINGS['client_config_file'] = '../doc/client_secrets.json'
        gauth = GoogleAuth()

        # Try to load saved client credentials
        gauth.LoadCredentialsFile('../doc/gdrive_creds.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('../doc/gdrive_creds.txt')

        drive = GoogleDrive(gauth)

        file_list = drive.ListFile(
            {'q': "trashed=false", 'includeItemsFromAllDrives': True,
             'supportsAllDrives': True, 'corpora': 'allDrives'}).GetList()

        # folder_id = '12Tcsl57iFVvQyCPr49-VzUfcbHcrXU34'
        # file_list = drive.ListFile({'q': f"parents in '{folder_id}' and trashed=false", 'includeItemsFromAllDrives':
        # True,
        # 'supportsAllDrives': True, 'corpora': 'allDrives'}).GetList()
        folder_id = ''
        for gf in file_list:
            if gf['title'] == gdrive_dir and gf['shared'] is True:
                folder_id = gf['id']
                break

        if folder_id != '':
            f = drive.CreateFile({'title': filename, 'corpora': 'allDrives', 'includeItemsFromAllDrives': True,
                                  'supportsAllDrives': True,
                                  'parents': [{'kind': 'drive#fileLink',
                                               'id': folder_id}]})
        else:
            f = drive.CreateFile({'title': filename})

        f.SetContentFile(filepath)
        f.Upload(param={'supportsAllDrives': True})

        f = None
Пример #21
0
class MyGoogleDrive():
    def __init__(self, cred_path):

        gauth = GoogleAuth()
        gauth.LoadCredentialsFile(cred_path)

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

        gauth.SaveCredentialsFile(cred_path)
        self.drive = GoogleDrive(gauth)

    def push(self, file_path, folder_id):
        try:
            filename = os.path.basename(file_path)
            Logs.Print('Uploading file: ' + str(filename) +
                       " on gdrive folder: " + str(folder_id))
            textfile = self.drive.CreateFile({
                'title':
                filename,
                'mimeType':
                'image/jpg',
                "parents": [{
                    "kind": "drive#fileLink",
                    "id": folder_id
                }]
            })
            textfile.SetContentFile(file_path)
            textfile.Upload()
        except Exception as e:
            Logs.Print("Exception: " + str(e))

    def cleanup(self, days, gdrive_folder_ids):
        try:
            date_N_days_ago = datetime.now() - timedelta(days=days)
            files = self.drive.ListFile({
                "q":
                "trashed = false and modifiedDate < '" +
                str(date_N_days_ago).split(' ')[0] + "'",
                "maxResults":
                1000
            }).GetList()
            for file in files:
                if file['id'] not in gdrive_folder_ids:
                    Logs.Print(file['title'] + " will be deleted")
                    file.Delete()
        except Exception as e:
            Logs.Print("Exception: " + str(e))
class GoogleDriveApiClient():
    def __init__(self):
        '''Creating a google drive authenticated object so that we
        can pass it around in google_upload.py to do various tasks. Need
        to have a json like object in environment variables that holds the
        service account credentials'''
        gauth = GoogleAuth()
        scope = ['https://www.googleapis.com/auth/drive']

        auth_json = json.loads(os.environ['GDRIVE_AUTH_PASSWORD'])
        gauth.credentials = ServiceAccountCredentials.from_json_keyfile_dict(
            auth_json, scope)

        self.drive = GoogleDrive(gauth)

    def list_files_in_folder(self, folder_name):
        return self.drive.ListFile(
            {'q': "'{}' in parents and trashed=false".format(folder_name)})

    def upload_file(self, file_name, folder_id):
        """Uploads a file to google drive folder that you've specified

        Arguments:
            drive {Google Drive Object} -- Google Drive Object passed in from google_drive_utils.py
            file_name {String} -- name of the file
            folder_id {String} -- folder id that you get from visiting the webpage and the
            folder that you want. It'll be the last part of the URL.
            Ex: https://drive.google.com/drive/folders/1E-19lkZJJ055ApIhD_HMFBqMFJBj4DfQ
            the folder id is: 1E-19lkZJJ055ApIhD_HMFBqMFJBj4DfQ
        """
        bern = self.drive.CreateFile({
            'title':
            f'{file_name}',
            'mimeType':
            'text/csv',
            "parents": [{
                "kind": "drive#fileLink",
                "id": f'{folder_id}'
            }]
        })

        bern.SetContentFile(f'./{file_name}')
        bern.Upload()

    def delete_files(self, to_delete):
        for file in to_delete:
            try:
                x = self.drive.CreateFile({'id': file['id']})
                print(f'deleting: {file["title"]}')
                x.Delete()
            except Exception:
                pass
Пример #23
0
class GoogleDriveWrapper(object):
    def __init__(self):
        auth.authenticate_user()
        self.gauth = GoogleAuth()
        self.gauth.credentials = GoogleCredentials.get_application_default()
        self.drive = GoogleDrive(self.gauth)

    def save(self, path, gd_dir_id=None):
        metadata = {'title': os.path.basename(path)}
        if gd_dir_id is not None:
            metadata['parents'] = [{
                'kind': 'drive#childList',
                'id': gd_dir_id
            }]
        file = self.drive.CreateFile(metadata)
        file.SetContentFile(path)
        file.Upload()
        return self

    def ls(self, gd_dir_id):
        return [
            file_info['title'] for file_info in self.drive.ListFile({
                'q':
                "'{}' in parents".format(gd_dir_id)
            }).GetList()
        ]

    def load(self, file_name=None, gd_dir_id=None):
        query = {}
        if gd_dir_id is not None:
            query['q'] = "'{}' in parents and trashed=false".format(gd_dir_id)
        if file_name is not None:
            query['orderBy'] = 'modifiedDate desc'
        for file_info in self.drive.ListFile(query).GetList():
            if file_name is None or file_info['title'] == file_name:
                f = self.drive.CreateFile({'id': file_info['id']})
                f.GetContentFile(file_info['title'])
                break
        return self
Пример #24
0
def restoreFromGoogleDrive():
    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")

    drive = GoogleDrive(gauth)

    file_list = drive.ListFile({
        'q': "'root' in parents and trashed=false"
    }).GetList()
    for file1 in file_list:
        if (file1['title'] == "PC-Backups"):
            folderid = file1['id']

    file_list = drive.ListFile({
        'q':
        "'{}' in parents and trashed=false".format(folderid)
    }).GetList()

    restore_date = input("Enter date of backup in dd-mm-yyyy: ")
    filename = "backup-" + restore_date

    for i, file1 in enumerate(sorted(file_list, key=lambda x: x['title']),
                              start=1):
        if (file1['title'] == filename):
            print('Downloading {} from GDrive ({}/{})'.format(
                file1['title'], i, len(file_list)))
            file1.GetContentFile(file1['title'])
Пример #25
0
def GetFileID(file_name, folder_id):
    gauth = GoogleAuth()
    scope = ['https://www.googleapis.com/auth/drive']
    gauth.credentials = ServiceAccountCredentials.from_json_keyfile_name(
        'ClipFetcher-SERVICE-ACCOUNT.json', scope)
    drive = GoogleDrive(gauth)

    query = '\'' + folder_id + '\' in parents and trashed=false'  # root OR chat OR video
    file_list = drive.ListFile({'q': query}).GetList()
    for file in file_list:
        if file['title'] == file_name:
            return file['id']
    return None
Пример #26
0
class GoogleDriveManager:
    def __init__(self):
        google_auth = GoogleAuth()
        google_auth.LocalWebserverAuth()
        self.drive = GoogleDrive(google_auth)

        self.file_list = None

    def __get_file_list(self, query_set):

        query_str = "'{}' in parents and trashed=false"
        query = {'q': query_str.format('root')}
        files = self.drive.ListFile(query).GetList()

        while query_set:
            next_file_name = query_set.pop(0)
            for file in files:
                file_name = file.get('title')
                if file_name == next_file_name:
                    query = {'q': query_str.format(file.get('id'))}
                    print('title: {}, id: {}'.format(file_name, file['id']))

            files = self.drive.ListFile(query).GetList()

        self.file_list = files

    def __download_file(self):
        for file in self.file_list:
            print(file['alternateLink'])
            print('title: %s, id: %s' % (file['title'], file['id']))
        return

    def void_arg(self):
        return

    def google_drive_manager(self):
        query_set = ['IUM', 'dispense']
        self.__get_file_list(query_set)
        self.__download_file()
Пример #27
0
class PyDriveUtil(object):
    def __init__(self):
        self.gauth = self.get_gauth()
        self.drive = GoogleDrive(self.gauth)

    def get_file_object(self, folder_uri, file_name):

        search_string = "'%s' in parents and trashed=false" % folder_uri
        file_list = self.drive.ListFile({'q': search_string}).GetList()
        for file_obj in file_list:
            if file_name in file_obj['title']:
                return file_obj
        return None

    def update_file_content(self, folder_uri, file_name, content):
        file_obj = self.get_file_object(folder_uri, file_name)
        file_obj.SetContentString(content)
        file_obj.Upload()

    def get_gauth(self):
        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()

        # Initialize the saved creds
        gauth.Authorize()
        # Save the current credentials to a file
        gauth.SaveCredentialsFile("mycreds.txt")
        return gauth

    def copy_file(self, file_id, folder_uri, new_title):
        return self.drive.auth.service.files().copy(fileId=file_id,
                                                    body={
                                                        "parents": [{
                                                            "kind":
                                                            "drive#fileLink",
                                                            "id":
                                                            folder_uri
                                                        }],
                                                        'title':
                                                        new_title
                                                    }).execute()

    def delete_file(self, file_id):
        self.drive.auth.service.files().delete(fileId=file_id).execute()
Пример #28
0
def id_fn(entryList):
    print(entryList)
    internet = {}
    dic = {}
    inter = []
    gauth = GoogleAuth()
    gauth.LocalWebserverAuth()
    drive = GoogleDrive(gauth)
    for i in entryList:
        links = []
        fileList = drive.ListFile({
            'q':
            "'{}' in parents and trashed=false".format(i.get())
        }).GetList()
        for f in fileList:
            d = {}
            d['Email'] = f['title']
            url = "https://drive.google.com/open?id=" + f['id']
            d['url'] = url
            links.append(d)
        inter.append(links)

    print(inter)
    with open(filename, 'r') as f:
        local = json.load(f)

    domain = ["Photoshop", "Python_Programming", "C_Programming"]

    for (i, dn) in zip(inter, domain):
        internet[dn] = i

    # Merging JSON files
    for (key, value), (key2, value2) in zip(internet.items(), local.items()):

        for each1 in value:
            for each2 in value2:
                if each2['Email'].split(
                        '@')[0] + "_Certificate.pdf" == each1['Email']:
                    print("Yes")
                    each2['url'] = each1['url']

    # Checker
    print(local["Photoshop"])

    json_final = json.dumps(local, indent=6)
    with open(filename, 'w') as af:
        af.write(json_final)

    messagebox.showinfo(
        "Information",
        "JSON Updated Successfully and stored under JSON Folder")
Пример #29
0
async def gdrive_helper(client, message):
    if len(message.text.split()) == 1:
        gdriveclient = os.path.isfile("client_secrets.json")
        if not gdriveclient:
            await message.reply(
                "Hello, look like you're not logged in to google drive 🙂\nI can help you to login.\n\nFirst of all, you need to activate your google drive API\n1. [Go here](https://developers.google.com/drive/api/v3/quickstart/python), click **Enable the drive API**\n2. Login to your google account (skip this if you're already logged in)\n3. After logged in, click **Enable the drive API** again, and click **Download Client Configuration** button, download that.\n4. After downloaded that file, open that file then copy all of that content, back to telegram then do .credentials (copy the content of that file)  do without bracket \n\nAfter that, you can go next guide by type /gdrive"
            )
            return
        gauth.LoadCredentialsFile("nana/session/drive")
        if gauth.credentials is None:
            authurl = gauth.GetAuthUrl()
            teks = "First, you must log in to your Google drive first.\n\n[Visit this link and login to your Google account]({})\n\nAfter that you will get a verification code, type `/gdrive (verification code)` without '(' or ')'.".format(
                authurl)
            await message.reply(teks)
            return
        await message.reply(
            "You're already logged in!\nTo logout type `/gdrive logout`")
    elif len(
            message.text.split()) == 2 and message.text.split()[1] == "logout":
        os.remove("nana/session/drive")
        await message.reply(
            "You have logged out of your account!\nTo login again, just type /gdrive"
        )
    elif len(message.text.split()) == 2:
        try:
            gauth.Auth(message.text.split()[1])
        except pydrive.auth.AuthenticationError:
            await msg.reply_text("Kode autentikasi anda salah!")
            return
        gauth.SaveCredentialsFile("nana/session/drive")
        drive = GoogleDrive(gauth)
        file_list = drive.ListFile({
            'q': "'root' in parents and trashed=false"
        }).GetList()
        for drivefolders in file_list:
            if drivefolders['title'] == 'Nana Drive':
                await message.reply("Authentication successful!\nWelcome back!"
                                    )
                return
        mkdir = drive.CreateFile({
            'title':
            'Nana Drive',
            "mimeType":
            "application/vnd.google-apps.folder"
        })
        mkdir.Upload()
        await message.reply(
            "Authentication successful!\nThe 'Nana Drive' folder has been created automatically!"
        )
    else:
        await message.reply("Invaild args!\nCheck /gdrive for usage guide")
Пример #30
0
class GoogleDriveUtil(object):
    def __init__(self):
        self.gauth = GoogleAuth()
        self.gauth.LocalWebserverAuth()
        self.drive = GoogleDrive(self.gauth)

    def create_folder(self, folder_name):
        '''
        creating folder in top level directory, i.e., root for now
        TODO: extension for subdirectories
        '''
        folder_metadata = {
            'title': folder_name,
            # The mimetype defines this new file as a folder
            'mimeType': 'application/vnd.google-apps.folder'
        }
        folder = drive.CreateFile(folder_metadata)
        folder.Upload()
        return folder

    def upload_file(self, file_name, folder_name=None):
        if folder_name:
            if not self.folder_found(folder_name):
                folder = self.create_folder(folder_name)
            f = self.drive.CreateFile(
                {'parents': [{
                    'kind': 'drive#file',
                    'id': folder['id']
                }]})

            f.SetContentFile('/'.join(
                [DevelopmentConfig.UPLOAD_FOLDER, file_name]))
            f.Upload()
        else:
            f = self.drive.CreateFile({'title': file_name})
            f.SetContentFile('/'.join(
                [DevelopmentConfig.UPLOAD_FOLDER, file_name]))
            f.Upload()

    def folder_found(self, folder_name):
        contents = self.drive.ListFile({
            'q':
            "'root' in parents and trashed=false"
        }).GetList()
        for content in contents:
            if content.get(
                    'mimeType'
            ) == 'application/vnd.google-apps.folder' and content.get(
                    'title') == folder_name:
                return True
        return False