Esempio n. 1
0
def get_drive():
    gauth = GoogleAuth()
    scope = ['https://www.googleapis.com/auth/drive']
    gauth.credentials = ServiceAccountCredentials.from_json_keyfile_name(
        settings.SERVICE_ACCOUNT_CRED_PATH, scope)
    drive = GoogleDrive(gauth)
    return drive
Esempio n. 2
0
def init_permisson_google_drive(shared_user='******',
                                role='reader'):
    try:
        gauth = GoogleAuth()
        scope = ['https://www.googleapis.com/auth/drive']
        gauth.credentials = ServiceAccountCredentials.from_json_keyfile_name(
            'client_secrets.json', scope)
        drive = GoogleDrive(gauth)
    except Exception as e:
        print('---can not connect to google drive---')
        print(e)

    try:

        file_list = drive.ListFile({
            'q': "'root' in parents and trashed=false"
        }).GetList()
        for f in file_list:
            permission_list = [
                email['emailAddress'] for email in f.GetPermissions()
            ]
            if '*****@*****.**' not in permission_list:
                f.InsertPermission({
                    'type': 'user',
                    'value': shared_user,
                    'role': role,
                    'sendNotificationEmails': 'false'
                })
    except Exception as e:
        print('---can not init file permission---')
        print(e)
def connectDrive(service_account_file, user_email):
    gauth = GoogleAuth()
    credentials = ServiceAccountCredentials.from_json_keyfile_name(
        service_account_file, SCOPES)
    gauth.credentials = credentials.create_delegated(sub=USER_EMAIL)

    drive = GoogleDrive(gauth)
    return drive
Esempio n. 4
0
 def __init__(self, cred_json_file):
     """
     Create Google Drive client using service configuration json
     :param cred_json_file:
     """
     auth = GoogleAuth()
     auth.credentials = ServiceAccountCredentials.from_json_keyfile_name(
         cred_json_file, ['https://www.googleapis.com/auth/drive'])
     self.drive = GoogleDrive(auth)
Esempio n. 5
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']))
def upload_to_drive(file_path, title, folder_title, project, user, sheet=None):
    """
    Uploads a google sheet to a drive Supports team drive.

    """
    gauth = GoogleAuth()
    team_drive_id = parent_folder_id = settings.PARENT_FOLDER_ID
    scope = [
        'https://www.googleapis.com/auth/drive',
        'https://www.googleapis.com/auth/drive.file'
    ]
    gauth.credentials = ServiceAccountCredentials.from_json_keyfile_name(
        settings.SERVICE_ACCOUNT_JSON, scope)
    drive = GoogleDrive(gauth)
    permissions = []
    user_emails = UserRole.objects.filter(ended_at__isnull=True).filter(
        Q(
            Q(group__name="Organization Admin", project__isnull=True)
            | Q(group__name__in=["Project Manager", "Project Donor"],
                project_id=sheet.project.id)),
        organization_id=sheet.project.organization_id).distinct().values_list(
            'user__email', flat=True)
    user_emails = list(user_emails)
    user_emails.append(settings.SERVICE_ACCOUNT_EMAIL)
    all_users = set(user_emails)
    for perm in all_users:
        permissions.append({'type': 'user', 'value': perm, 'role': 'writer'})
    new_file = drive.CreateFile({
        'title':
        title,
        'parents': [{
            'kind': 'drive#fileLink',
            'teamDriveId': team_drive_id,
            'id': parent_folder_id
        }],
        'shareable':
        True,
        'userPermission': [permissions]
    })
    new_file.SetContentFile(file_path)
    new_file.Upload({'convert': True, 'supportsTeamDrives': True})

    sheet.spreadsheet_id = new_file['alternateLink']
    sheet.last_synced_date = datetime.datetime.now()
    sheet.save()

    for perm in permissions:
        try:
            new_file.InsertPermission(perm)
        except Exception as e:
            print(
                str(e), "Failed to share file {0} to {1} email".format(
                    new_file['alternateLink'], perm))
Esempio n. 7
0
 def __init__(self, credential):
     self.gauth = GoogleAuth()
     self.scopes = [
         'https://www.googleapis.com/auth/spreadsheets',
         'https://www.googleapis.com/auth/drive',
         'https://www.googleapis.com/auth/drive.file'
     ]
     self.credentials = ServiceAccountCredentials.from_json_keyfile_name(
         credential, self.scopes)
     self.gauth.credentials = self.credentials
     self.drive = GoogleDrive(self.gauth)
     self.gsheet = gspread.authorize(self.credentials)
Esempio n. 8
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
Esempio n. 9
0
 def __authenticate(self):
     try:
         gauth = GoogleAuth()
         scope = ["https://www.googleapis.com/auth/drive"]
         gauth.credentials = ServiceAccountCredentials.from_json_keyfile_name(
             "service-account.json", scope)
         self.drive = GoogleDrive(gauth)
         self.is_ready = True
     except Exception as e:
         logger.info(
             f"Can't authenticate BackupService, setting it to not ready: {e}",
             exc_info=e)
         self.is_ready = False
Esempio n. 10
0
def authenticate():
    """ 
    Authenticate to Google API
    """
    with open("settings.yaml") as f:
        settings = yaml.load(f, Loader=yaml.FullLoader)

    gauth = GoogleAuth()
    scope = settings["oauth_scope"]
    gauth.credentials = ServiceAccountCredentials.from_json_keyfile_name(
        settings["client_config_file"], scope)

    return GoogleDrive(gauth)
    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)
Esempio n. 12
0
def UploadChat(vod_id, abs_path):
    gauth = GoogleAuth()
    scope = ['https://www.googleapis.com/auth/drive']
    gauth.credentials = ServiceAccountCredentials.from_json_keyfile_name(
        'ClipFetcher-SERVICE-ACCOUNT.json', scope)
    drive = GoogleDrive(gauth)

    file_name = vod_id + '.json'  #
    with open(abs_path, "r") as file:
        file_drive = drive.CreateFile({
            'title':
            os.path.basename(file.name),
            'parents': [{
                'kind': 'drive#fileLink',
                'id': CHAT_FOLDER_ID
            }]
        })
        file_drive.SetContentFile(abs_path)
        file_drive.Upload()
Esempio n. 13
0
def main(credentials, folder, databases, interval, delay):
    gauth = GoogleAuth()
    scope = ['https://www.googleapis.com/auth/drive']
    gauth.credentials = ServiceAccountCredentials.from_json_keyfile_name(
        credentials, scope)
    gdrive = GoogleDrive(gauth)

    parent_id = gdrive.ListFile({
        'q':
        f"mimeType = 'application/vnd.google-apps.folder' and title = '{folder}'"
    }).GetList()[0]['id']

    time.sleep(delay)

    backoff = False
    while True:
        if backoff:
            time.sleep(BACK_OFF_INTERVAL)
        now = time.time()
        try:
            backup_db(databases, gdrive, parent_id, now)
        except KeyboardInterrupt:
            print("backup.py exiting...")
            break
        except Exception:
            logging.exception('Unexpected Exception')
            backoff = True
            continue
        else:
            backoff = False

        try:
            time.sleep(now - time.time() + interval)
        except ValueError:
            logging.info(
                f"Backing up databases took longer than {interval} seconds")
        except KeyboardInterrupt:
            print("backup.py exiting...")
            break
Esempio n. 14
0
def main():
    # Authenticate
    print("Authenticating...")
    gauth = GoogleAuth()
    scope = ['https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.file']
    gauth.credentials = ServiceAccountCredentials.from_json_keyfile_name('client_secrets.json', scope)
    
    # Initialize drive
    global drive
    drive = GoogleDrive(gauth)

    delete_all(get_file_list())

    upload_recursive()

    # Add a file which marks dir as changed
    control_file = drive.CreateFile({'title': 'changed'})
    control_file.Upload()

    # for file in get_file_list():
    #     print(file['title'], file['id'])

    print("Done")
Esempio n. 15
0
def main():
    # Authenticate
    print("Authenticating...")
    gauth = GoogleAuth()
    scope = [
        'https://www.googleapis.com/auth/drive',
        'https://www.googleapis.com/auth/drive.file'
    ]
    gauth.credentials = ServiceAccountCredentials.from_json_keyfile_name(
        'client_secrets.json', scope)
    drive = GoogleDrive(gauth)
    print("Authenticated.")

    user_input = input(
        "1. Download latest version\n2. Upload this version as latest\nInput: "
    )

    if (user_input == '1'):
        download(drive)
    if (user_input == '2'):
        delete_all(get_file_list(drive))
        upload(drive)

    print("Exiting...")
Esempio n. 16
0
def upload_img_to_google_drive(folder_id, img, name):
    try:
        gauth = GoogleAuth()
        scope = ['https://www.googleapis.com/auth/drive']
        gauth.credentials = ServiceAccountCredentials.from_json_keyfile_name(
            'client_secrets.json', scope)
        drive = GoogleDrive(gauth)
    except Exception as e:
        print('---can not connect to google drive---')
        print(e)
    try:
        file = drive.CreateFile({
            'title':
            '{}'.format(name),
            "parents": [{
                "kind": "drive#fileLink",
                "id": folder_id
            }]
        })
        file.SetContentFile(img)
        file.Upload()
        # file.InsertPermission({
        #                     'type': 'user',
        #                     'value': '*****@*****.**',
        #                     'role': 'reader',
        #                     'sendNotificationEmails': 'false'
        #                     })
        # file_list = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList()
        # for f in file_list:
        #      f.InsertPermission({
        #                     'type': 'user',
        #                     'value': '*****@*****.**',
        #                     'role': 'reader'})
    except Exception as e:
        print('---can not upload {}'.format(img))
        print(e)
Esempio n. 17
0
import os
from pydrive.drive import GoogleDrive
from pydrive.auth import GoogleAuth, ServiceAccountCredentials

gauth = GoogleAuth()
scope = ["https://www.googleapis.com/auth/drive"]
gauth.credentials = ServiceAccountCredentials.from_json_keyfile_name(
    "service_account_credentials.json", scope
)
drive = GoogleDrive(gauth)


def uploader(path):
    """
    Uploads a file to an environment specified Google Drive folder
    """
    folder_id = os.getenv("GDRIVE_FOLDER")
    if os.path.exists(path):
        gfile = drive.CreateFile(
            {"parents": [{"kind": "drive#fileLink", "id": folder_id}]}
        )
        gfile.SetContentFile(path)
        gfile["title"] = os.path.basename(path)
        gfile.Upload()
    else:
        raise FileNotFoundError()
Esempio n. 18
0
from pydrive.auth import GoogleAuth, ServiceAccountCredentials
from pydrive.drive import GoogleDrive

gauth = GoogleAuth()
scope = ['https://www.googleapis.com/auth/drive']
gauth.credentials = ServiceAccountCredentials.from_json_keyfile_name(
    'google_sa_key.json', scope)
drive = GoogleDrive(gauth)


def download_pdf(id, target):
    global drive
    file = drive.CreateFile({'id': id})
    print("Found a file in google drive!")
    file.GetContentFile(target)
Esempio n. 19
0
 def __init__(self):
     gauth = GoogleAuth()
     scope = ['https://www.googleapis.com/auth/drive']
     gauth.credentials = ServiceAccountCredentials.from_json_keyfile_name(settings.CLIENT_SECRET_FILE_SERVICEACCOUNT, scope)
     self.drive = GoogleDrive(gauth)
Esempio n. 20
0
from pydrive.auth import GoogleAuth, ServiceAccountCredentials
from pydrive.drive import GoogleDrive
from googleapiclient.discovery import build
from starlette.responses import FileResponse

import os, glob, shutil, sys

# os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "../key/system-backup-1-53687ddf7502.json"
google_login = GoogleAuth()
scope = ['https://www.googleapis.com/auth/drive']
google_login.credentials = ServiceAccountCredentials.from_json_keyfile_name(
    'client_secrets.json', scope)
drive = GoogleDrive(google_login)
service = build('drive', 'v3', credentials=google_login.credentials)


def delete_file(file_id):
    file_to_delete = drive.CreateFile({'id': file_id})
    file_name = file_to_delete['title']
    file_to_delete.Delete()
    return "file: " + file_name + " has successfully Deleted from the Drive"


def download_file(file_id):
    file_to_download = drive.CreateFile({'id': file_id})
    os.chdir("download")
    file_to_download.GetContentFile(str(file_to_download['title']))
    os.chdir("..")
    return file_to_download['title']
    return FileResponse(str(file_to_download['title']))
Esempio n. 21
0
    ProjectReviewRecordAdminForm,
)
from app.project.forms import *
from app.main.models import User, MailInfo
from pydrive.auth import ServiceAccountCredentials, GoogleAuth
from pydrive.drive import GoogleDrive
from flask_mail import Message
from itsdangerous import TimedJSONWebSignatureSerializer

import pandas as pd

gauth = GoogleAuth()
keyfile_dict = requests.get(
    os.environ.get('GOOGLE_APPLICATION_CREDENTIALS')).json()
scopes = ['https://www.googleapis.com/auth/drive']
gauth.credentials = ServiceAccountCredentials.from_json_keyfile_dict(
    keyfile_dict, scopes)
drive = GoogleDrive(gauth)

GANTT_ACTIVITIES = dict([
    (1, '1. พัฒนาโครงร่างการวิจัยและเครื่องมือการวิจัย'),
    (2, '2. เสนอโครงร่างการวิจัยเพื่อขอรับการพิจารณาจริยธรรมฯ'),
    (3, '3. เสนอขอรับทุนอุดหนุนการวิจัย'),
    (4, '4. ผู้ทรงคุณวุฒิตรวจสอบและแก้ไข'),
    (5, '5. ติดต่อประสานงานเพื่อขอเก็บข้อมูล'),
    (6, '6. ดำเนินการเก็บรวบรวมข้อมูล'),
    (7, '7. วิเคราะห์ผลการวิจัยและอภิปรายผล'),
    (8, '8. จัดทำรายงานการวิจัยและเตรียมต้นฉบับตีพิมพ์งานวิจัย')
])

STIN_EMAIL = os.environ.get('MAIL_USERNAME')
Esempio n. 22
0
def initialize_gdrive():
    gauth = GoogleAuth()
    scopes = ['https://www.googleapis.com/auth/drive']
    gauth.credentials = ServiceAccountCredentials.from_json_keyfile_dict(
        json_keyfile, scopes)
    return GoogleDrive(gauth)
Esempio n. 23
0
import os
import re
import sys
import subprocess
from time import sleep
from pydrive.drive import GoogleDrive
from pydrive.auth import GoogleAuth, ServiceAccountCredentials
proxy = 'http://localhost:8080'
'''os.environ['http_proxy'] = proxy 
os.environ['HTTP_PROXY'] = proxy
os.environ['https_proxy'] = proxy
os.environ['HTTPS_PROXY'] = proxy'''
flag = sys.argv[1]
gauth = GoogleAuth()
scope = ['https://www.googleapis.com/auth/drive']
gauth.credentials = ServiceAccountCredentials.from_json_keyfile_name(
    json_file_location, scope)
drive = GoogleDrive(gauth)

list1 = os.listdir(folder1)


def uploadFiles(files_list):
    for x in files_list:
        output_name = x
        output_path = folder1 + output_name
        split_output_name = "Split_" + output_name
        split_path = folder2 + split_output_name
        print("Directory updated " + split_path)
        pages_range = "1-" + str(pages_number)
        try:
            subprocess.check_call([
Esempio n. 24
0
from PIL import Image, ImageChops
from pydrive.auth import GoogleAuth, ServiceAccountCredentials as Creds
from pydrive.drive import GoogleDrive
import numpy
import os
import picamera
import time

# Initialize PiCamera, set up Google Auth creds
choice = ""
threshold = 0.1
camera = picamera.PiCamera()
folder_id = "DRIVE_FOLDER_ID_TO_UPLOAD_FILES"
gauth = GoogleAuth()
auth = ["https://www.googleapis.com/auth/drive"]
gauth.credentials = Creds.from_json_keyfile_name("creds.json", auth)
drive = GoogleDrive(gauth)


# Uploads/removes local file (unless can't connect)
def upload(file):
    try:
        print("Uploading", file)
        location = [{"kind": "drive#fileLink", "id": folder_id}]
        drive_file = drive.CreateFile({"parents": location})
        drive_file.SetContentFile(file)
        drive_file.Upload()
        os.remove(file)
    except:
        print("Connection is offline or something's wrong with Google")
Esempio n. 25
0
# Variables
transform_x = config.monitor_w  # how wide to scale the jpg when replaying
transfrom_y = config.monitor_h  # how high to scale the jpg when replaying
offset_x = 0  # how far off to left corner to display photos
offset_y = 0  # how far off to left corner to display photos
replay_delay = 1  # how much to wait in-between showing pics on-screen after taking
replay_cycles = 2  # how many times to show each photo on-screen after taking

real_path = os.path.dirname(os.path.realpath(__file__))

# Auth Google
CREDS_FILE = "/home/pi/photobooth-pi/service_creds.json"
gauth = GoogleAuth()
scope = ['https://www.googleapis.com/auth/drive']
gauth.credentials = ServiceAccountCredentials.from_json_keyfile_name(
    CREDS_FILE, scope)
# gauth.LocalWebserverAuth()

drive = GoogleDrive(gauth)

# GPIO setup
GPIO.setmode(GPIO.BOARD)
GPIO.setup(config.led_pin, GPIO.OUT)  # LED
GPIO.setup(config.btn_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# GPIO.output(config.led_pin,False) #for some reason the pin turns on at the beginning of the program

# initialize pygame
pygame.init()
pygame.display.set_mode((config.monitor_w, config.monitor_h))
screen = pygame.display.get_surface()
pygame.display.set_caption('Photo Booth Pics')