Esempio n. 1
0
def startbtsync(request):
    if isbtsyncactive():
        return HttpResponseRedirect('/')

    # If wrong config file structure raise an exception
    if 'btsync_conf_file' not in config.keys():
        return HttpResponse('Klucz btsync_conf_file nie istnieje w pliku konfiguracyjnym')

    # If btsync-folder doesn't exist, create it
    btsyncconf = loadJSON(config['btsync_conf_file'])
    if not os.path.exists(btsyncconf['storage_path']):
        os.makedirs(btsyncconf['storage_path'])

    # If BTSync config file doesn't exist, create a new one
    if not path.isfile(config['btsync_conf_file']):
        createemptybtsyncconfigfile(config)

    # Start BTSync process
    if platform.system() == 'Windows':
        pass
    elif platform.system() == 'Linux':
        pid = subprocess.Popen([config['btsync_exe_file'], '--config', config['btsync_conf_file']])
        while not isbtsyncactive():     pass
        print 'BTSync started PID = ' + str(pid)

        if 'uid' not in config.keys():
            print 'taking UID'
            config['uid'] = getUID(config['btsync_server_address'])
            print config['uid']
            saveJSON(os.path.join(config['application_path'], 'config.json'), config)

    return HttpResponseRedirect('/')
Esempio n. 2
0
def addnewfolder(folderpath, identity, secret='', option=''):
    # CHECKING IF DIR EXISTS
    if not os.path.isdir(folderpath):
        pass

    # GETTING SECRET
    if secret == '':
        js = json.loads(requests.get("http://" + config['btsync_server_address'] + "/api", params={
            'method': 'get_secrets'
        }, auth=('team', 'sync')).text)
        secret = js[option]
        # print "option: " + option + ",secret " + js[option]
        if 'read_write' not in js.keys():
            print "Blad podczas uzyskiwania secreta"
            return

    # ADDING FOLDER
    js2 = json.loads(requests.get("http://" + config['btsync_server_address'] + "/api", params={
        'method': 'add_folder',
        'dir': folderpath,
        'secret': secret
    }, auth=('team', 'sync')).text)

    if js2['error'] == 0:
        print "Dodano folder " + folderpath + " o secrecie " + secret
    else:
        print "Blad podczas dodawania folderu."
        # dolozyc obsluge bledu (najczesciej nie mozna dodac bo folder nie jest pusty)

    # UPDATING CONFIG AND ADDING USER TO .USERS FOLDER
    config['identities'][secret] = identity
    saveJSON(config['application_path'] + '/config/config.json', config)
Esempio n. 3
0
def writecomment(request):
    try:
        if not checkConnection():
            return HttpResponseServerError('Brak połączenia z Internetem.')

        data = json.loads(request.body)

        if len(data['comment']) == 0:
            return HttpResponseServerError('Treść komentarza nie może być pusta.')

        newcomment = {
            'uid': config['uid'],
            'timestamp': gettimestamp(),
            'readby': {},
            'comment': data['comment'],
            'history': []
        }
        newcomment['readby'][config['uid']] = newcomment['timestamp']
        newcomment['history'].append({'timestamp': newcomment['timestamp'], 'comment': newcomment['comment']})

        fullpath = os.path.join(data['fullthreadpath'], newcomment['timestamp'] + fileseparator + config['uid'])

        saveJSON(fullpath, newcomment)

        return JsonResponse(newcomment, safe=False)
    except:
        return HttpResponseServerError('Wystąpił nieznany błąd podczas dodawania komentarza.')
Esempio n. 4
0
def writenewthread(request):
    try:
        if not checkConnection():
            return HttpResponseServerError('Brak połączenia z Internetem.')

        # getting and preparing data
        timestamp = gettimestamp()
        data = json.loads(request.body)

        folderpath = data['folderpath']
        fileabout = '' if data['fileabout'] == "<brak>" else os.path.join(data['insidepath'], data['fileabout'])
        fullthreadpath = os.path.join(folderpath, '.Comments', data['insidepath'][1:], timestamp + fileseparator + config['uid'])

        response = {
            'timestamp': timestamp,
            'name': data['topic'],
            'type': 'thread',
            'numberofcomments': 1,
            'unreadcomment': False,
            'lastcomment': timestamp,
            'fullpath': fullthreadpath,
            'insidepath': fullthreadpath.replace(folderpath + '/.Comments', ''),
        }
        meta = {
            'uid': config['uid'],
            'timestamp': timestamp,
            'topic': data['topic'],
            'fileabout': fileabout
        }
        comment = {
            'uid': config['uid'],
            'timestamp': timestamp,
            'comment': data['comment'],
            'readby': {},
            'history': []
        }
        comment['readby'][config['uid']] = timestamp
        comment['history'].append({'timestamp': timestamp, 'comment': comment['comment']})

        if os.path.isdir(fullthreadpath):
            return HttpResponseServerError('Podany wątek już istnieje.')

        os.makedirs(fullthreadpath)
        saveJSON(os.path.join(fullthreadpath, 'meta'), meta)
        saveJSON(os.path.join(fullthreadpath, timestamp + fileseparator + config['uid']), comment)

        return JsonResponse(response, safe=False)
    except:
        return HttpResponseServerError('Wystąpił nieznany błąd podczas dodawania nowego wątku.')
Esempio n. 5
0
def editcomment(request):
    try:
        if not checkConnection():
            return HttpResponseServerError('Brak połączenia z Internetem.')

        editedcomment = json.loads(request.body)['comment']
        threadfullpath = json.loads(request.body)['threadfullpath']
        #print json.dumps(editedcomment, indent=4)
        #print threadfullpath

        commentpath = os.path.join(threadfullpath, editedcomment['timestamp'] + fileseparator + editedcomment['uid'])

        comment = loadJSON(commentpath)
        comment['history'].append({'timestamp': gettimestamp(), 'comment': editedcomment['comment']})
        comment['comment'] = editedcomment['comment']

        saveJSON(commentpath, comment)

        return JsonResponse({}, safe=False)
    except:
        return HttpResponseServerError('Wystąpił nieznany błąd podczas edycji komentarza.')
Esempio n. 6
0
def deleteFolder(request):
    try:
        data = json.loads(request.body)

        js = json.loads(requests.get("http://" + config['btsync_server_address'] + "/api", params={
            'method': 'remove_folder',
            'secret': data['secret']
        }, auth=('team', 'sync')).text)

        if js['error'] == 0:
            # POPPING IDENTITY FROM LIST OF OUR IDENTITIES IN CONFIG FILE
            if data['secret'] in config['identities'].keys():
                config['identities'].pop(data['secret'])

            # SAVING CONFIG FILE
            saveJSON(config['application_path'] + '/config.json', config)

            return HttpResponse('Usunięto folder.')
        else:
            return HttpResponseServerError('Wystąpił błąd podczas usuwania folderu.')
    except (Exception):
        return HttpResponseServerError('Wystąpił nieznany błąd podczas usuwania folderu.')
Esempio n. 7
0
def getcomments(request):
    result = []

    try:
        data = json.loads(request.body)
        fullthreadpath = data['fullthreadpath']
        sortinguid = data['sortinguid']

        for commentfile in os.listdir(fullthreadpath):
            if commentfile == 'meta':
                continue

            comment = loadJSON(os.path.join(fullthreadpath, commentfile))

            if config['uid'] not in comment['readby'].keys():
                comment['readby'][config['uid']] = gettimestamp()

            saveJSON(os.path.join(fullthreadpath, commentfile), comment)

            comment['editing'] = False                                  # need for UI purposes
            comment['historing'] = False                                # need for UI purposes

            result.append(comment)

        if sortinguid != '':
            for res in result:
                if sortinguid not in res['readby'].keys():
                    result.remove(res)
                else:
                    res['timestamp'] = res['readby'][sortinguid]

        result = sorted(result, key=lambda comm: comm['timestamp'])

        return JsonResponse({'comments': result, 'stats': getstats(result)}, safe=False)
    except Exception:
        return HttpResponseServerError('Wystąpił nieznany błąd podczas pobierania komentarzy.')
Esempio n. 8
0
def addFolder(request):
    try:
        # receiving keys: path, secret, identity
        data = json.loads(request.body)

        # CHECKING IF USER PASSED NO IDENTITY
        if data['identity'] == '':
            return HttpResponseServerError('Pole tożsamości jest puste.')

        # CHECKING IF USER PASSED TOO LONG IDENTITY
        if len(data['identity']) > 25:
            return HttpResponseServerError('Zbyt długa tożsamość.')

        # CHECKING IF DIR EXISTS
        if not os.path.isdir(data['path']):
            return HttpResponseServerError('Wybrany folder nie istnieje.')

        # CHECKING IF DIR IS EMPTY
        if os.listdir(data['path']) != []:
            return HttpResponseServerError('Wybrany folder nie jest pusty.')

        #CHECKING SECRET
        if len(data['secret']) != 33 and len(data['secret']) != 0:
            return HttpResponseServerError('Wpisany secret ma złą długość.')

        # GETTING SECRET
        if data['secret'] == '':
            js = json.loads(requests.get("http://" + config['btsync_server_address'] + "/api", params={
                'method': 'get_secrets'
            }, auth=('team', 'sync')).text)

            if 'read_write' not in js.keys():
                return HttpResponseServerError('Wystąpił błąd podczas uzyskiwania secreta.')

            data['secret'] = js['read_write']

        # ADDING FOLDER
        js2 = json.loads(requests.get("http://" + config['btsync_server_address'] + "/api", params={
            'method': 'add_folder',
            'dir': data['path'],
            'secret': data['secret']
        }, auth=('team', 'sync')).text)

        if js2['error'] != 0:
            return HttpResponseServerError('Wystąpił błąd podczas dodawania folderu.')

        # UPDATING CONFIG
        config['identities'][data['secret']] = data['identity']
        saveJSON(config['application_path'] + '/config.json', config)

        # CREATING .COMMENTS DIRECTORY
        if not os.path.isdir(data['path'] + '/.Comments'):
            os.makedirs(data['path'] + '/.Comments')

        # CREATING .USERS DIRECTORY
        if not os.path.isdir(data['path'] + '/.Users'):
            os.makedirs(data['path'] + '/.Users')

        # ADDING USER TO .USERS DIRECTORY
        saveJSON(data['path'] + '/.Users/' + config['uid'] + '.json', {
            'uid': config['uid'],
            'identity': data['identity']
            # todo another config goes here for example color of comments
        })

        return HttpResponse('Dodano folder.')
    except (Exception):
        return HttpResponseServerError('Wystąpił nieznany błąd podczas dodawania folderu.')
Esempio n. 9
0
from common import getReliableStations, getTotalHours, getHourlyString, saveJSON, makeGeoJSON, makeDataImage

# All daily records
files = sorted(glob.glob('????-??-??-*.json'), key=os.path.getmtime)

# get a common list of station across daily records
stations = getReliableStations(files)

# make a GeoJSON of it
stationsList = makeGeoJSON(stations, 'station')

print len(stations), len(stationsList)

hoursList = getTotalHours(files)

saveJSON(hoursList, "hours.json")

database = {}
for filename in files:
    with open(filename) as data_file:
        data = json.load(data_file)
        for station in stationsList:
            if station not in database:
                database[station] = {}
            if station in data:
                for cycle in data[station]['cycles']:
                    hour = getHourlyString(
                        data[station]['cycles'][cycle]['time'])
                    if hour not in database[station]:
                        database[station][hour] = {}
                        database[station][hour]['temp'] = data[station][