Beispiel #1
0
col.save()

# Export the filtered deck
exporter = AnkiPackageExporter(col)
exporter.did = base_deck_id
exporter.exportInto(OUTPUT_PATH)

# Clean up collection
for did in col.decks.allIds():
    col.decks.rem(did, True)
col.save()

print('Export Deck: Success')

# Upload new deck to dropbox
dbx = dropbox.Dropbox(DROPBOX_AUTH_TOKEN)
file = open(OUTPUT_PATH, "rb")
dropbox_path = '/Gamegogakuen JP Anki Cards/' + OUTPUT_FILE_NAME

dbx.files_upload(file.read(), dropbox_path, mode=WriteMode.overwrite)

print('Upload to Dropbox: Success')

# Clean up exported deck
file.close()
os.remove(OUTPUT_PATH)

# Update LAST_MODIFIED timestamp in database
now = int(round(time.time() * 1000))
timestamps = db.timestamps
#!/usr/bin/env python3

import dropbox
from dropbox import DropboxOAuth2FlowNoRedirect
'''
This example walks through a basic oauth flow using the existing long-lived token type
Populate your app key and app secret in order to run this locally
'''
APP_KEY = ""
APP_SECRET = ""

auth_flow = DropboxOAuth2FlowNoRedirect(APP_KEY, APP_SECRET)

authorize_url = auth_flow.start()
print("1. Go to: " + authorize_url)
print("2. Click \"Allow\" (you might have to log in first).")
print("3. Copy the authorization code.")
auth_code = input("Enter the authorization code here: ").strip()

try:
    oauth_result = auth_flow.finish(auth_code)
except Exception as e:
    print('Error: %s' % (e, ))
    exit(1)

with dropbox.Dropbox(oauth2_access_token=oauth_result.access_token) as dbx:
    dbx.users_get_current_account()
    print("Successfully set up client!")
Beispiel #3
0
    def upload_file(self,file_from, file_to):
        dbx = dropbox.Dropbox(self.access_token)

        with open(file_from, 'rb') as f:
            dbx.files_upload(f.read(), file_to)
Beispiel #4
0
 def __init__(self, start_date, end_date, mock_flag):
     self.start_date = start_date
     self.end_date = end_date
     self.ext = LBExtract(start_date, end_date, mock_flag)
     self._set_predata()
     self.dbx = dropbox.Dropbox(mc.DROPBOX_KEY)
Beispiel #5
0
def uploadToDropbox(path):
    dbx = dropbox.Dropbox(os.environ.get('DROPBOX_ACCESS_TOKEN'))
    response = dbx.files_upload(getPicture(path),
                                '/knowit-18/' + path,
                                mode=WriteMode('overwrite', None))
Beispiel #6
0
#!/usr/bin/python

import dropbox
import os.path
import time
from requests import get

timestr = time.strftime("%Y%m%d-%H%M%S")
ip = get('https://api.ipify.org').text

if os.path.exists('/home/pi/log-rpi-zero-w.txt'):
    f = open("/home/pi/log-rpi-zero-w.txt", "a+")
    f.write(timestr + " : " + ip + "\n")
else:
    f = open("/home/pi/log-rpi-zero-w.txt", "a+")
    f.write(
        "********************\n***IP Address Log***\n********************\n\n")
    f.write(timestr + " : " + ip + "\n")

time.sleep(3)

minute = time.strftime("%M")
#print minute[1]

if minute[1] == "0":
    d = dropbox.Dropbox('<<<Dropbox key>>>')
    with open("/home/pi/log-rpi-zero-w.txt", "rb") as f2:
        d.files_upload(f2.read(),
                       '/IP_Log/log-rpi-zero-w.txt',
                       mode=dropbox.files.WriteMode("overwrite"))
def main():
    """Main program.

    Parse command line, then iterate over files and directories under
    rootdir and upload all files.  Skips some temporary files and
    directories, and avoids duplicate uploads by comparing size and
    mtime with the server.
    """
    args = parser.parse_args()
    if sum([bool(b) for b in (args.yes, args.no, args.default)]) > 1:
        print('At most one of --yes, --no, --default is allowed')
        sys.exit(2)
    if not args.token:
        print('--token is mandatory')
        sys.exit(2)

    folder = args.folder
    rootdir = os.path.expanduser(args.rootdir)
    print('Dropbox folder name:', folder)
    print('Local directory:', rootdir)
    if not os.path.exists(rootdir):
        print(rootdir, 'does not exist on your filesystem')
        sys.exit(1)
    elif not os.path.isdir(rootdir):
        print(rootdir, 'is not a folder on your filesystem')
        sys.exit(1)

    dbx = dropbox.Dropbox(args.token)

    for dn, dirs, files in os.walk(rootdir):
        subfolder = dn[len(rootdir):].strip(os.path.sep)
        listing = list_folder(dbx, folder, subfolder)
        print('Descending into', subfolder, '...')

        # First do all the files.
        for name in files:
            fullname = os.path.join(dn, name)
            if not isinstance(name, six.text_type):
                name = name.decode('utf-8')
            nname = unicodedata.normalize('NFC', name)
            if name.startswith('.'):
                print('Skipping dot file:', name)
            elif name.startswith('@') or name.endswith('~'):
                print('Skipping temporary file:', name)
            elif name.endswith('.pyc') or name.endswith('.pyo'):
                print('Skipping generated file:', name)
            elif nname in listing:
                md = listing[nname]
                mtime = os.path.getmtime(fullname)
                mtime_dt = datetime.datetime(*time.gmtime(mtime)[:6])
                size = os.path.getsize(fullname)
                if (isinstance(md, dropbox.files.FileMetadata) and
                        mtime_dt == md.client_modified and size == md.size):
                    print(name, 'is already synced [stats match]')
                else:
                    print(name, 'exists with different stats, downloading')
                    res = download(dbx, folder, subfolder, name)
                    with open(fullname) as f:
                        data = f.read()
                    if res == data:
                        print(name, 'is already synced [content match]')
                    else:
                        print(name, 'has changed since last sync')
                        if yesno('Refresh %s' % name, False, args):
                            upload(dbx, fullname, folder, subfolder, name,
                                   overwrite=True)
            elif yesno('Upload %s' % name, True, args):
                upload(dbx, fullname, folder, subfolder, name)

        # Then choose which subdirectories to traverse.
        keep = []
        for name in dirs:
            if name.startswith('.'):
                print('Skipping dot directory:', name)
            elif name.startswith('@') or name.endswith('~'):
                print('Skipping temporary directory:', name)
            elif name == '__pycache__':
                print('Skipping generated directory:', name)
            elif yesno('Descend into %s' % name, True, args):
                print('Keeping directory:', name)
                keep.append(name)
            else:
                print('OK, skipping directory:', name)
        dirs[:] = keep
dropbox_access_token = "oiMRWc9DAhoAAAAAAAAAAWALYwC53_XkoaDXh9K3AdBmraK-G4sh6a1cEPiJT3q5"
from tabulate import tabulate
import boto3
from boto3.dynamodb.conditions import Key

app = Flask(__name__, static_url_path="/images", static_folder="images")
flag = 0
users = {}
curr_repo = 0
curr_branch = 0
curr_folder = 0
obj2 = 0
dynamodb = boto3.resource('dynamodb', region_name='us-east-1')
#dropbox_path= "/test.py"
#computer_path="./test.py"
client = dropbox.Dropbox(dropbox_access_token)
print("[SUCCESS] dropbox account linked")


@app.route('/')
def home():
    return render_template('login.html')


@app.route('/registered', methods=['GET', 'POST'])
def after_register():
    username = request.form['username']
    password = request.form['password']
    email = request.form['email']
    if username not in users:
        put_user(username, password)
Beispiel #9
0
 def initialize(self):
     assert config.initialized
     self.dbx = dropbox.Dropbox(self.get_auth_token())
Beispiel #10
0
 def _clientv2(self):
     toret = getattr(self._local, '_clientv2', None)
     if toret is None:
         self._local._clientv2 = toret = dropbox.Dropbox(
             self._access_token, session=self._db_session)
     return toret
Beispiel #11
0
usage:
    python delete_folder.py <folder path> [<API key>]
"""


def delete_folder(path, dbx):
    print("deleting {}".format(path))
    try:
        dbx.files_delete_v2(path)
    except dropbox.exceptions.ApiError as e:
        if type(e.error) is dropbox.files.DeleteError:
            print("too many files! Moving down a level from {}".format(path))
            content = dbx.files_list_folder(path)
            print("found {} files in {}".format(len(content.entries), path))
            for file in content.entries:
                delete_folder(file.path_lower, dbx)
        else:
            raise (e)


if __name__ == '__main__':
    import sys
    if len(sys.argv) == 2:
        dbx = dropbox.Dropbox(input("input your API key: "))
        delete_folder(sys.argv[1], dbx)
    elif len(sys.argv) == 1:
        delete_folder(sys.argv[1], sys.argv[2])
    else:
        print(USAGE)
Beispiel #12
0
                   help='base URL for links')
parms.add_argument('--cursor', default=None, help='Dropbox cursor to use')
parms.add_argument(
    '--cfile',
    default='${cursordir}/copywebfiles.txt',
    help='File containing Dropbox cursor; will be created/updated')
myglobals.setup(parms, connect=False)

if not parms.dropboxtoken:
    sys.stderr.write(
        'ERROR: No access token provided.  Generate one from the app console on the web.'
    )
    sys.exit(1)

# Access Dropbox; check to make sure we actually have access
dbx = dropbox.Dropbox(parms.dropboxtoken)
try:
    dbx.users_get_current_account()
except AuthError as err:
    sys.stderr.write(
        "ERROR: Invalid access token; try re-generating an access token from the app console on the web."
    )
    sys.exit(2)

path = parms.dropboxfolder
if not path.startswith('/'):
    path = '/' + path
localpath = os.path.expandvars(parms.outdir)
linkpath = parms.baseurl
if not linkpath.endswith('/'):
    linkpath = linkpath + '/'
Beispiel #13
0
"""
#uploading file
f = open('test1.cpp', 'rb')
dbx.files_upload(f.read(),'/backup/test1.cpp')
f.close()
"""
"""
#downloading file
dbx.files_download_to_file('./backup/miuki.jpg','/43946355.jpg')
"""
"""
# アプリディレクトリにあるファイルの一覧を表示
for entry in dbx.files_list_folder('').entries:
    print(entry.name)
"""
dbx = dropbox.Dropbox(
    'JUSy-o0vW0gAAAAAAAAAnWt-oe9m54xJMIiK6xoR7aPuUDKdJdCc0_hU1POafwNA')
dbx.users_get_current_account()


def writing(words):
    now = datetime.datetime.now()
    dbx.files_download_to_file('log.txt', '/backup/log.txt')
    with open("log.txt", "a") as f:
        f.write(words + '\t{0:%Y%m%d%H%M%S}\n'.format(now))
    with open('log.txt', 'rb') as f:
        dbx.files_upload(f.read(),
                         '/backup/log.txt',
                         mode=WriteMode('overwrite'))


writing("hello world")
def connect_to_dropbox(token):
    return dropbox.Dropbox(token)
Beispiel #15
0
 def connect(self):
     self.api = dropbox.Dropbox(self.key)
     print("Conexión exitosa")
     print("Bienvenido!! " + self.getAccountInfo().name.display_name)
Beispiel #16
0
	for a in assignments_list:
		alink = get_download_link(dbx,course_code,a.filename,'assignments')
		try:
			asub = AssignmentSubmission.objects.get(student=student,assignment=a)
			sfilename = student.username + '|' + asub.solution_file
			slink = get_download_link(dbx,course_code,sfilename,'submissions')
			submitted.append((asub,alink,slink))
		except AssignmentSubmission.DoesNotExist:
			asub = None
			not_submitted.append((a,alink))
	data = {'course_code':course_code,'submitted':submitted,'unsubmitted':not_submitted}
	return render(request,'students/course_assignments.html',data)

#dropbox data
access_token = 'oWw_iYHAydcAAAAAAAAA1UQIMnh-LpfBDd9mnqNlNcfTg5dCdepmD42C2htSajap'
dbx = dropbox.Dropbox(access_token)

@login_required(login_url="/login/login/")
@user_passes_test(student_check,login_url=settings.LOGIN_URL)
def submit_assignment(request):
	course_code = request.GET.get('code')
	aname = request.GET.get('aname')
	ccourse = CurrentCourse.objects.get(course_code=course_code)
	assignment = Assignment.objects.get(course=ccourse,name=aname)
	student = Student.objects.get(username=request.user.username)
	alink = get_download_link(dbx,course_code,assignment.filename,'assignments')
	sfile = None
	data = {'assgn':assignment,'course_code':course_code,'alink':alink}
	if request.method=='POST' and request.FILES['sfile']:
		sfile = request.FILES['sfile']
		if sfile is not None:
Beispiel #17
0
import dropbox
import string
import cv2
from docopt import docopt
import glob
import logging
import sys
from PIL import Image
import numpy as np
import json
from oauth2client.service_account import ServiceAccountCredentials
import gspread

bot = commands.Bot(command_prefix='m!',help_command=None)
dbxtoken = os.environ['dbxtoken']
dbx = dropbox.Dropbox(dbxtoken)
dbx.users_get_current_account()
BOT_TOKEN = os.environ['TOKEN']
dbxtoken = os.environ['dbxtoken']
dbx = dropbox.Dropbox(dbxtoken)
dbx.users_get_current_account()
scope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive']
dbx.files_download_to_file('src/miyakobot-spreadsheet.json', '/miyakobot/miyakobot-spreadsheet-f0f4058290d2.json', rev=None)
credentials = ServiceAccountCredentials.from_json_keyfile_name('src/miyakobot-spreadsheet.json', scope)
gc = gspread.authorize(credentials)
SPREADSHEET_KEY = os.environ['SpreadSheet']
worksheet = gc.open_by_key(SPREADSHEET_KEY).sheet1

cogs = [
    'cogs.help',
    'cogs.miyako',
Beispiel #18
0
def __dbx_conn__():
    """ Function returns a connection to Dropbox """
    global __dbx
    if __dbx is None:
        __dbx = dropbox.Dropbox(__TOKEN)
    return __dbx
Beispiel #19
0
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
import qrcode
import random
import dropbox
from django.conf import settings
import io

dbx = dropbox.Dropbox(settings.DROPBOX_ACCESS_TOKEN)

WIDTH = 640
HEIGHT = 480


def make_image(first_name, last_name, qr_hash):
    image = Image.new('RGB', (WIDTH, HEIGHT))
    pixels = image.load()

    for k in range(0, WIDTH):
        for j in range(0, HEIGHT):
            if j <= HEIGHT / 4:
                pixels[k, j] = (0, 47, 108)
            else:
                pixels[k, j] = (255, 255, 255)

    img2 = Image.open("administration/nametag/heading.png")
    area = (20, 0)
    image.paste(img2, area)

    qr = qrcode.QRCode(
Beispiel #20
0
def main() -> None:
    """
    Main program
    Get token, login to dropbox, upload/download folder, overwrite
    :return: None
    """
    # Get the token since it will always be in the dbxupdate directory
    path_to_token = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'token.txt')
    with open(path_to_token) as files:
        token = files.read().strip()

    dbx = dropbox.Dropbox(token)

    parser = argparse.ArgumentParser()
    parser.add_argument("path",
                        help="Folder name to be uploaded or downloaded")
    parser.add_argument("homepath",
                        help="Home path (probably /home/pi/ on RPI or ~/Python3/ on Mac")
    parser.add_argument("finalfolder",
                        help="Final parent folder to move the updated Dropbox folder to")
    parser.add_argument("-push", "--push", action="store_true",
                        help="Push this folder to Dropbox")
    parser.add_argument("-pull", "--pull", action="store_true",
                        help="Pull this folder from Dropbox and overwrite existing")
    args = parser.parse_args()

    temp_folder = os.path.join(args.homepath, 'Dropbox')
    final_folder = args.finalfolder

    if args.pull:
        if os.path.exists(args.homepath):
            # Make sure homepath exists before cd'ing
            os.chdir(args.homepath)
        if not os.path.exists(temp_folder):
            os.mkdir('Dropbox')
            remove_dropbox = True
        else:
            remove_dropbox = False

        list_names = get_filenames(dbx, args.path)

        for file in list_names:
            if '__pycache__' not in file:
                if capwords(args.path) == args.path:
                    # Dealing with 'Updater'
                    file1 = file.replace(args.path.lower(), capwords(args.path))
                    file1 = file1[1:]
                elif args.path[0].isupper() and args.path == 'MatchThreader':
                    # Dealing with MatchThreader
                    file1 = file.replace('matchthreader', args.path)
                    file1 = file1[1:]
                else:
                    # Dealing with all lowercase folder name
                    file1 = file[1:]
                print('Getting {}'.format(file))
                updated_folder_bytes = download_from_dropbox(dbx, file)
                put_in_folder(updated_folder_bytes, file1, temp_folder, args.path)

        if args.path == 'MatchThreader':
            move_rpi_files()

        move_folder(os.path.join(temp_folder, args.path), final_folder, args.path)

        if remove_dropbox:
            if 'Dropbox' in os.getcwd():
                os.chdir('..')

            os.rmdir('Dropbox')

    elif args.push:
        if args.path == 'MatchThreader':
            list_dirs = os.listdir(os.path.join(args.homepath, args.path))
            basepath = args.homepath
        else:
            list_dirs = os.listdir(os.path.join(args.homepath, args.path))
            basepath = args.homepath
        for direc in list_dirs:
            if '.DS_Store' not in direc and '__pycache__' not in direc and\
                    not direc.endswith('pyc') and not direc.endswith('log'):
                filename = os.path.join(basepath, args.path, direc)
                dropbox_filename = os.path.join('/{}/'.format(args.path), direc)
                with open(filename, 'rb') as f:
                    print('Uploading {}'.format(dropbox_filename))
                    dbx.files_upload(f.read(), dropbox_filename,
                                     mode=dropbox.files.WriteMode('overwrite'))
    else:
        raise Exception("You need to specify -push or -pull")
    trial_num = []
    wavFiles = []
    for x in range(len(fentries)):
        fname = fentries[x].name
        if fname[len(fname)-4:len(fname)].lower() == '.wav' and fname!='diotic_volstim.wav':
            trial_num.append(int(fname[fname.find('trial_')+6:fname.find('.wav')]))
            wavFiles.append(fname)
    sortIndex = sorted(range(len(trial_num)), key = lambda k: trial_num[k])
    wavFiles = [wavFiles[i] for i in sortIndex]
    return wavFiles

with open('../../SnapOnlineExperiments/dbAPIkey.json') as f:
    APIkey = json.load(f)

dbxAPIkey = APIkey['dbxAPIkey'] #importing API key from json file. Doing this to keep key hidden from public repo
dbx = dropbox.Dropbox(dbxAPIkey)

# Find detailed documentation here https://snaplabonline.com/task/howto/

AM =64
trial_cond = 1

json_fname = 'AMphi_AMIncoh_dichotic' + str(AM) + '.json'
instructions = ["Welcome to the actual experiment! "]
feedback = True
holdfeedback = False
feedbackdur = 750 #duration of feedback in ms
serveraudio = False
#estimatedduration: 
randomize = False #randomize trial order
isi = 0 # interstimulus interval in ms
Beispiel #22
0
def dropbox_login():
    global db
    db = dropbox.Dropbox(config.get_value("dropbox", "token"))
    db.users_get_current_account()
Beispiel #23
0
	print("Checking file details")

	for entry in dbx.files_list_folder('').entries:
		print("File list is : ")
		print(entry.name)


# Run this script independently
if __name__ == '__main__':
	# Check for an access token
	if (len(TOKEN) == 0):
		sys.exit("ERROR: Looks like you didn't add your access token. Open up backup-and-restore-example.py in a text editor and paste in your token in line 14.")

	# Create an instance of a Dropbox class, which can make requests to the API.
	print("Creating a Dropbox object...")
	dbx = dropbox.Dropbox(TOKEN)

	# Check that the access token is valid
	try:
		dbx.users_get_current_account()
	except AuthError as err:
		sys.exit(
			"ERROR: Invalid access token; try re-generating an access token from the app console on the web.")

	try:
		checkFileDetails()
	except Error as err:
		sys.exit("Error while checking file details")

	print("Creating backup...")
	# Create a backup of the current settings file
Beispiel #24
0
    drop=True
    

else:
    print( ' to run the program you have to give a filename \n plot_speed.py inputfile ')
    print(' You have to give the token file')
    sys.exit(0)
    
# connect to dropbox
if(drop):
    f=open(sys.argv[2],"r")
    data =f.readline() #key for encryption
    data=data.strip('\n')

#connect to dropbox
    dbx=dropbox.Dropbox(data)
    myaccount = dbx.users_get_current_account()
    print('***************************dropbox************************************')
    print('*                                                                    *')
    print 'first = ',myaccount.name.given_name,'last = ',myaccount.name.surname  
    print 'email account = ',myaccount.email
    print('*                                                                    *')
    print('***************************dropbox************************************')

# get dropbox file

    file = '/LCWA/'+ sys.argv[1]
    dir = os.path.expanduser("~")
    file1 = dir+'/scratch/'+sys.argv[1]
    filename = dbx.files_download_to_file(file1,file)
    #print filename         
Beispiel #25
0
 def ensure_client(self, token):
     self.client = dropbox.Dropbox(token)
     return self
Beispiel #26
0
    def conectar(self, token):

        self.client = dropbox.Dropbox(token)
import os
import dropbox

dbx_token = os.getenv('DROPBOX_ACCESS_TOKEN')
dbx = None
dropbox_switch = False

if dbx_token is not None:
    print('DROPBOX_ACCESS_TOKEN found, extension storage has been enabled')
    dropbox_switch = True
    dbx = dropbox.Dropbox(dbx_token)


def download_extension(name):
    if dropbox_switch:
        os.makedirs('commands', exist_ok=True)
        dbx.files_download_to_file('commands/' + name + '.py', '/' + name + '.py')


"""
def read_config(name, section):
    if dropbox_switch:
        metadata, file = dbx.files_download('/' + name + '.ini')
        config = configparser.ConfigParser()
        config.read(file)
        print(file)
        return config[section]
    return []


def edit_config(file, section, item, value):
Beispiel #28
0
 def __init__(self):
     """Initialize."""
     self.access_token = os.environ["DROPBOX_TOKEN"]
     self.export_format = dropbox.paper.ExportFormat('markdown')
     self.dbx = dropbox.Dropbox(self.access_token)
     self.docs_list = self.dbx.paper_docs_list()
Beispiel #29
0
 def upload_file(self):
     dbx = dropbox.Dropbox(self.access_token)
     f = open(self.file_from, 'rb')
     dbx.files_upload(f.read(), self.file_to)
Beispiel #30
0
 def __init__(self):
     self.client = dropbox.Dropbox(settings.DROPBOX_API['access_token'])
     self.data_path = os.path.join(settings.BASE_DIR, 'spendalot', 'static', 'data_sources', 'dropbox')
     self.output_path = '/tmp/output.csv'