Exemple #1
0
        def check_cred_store():
            #We use a special authorization callback handler that
            #raises an exception to stop the authorization process
            #This happens when credential store is missing or invalid
            def exception_handler(uri):
                raise ValueError("Bad credential file")
                return None
            try:
                #Try to connect to Google Services
                self.google_service = oauth2services.OAuthServices(constants.APP_ID_FILE,constants.CREDENTIALS_STORE_FILE,self.user_mail_var.get())
                return self.google_service.refresh()
            except Exception as error:
#                print error
#                import traceback
#                traceback.print_exc()
                #We failed to connect
                self.google_service = None
                return False
Exemple #2
0
def console_assistant():
    """Launches the text-based interface"""

    print """
    ________________________________________________________________

    Welcome to the installation assistant!
    I will guide you through the setup and installation of Google
    credentials
    ________________________________________________________________

    """
    install_dir = os.path.split(os.path.abspath(__file__))[0]


    #try to read configuration
    config = configuration.Configuration(constants.CONFIGURATION_FILE)



    config.enable_email = ask_boolean("Do you want the 'send photo by email' feature?",config.enable_email)
    print ""
    config.enable_upload = ask_boolean("Do you want the 'auto-upload photos' feature?",config.enable_upload)
    print ""
    config.enable_effects = ask_boolean("Do you want the 'Photos effects' feature?",config.enable_effects)
    print ""
    if printer_selection_enable == True:
        config.enable_print = ask_boolean("Do you want the 'Send photo to printer' feature?", config.enable_print)
        print ""
        if config.enable_print == True:
            conn = cups.Connection()
            printers = conn.getPrinters()
            index = 0
            selectedindex = 0
            for printer in printers:
                if config.selected_printer == str(index):
                    print '[*] ['+str(index)+'] '+printer
                    selectedindex = index
                else:
                    print '[ ] ['+str(index)+'] '+printer
                index = index + 1
            config.selected_printer = raw_input("Seleted printer: [%s] confirm or change =>" % config.selected_printer)
            if config.selected_printer is "": config.selected_printer = selectedindex

    want_email  = config.enable_email
    want_upload = config.enable_upload
    want_print = config.enable_print
    selected_printer = config.selected_printer
    need_credentials = want_email or want_upload

    # We only need a user name if we need credentials
    if config.user_name is None:
        config.user_name = "*****@*****.**"
    config.write()
    if need_credentials:
        # Check for user account
        _username = raw_input("Google account: [%s] confirm or change => " % config.user_name)
        if _username != "":
            config.user_name = _username.strip()
            config.write()
        # Check for credentials
        app_id     = os.path.join(install_dir,constants.APP_ID_FILE)

        if os.path.exists(app_id):
            print "\n** found %s application file, will use it (remove in case of problems)"%constants.APP_ID_FILE
        else:
            print """
    ________________________________________________________________

    Photo upload or email sending requires that you create a
    Google Project and download the project's credentials to
    the scripts/ directory

    Note: you can do the following on any computer (except step 5/)
    ________________________________________________________________

    Here's a step by step guide:
    1/  Go to https://console.developers.google.com/start/api?id=gmail
    2/  Select "Create a project" and click continue
    3/  Follow the assistant with these hints:
        - Platform : other (with command-line user interface)
        - Access   : User data
        - Fill whatever your like for application name and ID name
    4/  The last step of the assistant makes you Download
        a client_id.json file : this is your project's credentials!
    5/  Copy the downloaded file to :
        %s

    The following page has up-to-date informations for this procedure:
    https://support.google.com/googleapi/answer/6158849

    The installation program will now exit.
    Run it again once this is done
    """%(app_id)
            sys.exit()

        # We do have the client_id !

        cred_store = os.path.join(install_dir,constants.CREDENTIALS_STORE_FILE)
        if os.path.exists(cred_store):
            print "\n** Found %s credential store"%constants.CREDENTIALS_STORE_FILE
            remove_file = to_boolean(raw_input("If you have troubles connecting you may want to remove this file\nRemove ? [N/y] => "),False)
            if remove_file:
                try:
                    os.remove(cred_store)
                except:
                    import traceback
                    traceback.print_exc()
                    print "\n==> Problem removing %s file, please do it on your side and run this assistant again\n"%cred_store
                    sys.exit()

        # prepare the validation callback in case of missing or invalid credential store
        import webbrowser
        def auth_callback(authorization_uri):
            print "\n%s file is missing or invalid"%cred_store
            print """
    _________________________________________________________________

    You must authorize this application to access your data
    I will now open a web browser to complete the validation process
    Once this is done, you will get a validation key that you must
    paste below
    _________________________________________________________________"""
            raw_input("Press a key when ready...")
            webbrowser.open(authorization_uri)
            mycode = raw_input('\n[validation code]: ').strip()
            return mycode


        import oauth2services
        try:
            print "\n** Connecting..."
            service = oauth2services.OAuthServices(app_id,cred_store,config.user_name)
            connected = service.refresh() # will call 'auth_callback' if needed
            print "... Done"
        except Exception as error:
            print error
            print "\n==> Connection failed :("
            sys.exit()

        if not connected:
            print "\nThere was an error during the connection"
            print "Please check your network connection and/or reauthorize this application"
            print "Exiting..."
            sys.exit()


       
        if config.albumID != None:
            keep_album = to_boolean(raw_input("Photo Album is configured (%s), do you want to keep it? [Y/n] => "%config.album_name))
            change_album_id = not keep_album
        else:
            print "\nNo photo album selected, images will be uploaded to\nGoogle Photo Library (No Album)"
            change_album_id = to_boolean(raw_input("\nDo you want to select another album for upload? [N/y] => "))

        if change_album_id:
            try:
                print "\nDownloading %s albums list..."% config.user_name
                albums = service.get_user_albums()
                print "... %d albums found"%(len(albums))
                candidates    = []
                candidates_id = []
                album_title = None
                album_id    = None
                while True:
                    search_string = raw_input("Type a part of an existing album name (or return for all): ")
                    search_string = search_string.lower()
                    candidates    = ["<No Album>","<Create New>"]
                    candidates_id = ["","<New>"]
                    for album in albums:
                        title = album['title']
                        title_ = title.lower()
                        id    = album['id']
                        if title_.find(search_string) != -1:
                            candidates.append(title)
                            candidates_id.append(id)
                    if len(candidates) == 0:
                        print "Sorry: no match\n"
                    else:
                        break
                print "Here's the album that match:"
                for i, title in enumerate(candidates):
                    print "[%3d] %s"%(i,title)

                while True:
                    album_num = raw_input("Type album number => ")
                    try:
                        album_title = candidates[int(album_num)]
                        album_id = candidates_id[int(album_num)]
                        break
                    except:
                        print "Bad album number!"
                if album_id == "":
                    config.albumID = None
                elif album_id == "<New>":
                    config.albumID = service.create_album(album_name = "TouchSelfie", add_placeholder_picture = True)
                    album_title = "TouchSelfie"
                else:
                    config.albumID = album_id
                config.album_name = album_title
                config.write()
                print "\nAlbum '%s' with id '%s' successfully selected!\n"%(album_title, album_id)
            except:
                import traceback
                traceback.print_exc()
                print "\n==> Error while fetching user albums, try to re-authenticate the application :("


    # Optional tests for connection
    if config.enable_email:
        config.enable_email_logging = ask_boolean("Do you want to log outgoing email addresses?",config.enable_email_logging)
        config.write()
        test_email = to_boolean(raw_input("Do you want to test email sending? [N/y] => "),False)

    if config.enable_upload:
        test_upload = to_boolean(raw_input("Do you want to test image upload? [N/y] => "),False)

    test_connection(service, config, test_email, test_upload)

    #finally create a personalized script to run the photobooth
    script_name = os.path.join(os.path.abspath(".."),"photobooth.sh")
    script = open(script_name,"w")
    script.write("#!/bin/sh\n")
    script.write("cd %s\n"% install_dir)
    script.write("python user_interface.py $* > %s\n"%(os.path.join(install_dir,"..","photobooth.log")))
    script.close()
    #make the script executable
    import stat
    st = os.stat(script_name)
    os.chmod(script_name, st.st_mode | stat.S_IEXEC)

    print """

    ________________________________________________________________

    We're all set, I just created a script to launch TouchSelfie with
    your options, you will find it here :
    => %s
    You can tune configuration parameters in scripts/%s
    You can adapt your hardware configuration in scripts/constants.py
    """% (script_name, constants.CONFIGURATION_FILE)
Exemple #3
0
    def __connect_app(self):
        print "Connecting App"

        #Create a graphical handler for the authorization
        def auth_handler(URI):
            top = Toplevel(self, bg='white')
            text_frame=Frame(top, bg='white')
            text_frame.pack(side=TOP,fill=X)

            button_frame = Frame(top,bg='white')
            qb = Button(button_frame, text="Start", font='Helvetica', fg="white", bg=self.BUTTONS_BG)
            qb.pack( side = LEFT,pady=20,padx=20)
            dismiss_button = Button(button_frame, text="Dismiss", font='Helvetica', fg="white", bg=self.BUTTONS_BG, command=top.destroy)
            dismiss_button.pack( side= RIGHT, pady=20,padx=20)
            button_frame.pack(fill=X)

            code_frame = LabelFrame(top,bg='white',text="Authorization Code")
            code_frame_top = Frame(code_frame, bg='white')
            code_frame_top.pack(fill=X)
            code_frame_bot = Frame(code_frame, bg='white')
            code_frame_bot.pack(fill=X)
            auth_code = StringVar()
            code_entry = Entry(code_frame_top, textvariable = auth_code, font='Helvetica', width=40)
            self.__install_soft_keyboard(code_entry,auth_code)
            code_entry.pack(side=LEFT, padx=20, pady=20)
            paste_button = Button(code_frame_top,text="Paste",font='Helvetica',fg='white',bg=self.BUTTONS_BG, command = lambda *args: auth_code.set(self.clipboard_get()))
            paste_button.pack(side=RIGHT,padx=20,pady=20)

            ok_button = Button(code_frame_bot,text="Authenticate", font='Helvetica',fg='white',bg=self.BUTTONS_BG, command=top.destroy)
            ok_button.pack(fill=X,padx=20,pady=20)



            message_box = Text(text_frame, font=('Helvetica',10), height=12)
            message_box.insert(INSERT,"""You need to authorize this application to access you data

Click the Start button below:
    - This will launch a web browser
    - You will land on an authorization page for this app to
       - send emails
       - upload pictures
""")
            message_box.pack(fill=X)

            def authenticate():
                button_frame.pack_forget()
                code_frame.pack(fill=X, padx=10, pady=10)
                import webbrowser
                webbrowser.open(URI)

            qb.config(command=authenticate)


            self.wait_window(top)
            #update displayed
            print "returning code %s"%auth_code.get()
            return auth_code.get()
        print "Trying the connexion"
        #try to connect
        try:

            self.google_service = oauth2services.OAuthServices(constants.APP_ID_FILE,constants.CREDENTIALS_STORE_FILE,self.user_mail_var.get() )
            print self.google_service.refresh()
        except Exception as error:
            self.google_service = None
            print error
            import traceback
            traceback.print_exc()
        self.__check_credentials_files()