예제 #1
0
def get_authenticated_service(args):
    flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE,
                                   scope=YOUTUBE_UPLOAD_SCOPE,
                                   message=MISSING_CLIENT_SECRETS_MESSAGE)

    storage = Storage("%s-oauth2.json" % sys.argv[0])
    credentials = storage.get()

    if credentials is None or credentials.invalid:
        credentials = run_flow(flow, storage, args)

    return build(YOUTUBE_API_SERVICE_NAME,
                 YOUTUBE_API_VERSION,
                 http=credentials.authorize(httplib2.Http()),
                 cache_discovery=False)
예제 #2
0
def SendMessage(sender, to, subject, msgHtml, msgPlain, attachmentFile=None):
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('gmail', 'v1', http=http)
    # if attachmentFile:
    #     message1 = createMessageWithAttachment(sender, to, subject, msgHtml, msgPlain, attachmentFile)
    # else:
    #     message1 = CreateMessageHtml(sender, to, subject, msgHtml, msgPlain)
    # result = SendMessageInternal(service, "me", message1)
    if 'user' in session and session['user'] == 'admin':
        message1 = CreateMessageHtml(sender, to, subject, msgHtml, msgPlain)
        result = SendMessageInternal(service, "me", message1)
        return result
    else:
        redirect(url_for('admin_login'))
예제 #3
0
def get_authenticated_service():
    parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, parents=[tools.argparser])
    flags = parser.parse_args([])

    flow = client.flow_from_clientsecrets(CLIENT_SECRETS_FILE, scope=SCOPES, message=tools.message_if_missing(CLIENT_SECRETS_FILE))

    storage = file.Storage(CREDENTIALS_FILE)
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        credentials = tools.run_flow(flow, storage)
    http = credentials.authorize(http=httplib2.Http())

    youtube = build(API_SERVICE_NAME, API_VERSION, http=http)

    return youtube
예제 #4
0
def get_authenticated_service(args):
    #flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE, scope=YOUTUBE_READ_WRITE_SSL_SCOPE, message=MISSING_CLIENT_SECRETS_MESSAGE)
    flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES)
    #credentials = flow.run_console()

    #storage = Storage("%s-oauth2.json" % sys.argv[0])
    credentials = storage.get()

    if credentials is None or credentials.invalid:
        credentials = run_flow(flow, storage, args)

    # Trusted testers can download this discovery document from the developers page
    # and it should be in the same directory with the code.
    with open("youtube-v3-discoverydocument.json", "r") as f:
        doc = f.read()
        return build_from_document(doc, http=credentials.authorize(httplib2.Http()))
예제 #5
0
def get_credentials(username):
    usr = User.objects.get(username=username)
    store = Storage('storage.json')
    creden = Credentials.objects.filter(user=usr).first()
    #
    if (creden):  #if creden existed
        if (
                not creden.invalid
        ):  #and if creden valid, request new access token using refresh_token
            payload = {
                'refresh_token': creden.refresh_token,
                'client_id': creden.client_id,
                'client_secret': creden.client_secret,
                'grant_type': 'refresh_token'
            }
            r = requests.post('https://oauth2.googleapis.com/token',
                              data=payload)
            new_token = json.loads(r.text)
            credentials = google.oauth2.credentials.Credentials(
                token=new_token['access_token'],
                refresh_token=creden.refresh_token,
                id_token=None,
                token_uri='https://oauth2.googleapis.com/token',
                client_id=creden.client_id,
                client_secret=creden.client_secret)
            creden.access_token = new_token['access_token']
            creden.save()
            service = build('calendar', 'v3', credentials=credentials)
            return (service, credentials)
        else:
            creden.delete()
    # If no creden existed
    flow = flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
    credentials = tools.run_flow(flow, store, flags)
    os.remove('storage.json')
    cred = credentials_to_dict(credentials)
    creden = Credentials.objects.create(user=usr,
                                        access_token=cred['access_token'],
                                        refresh_token=cred['refresh_token'],
                                        client_id=cred['client_id'],
                                        client_secret=cred['client_secret'],
                                        scopes=cred['scopes'],
                                        invalid=cred['invalid'])
    creden.save()
    http = credentials.authorize(httplib2.Http())
    service = build('calendar', 'v3', http=http)
    return (service, credentials)
예제 #6
0
def get_properties():

	storage = Storage(WEBMASTER_CREDENTIALS_FILE_PATH)
	credentials = storage.get()

	# Create an httplib2.Http object and authorize it with our credentials
	http = httplib2.Http()
	http = credentials.authorize(http)
	service = build('webmasters', 'v3', http=http)

	# Retrieve list of properties in account
	site_list = service.sites().list().execute()

	# Filter for verified websites
	verified_sites_urls = [s['siteUrl'] for s in site_list['siteEntry'] if s['permissionLevel'] != 'siteUnverifiedUser' and s['siteUrl'][:4] == 'http']

	return verified_sites_urls
예제 #7
0
def list_files(request):
    credentials = get_credentials()
    HTTP = credentials.authorize(Http())
    DRIVE = discovery.build('drive', 'v3', http=HTTP)

    files = DRIVE.files().list().execute().get('files', [])
    file_list = []
    for f in files:
        file_list.append({"name": f['name'], "type": f['mimeType']})

    return JsonResponse(file_list, status=status.HTTP_200_OK, safe=False)

# from googleapiclient.discovery import build
#
# with build('drive', 'v3') as service:
#     collection = service.stamps
#     nested_collection = service.featured().stamps()
#     request = collection.list(cents=5)
#     response = request.execute()
예제 #8
0
def main():
    """Set up the credentials and service for Google Calendar authorization."""
    global workStart
    global workEnd
    checkPreferencesForm.has_been_called = False

    global current
    current = Time()

    global format
    format = Format()

    global service

    if request.method == "POST":
        if request.headers.get('X-Requested-With'):

            #Source for the authentication code
            #https://developers.google.com/identity/sign-in/web/server-side-flow

            auth_code = request.data
            # Set path to the Web application client_secret_*.json file you downloaded from the
            # Google API Console: https://console.developers.google.com/apis/credentials
            CLIENT_SECRET_FILE = 'app/static/client_secret.json'

            # Exchange auth code for access token, refresh token, and ID token
            credentials = client.credentials_from_clientsecrets_and_code(
                CLIENT_SECRET_FILE, [
                    'https://www.googleapis.com/auth/calendar', 'profile',
                    'email'
                ], auth_code)

            # Call Google API
            http_auth = credentials.authorize(httplib2.Http())
            service = discovery.build('calendar', 'v3', http=http_auth)

            now = datetime.datetime.utcnow().isoformat(
            ) + 'Z'  # 'Z' indicates UTC time

            return form()
    return render_template('base.html')
예제 #9
0
def main():
    if request.method == "POST":
        print("main data = ")
        print(request.data)
        if request.headers.get('X-Requested-With'):
            print('----------------------')
            auth_code = request.data
            print(auth_code)
            if not request.headers.get('X-Requested-With'):
                print('403')

            # Set path to the Web application client_secret_*.json file you downloaded from the
            # Google API Console: https://console.developers.google.com/apis/credentials
            CLIENT_SECRET_FILE = 'app/static/client_secret.json'

            # Exchange auth code for access token, refresh token, and ID token
            credentials = client.credentials_from_clientsecrets_and_code(
                CLIENT_SECRET_FILE, [
                    'https://www.googleapis.com/auth/calendar', 'profile',
                    'email'
                ], auth_code)

            # Call Google API
            http_auth = credentials.authorize(httplib2.Http())
            service = discovery.build('calendar', 'v3', http=http_auth)

            # Get profile info from ID token
            # userid = credentials.id_token['sub']
            # email = credentials.id_token['email']
            # form(credentials)
            now = datetime.datetime.utcnow().isoformat(
            ) + 'Z'  # 'Z' indicates UTC time

            # redirect(url_for('form'))
            return form(credentials)
    return render_template('index.html')
예제 #10
0
    def list_files(self, request):

        user_id = request.body.get("userId")
        storage = Storage(CREDS_FILE)
        credentials = storage.get()

        now = datetime.now()
        year = str(now.year)
        month = '0' + str(now.month) if now.month < 10 else str(now.month)
        day = '0' + str(now.day) if now.day < 10 else str(now.day)

        tmp_path = os.path.join(settings.MEDIA_ROOT + str(user_id) + "/" +
                                year + month + day + "/")

        http = httplib2.Http()
        http = credentials.authorize(http)

        drive_service = build("drive", "v2", http=http)

        print("drive_service", drive_service)

        for x in self.get_list(drive_service):

            labels = x.get('labels')
            if (x.get('title')) and x.get('alternateLink') and x.get(
                    'shared') == False and labels['trashed'] == False:

                # 구글 드라이브 관련 메타 데이타 저장
                box_file = BoxFile()
                box_file.fi_bsusserid = user_id
                box_file.fi_bsdiv = "V"
                box_file.fi_bsname = "GD"
                box_file.fi_name = x.get('title')
                box_file.fi_path = x.get('alternateLink')
                print("구글 드라이브 내용", x)

                # 폴더 정보 가져오기
                # for y in self.print_files_in_folder(drive_service, )
                # 구글 드라이브에 파일이 저장되어 있을경우 파일을 다운로드 하여 S3에 업로드
                # 그 외에 링크는 해당 링크 정보 저장
                if x.get('webContentLink') is not None:
                    # fileid를 가지고 구글드라이브에서 파일정보를 가져옴
                    file = drive_service.files().get_media(fileId=x.get('id'))

                    print("tmp_path=================", tmp_path)

                    if not os.path.isdir(tmp_path):
                        os.mkdir(tmp_path)
                    file_path = tmp_path + x.get('title')

                    fh = io.FileIO(file_path, 'wb')
                    downloader = MediaIoBaseDownload(fh, file)
                    done = False
                    while done is False:
                        status, done = downloader.next_chunk()
                        print("Download %d%%" % int(status.progress() * 100))

                    if done is True:
                        with open(file_path, 'rb') as data:
                            server_path = FileExplorer.fileUpload(file=data)
                            data.close()

                        box_file.fi_name = data.name.split("/")[-1]
                        box_file.fi_path = server_path

                # 구글드라이브 관련 정보 별도로 저장
                google_drive = Googledrivefiles()

                # 부모폴더 처리
                parent_info = x.get('parents')
                if parent_info:
                    parent = parent_info[0]
                    if parent['isRoot'] == True:
                        box_file.fi_is_root = True
                    else:
                        box_file.fi_is_root = False
                        param = {}
                        children = drive_service.children().list(
                            folderId=x.get('id'), **param).execute()
                        print("children===============", children)

                    google_drive.parentid = parent['id']

                # 폴더여부 확인 및 파일 아이콘 타입 설정
                mimetype = x.get('mimeType')
                print("mimetype", mimetype)
                if mimetype == 'application/vnd.google-apps.folder':
                    box_file.fi_is_folder = True
                    box_file.fi_icon_type = 'folder'
                elif mimetype == 'application/vnd.google-apps.spreadsheet':
                    box_file.fi_icon_type = 'spreadsheet'
                elif mimetype == 'application/vnd.google-apps.presentation':
                    box_file.fi_icon_type = 'presentation'
                elif mimetype == 'application/vnd.google-apps.document':
                    box_file.fi_icon_type = 'document'
                elif mimetype == 'application/vnd.ms-excel':
                    box_file.fi_icon_type = 'ms-excel'
                elif mimetype == 'image/png' or mimetype == 'image/jpeg':
                    box_file.fi_icon_type = 'image'
                elif mimetype == 'application/vnd.openxmlformats-officedocument.presentationml.presentation':
                    box_file.fi_icon_type = 'presentation'
                else:
                    box_file.fi_icon_type = 'etc'

                box_file.fi_status = "G"
                box_file.fi_createdate = x.get('createdDate')
                box_file.fi_modifydate = x.get('modifiedDate')
                box_file.fi_file_size = x.get('fileSize')
                box_file.fi_mimetype = mimetype
                box_file.fi_ext = x.get('fileExtension')
                box_file.save()

                google_drive.box_file_id = box_file
                google_drive.filename = box_file.fi_name
                google_drive.filepath = x.get('webContentLink')
                google_drive.modifydate = x.get('modifiedDate')
                google_drive.mimetype = mimetype
                google_drive.googledrivefileid = x.get('id')

                google_drive.save()

        storage.delete()
        # # 구글드라이브에 있는 파일을 다운로드후 삭제
        # shutil.rmtree(tmp_path)

        return tmp_path
def get_authenticated_service():
  flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES)
  credentials = flow.run_console()
  return build(API_SERVICE_NAME, API_VERSION, http=credentials.authorize(httplib2.Http()))
예제 #12
0
CLIENT_ID = "929791903032-hpdm8djidqd8o5nqg2gk66efau34ea6q.apps.googleusercontent.com"
CLIENT_SECRET = "YHDd4FrEFtqjhIkZhprwUMuy"
REFRESH_TOKEN = "1/RinJvsjGrAUvBj3QoHsHMvopmsf-7U0x1KCvhpo0cq0"
ACCESS_TOKEN = "ya29.GlubBs2CfFIMOsQRkqSxgAyff5rQ8aiu1IWI6j2Ery5MsuL4VOnr9s7owicF0C_vgM8USc1IDY03jXxWlQn7dCjn2MMa5Gzh6LWZlxqLdLnU2ib8YXPR8nialM1F"
credentials = client.OAuth2Credentials(
    access_token=ACCESS_TOKEN,
    client_id=CLIENT_ID,
    client_secret=CLIENT_SECRET,
    refresh_token=REFRESH_TOKEN,
    token_expiry=3600,
    token_uri="https://oauth2.googleapis.com/token",
    scopes="https://www.googleapis.com/auth/yt-analytics-monetary.readonly",
    user_agent="Bearer",
    revoke_uri=None)

http = credentials.authorize(httplib2.Http())


# Authorize the request and store authorization credentials.
def get_authenticated_service():
    # flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES)
    # credentials = flow.run_local_server()
    return build(API_SERVICE_NAME, API_VERSION, credentials=credentials)


# Remove keyword arguments that are not set.
def remove_empty_kwargs(**kwargs):
    good_kwargs = {}
    if kwargs is not None:
        for key, value in kwargs.items():
            if value:
예제 #13
0
def login(request):
    set_credentials()
    credentials = CREDENTIAL
    http = credentials.authorize(httplib2.Http())
    print('login')
    return render(request, 'portal/home.html')