예제 #1
0
 def customCodes():
   globalVars = tools.initApp()
   if globalVars['arduino_map'] != None:
     #print(codes)
     #send json when token mode
     if('api' in request.path and 'token' in request.args):
       codes = db.get_customcodes(globalVars['arduino_map']['user_id'], session['app_id'], True)
       data = {}
       data['list_title'] = 'Your codes for ' + session['app_name']
       token = models.get_token('guest',flask_login.current_user.id)
       for i in range(len(codes)):
         codes[i]['url'] = url_for('customCode',code_id=codes[i]['id'])
         codes[i]['token'] = token
       data['elements']= codes
       response = app.response_class(
         response=json.dumps(data),
         mimetype='application/json'
       )
       return response  
     if request.args.get('saved'):
       flash('Your code is saved', 'success')  
     #manage post data from json request
     if request.method == 'POST':
       if request.is_json:
           jsonr = request.get_json()
           #print(json)
           db.set_customcode(globalVars['arduino_map']['user_id'], session['app_id'], None, jsonr['title'], jsonr['description'], \
             jsonr['published'], json.dumps(jsonr['customvars']), jsonr['customcode'])
           #print(request.data.decode())
     codes = db.get_customcodes(globalVars['arduino_map']['user_id'], session['app_id'])
     maxLeds = globalVars['arduino_map']['nb_cols']*globalVars['arduino_map']['nb_lines']      
     return render_template('customcodes.html', user_login=globalVars['user_login'], customcodes=codes, json=json, \
       max_leds=maxLeds, shelf_infos=globalVars['arduino_map'])
   abort(404)
예제 #2
0
 def editArduino(app_id):
   globalVars = tools.initApp()
   module = db.get_arduino_map(flask_login.current_user.id, app_id) #globalVars['arduino_map']
   if module:
     session['app_id'] = module['id']
     session['app_name'] = module['arduino_name']
     if request.method == 'POST':
       if 'module_name' in request.form:
         if db.set_module(request.form):
           return redirect(url_for('editArduino', _scheme='https', _external=True, app_id=request.form.get('module_id')))
       if request.is_json:
         mode = request.args.get('mode')
         if mode == 'preview':
           db.clean_request(app_id) #clean request for preview
         data = request.get_json()
         for numrow in data:
           positions = data[numrow]
           #print(positions)
           for i in range(len(positions)):
             pos = i+1        
             if mode == 'save': 
               db.set_position(app_id, pos, pos, numrow, 1, 'static', positions[i])            
             if mode == 'preview': #set distant request for preview
               db.set_request(app_id, pos, numrow, pos, 1, positions[i], 'static', 'server', 'add')
             if mode == 'remove': #remove all static 
               db.del_item_position(int(app_id), pos, 'static', numrow)        
     return render_template('module.html', user_login=flask_login.current_user.name, module=module, db=db, shelf_infos=globalVars['arduino_map'])
   abort(404) 
예제 #3
0
  def customCode(code_id):
    globalVars = tools.initApp()
    if globalVars['arduino_map'] != None:
      #manage post data from json request
      if request.method == 'POST':
        if request.is_json:
            jsonr = request.get_json()
            db.set_customcode(globalVars['arduino_map']['user_id'], session['app_id'], code_id, jsonr['title'], jsonr['description'], \
             jsonr['published'], json.dumps(jsonr['customvars']), jsonr['customcode'])

      data = db.get_customcode(globalVars['arduino_map']['user_id'], session['app_id'], code_id)
      customvars = ''
      if data and len(data['customvars'])>0:
        customvars = json.loads(data['customvars'])
        #send json when token mode
        if('api' in request.path and 'token' in request.args):
          response = app.response_class(
            response=json.dumps(data['customcode'].decode()),
            mimetype='application/json'
          )
          return response
        maxLeds = globalVars['arduino_map']['nb_cols']*globalVars['arduino_map']['nb_lines']
        return render_template('customcode.html', user_login=globalVars['user_login'], customcode=data['customcode'].decode(), \
          customvars=customvars, data=data, max_leds=maxLeds, effects=tools.get_leds_effects(), \
          shelf_infos=globalVars['arduino_map'])
    abort(404)
예제 #4
0
 def listCategories():
   globalVars = tools.initApp()
   #for mobile app
   if('api' in request.path and 'uuid' in request.args):
     categories = db.get_categories_for_app(globalVars['arduino_map']['user_id'], session['app_id'])
     data = {}
     data['list_title'] = session['app_name']
     token = models.get_token('guest',flask_login.current_user.id)
     if categories:
       for i in range(len(categories)):
         hasRequest = db.get_request_for_tag(session['app_id'], categories[i]['id'])
         categories[i]['url'] = url_for('locateBooksForTag',tag_id=categories[i]['id'])
         categories[i]['token'] = token
         categories[i]['hasRequest'] = hasRequest
         if categories[i]['color'] is not None:
           colors = categories[i]['color'].split(",")
           categories[i]['red'] = colors[0]
           categories[i]['green'] = colors[1]
           categories[i]['blue'] = colors[2]
       data['elements']=categories
       response = app.response_class(
         response=json.dumps(data),
         mimetype='application/json'
       )
       return response
     else:
       return ('', 204)
   #for web
   else:
     if globalVars['arduino_map'] != None:
       user_id = globalVars['arduino_map']['user_id']
       categories = db.get_categories_for_user(user_id)    
       return render_template('categories.html', user_login=globalVars['user_login'], categories=categories, \
       shelf_infos=globalVars['arduino_map'], uuid_encode=tools.uuid_encode(globalVars['arduino_map']['id_ble']))
     abort(404)
예제 #5
0
 def listAuthors():
   globalVars = tools.initApp()  
   if globalVars['arduino_map'] != None:
     #for mobile app 
     if('api' in request.path and 'uuid' in request.args):
       data = {}
       token = models.get_token('guest',flask_login.current_user.id)
       data['list_title'] = session['app_name']
       data['elements']=[]
       alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
       for j in range(len(alphabet)):
         '''data['elements'][j]={}
         data['elements'][j]['initial']=alphabet[j]'''
         #print(data)
         items = db.get_authors_for_app(session['app_id'], alphabet[j])
         if items:
           '''set url for authenticate requesting location from app'''
           for i in range(len(items)):
             items[i]['url'] = url_for('locateBooksForTag',tag_id=items[i]['id'])
             items[i]['token'] = token
             hasRequest = db.get_request_for_tag(session['app_id'], items[i]['id'])
             items[i]['hasRequest'] = hasRequest
           #data['elements'][j]['items'] = items
         data['elements'].append({'initial':alphabet[j],'items':items})
       response = app.response_class(
             response=json.dumps(data),
             mimetype='application/json'
       )
       return response
     #for web
     else:
       return render_template('authors.html', user_login=flask_login.current_user.name, db=db, \
           user_id=globalVars['arduino_map']['user_id'], shelf_infos=globalVars['arduino_map'], 
           uuid_encode=tools.uuid_encode(globalVars['arduino_map']['id_ble'])) 
   abort(404)    
예제 #6
0
 def borrowedBooks():
   globalVars = tools.initApp()
   if globalVars['arduino_map'] != None:
     addresses = db.get_borrowed_books(session.get('app_id'))
     data = {}
     data['list_title'] = "Borrowed books"
     books = []
     if addresses:
         #for address in addresses:
         for i in range(len(addresses)):
           book = db.get_book(addresses[i]['id_item'], globalVars['arduino_map']['user_id'])
           books.append(book)
           hasRequest = db.get_request_for_position(session.get('app_id'), addresses[i]['position'], addresses[i]['row'])
           books[i]['address'] = addresses[i]
           books[i]['hasRequest'] = hasRequest
           books[i]['arduino_name'] = globalVars['arduino_map']['arduino_name']
           books[i]['app_id'] = session.get('app_id')     
           books[i]['color'] = '255,0,0'
     data['items'] = books
     #send json when token mode
     if('api' in request.path and 'token' in request.args):
       response = app.response_class(
         response=json.dumps(data),
         mimetype='application/json'
       )
       return response     
     return render_template('borrowed.html', books=books, user_login=globalVars['user_login'], \
       shelf_infos=globalVars['arduino_map'])
   abort(404)
예제 #7
0
 def getBook(book_id):
   globalVars = tools.initApp()
   if globalVars['arduino_map'] != None:
     book = db.get_book(book_id, globalVars['arduino_map']['user_id'])
     if book:
       book['address']=None
       book['hasRequest']=None
       book['categories'] = []
       tags = db.get_tag_for_node(book['id'], 1)#book tags for taxonomy categories
       if tags:
         for i in range(len(tags)):
           book['categories'].append(tags[i]['tag'])
       app_modules = db.get_arduino_for_user(flask_login.current_user.id)
       for module in app_modules:
         address = db.get_position_for_book(module['id'], book['id'])
         if address:
           hasRequest = db.get_request_for_position(module['id'], address['position'], address['row'])
           book['address'] = address
           book['arduino_name'] = module['arduino_name']
           book['app_id'] = module['id']
           book['hasRequest'] = hasRequest
       #send json when token mode
       if('api' in request.path and 'token' in request.args):
         response = app.response_class(
           response=json.dumps(book),
           mimetype='application/json'
         )
         return response      
       return render_template('book.html', user_login=globalVars['user_login'], book=book, \
           shelf_infos=globalVars['arduino_map'], biblio_nb_rows=globalVars['arduino_map']['nb_lines'])
   abort(404)
예제 #8
0
    def ajaxPermutePosition():
        globalVars = tools.initApp()
        from_id = request.args.get('from_id')
        dest_id = request.args.get('dest_id')
        pos_from = db.get_position_for_book(session['app_id'], from_id)
        pos_dest = db.get_position_for_book(session['app_id'], dest_id)
        #test interval equality before permutation
        if pos_from['range'] != pos_dest['range']:
            message = {'success': False, 'dest_range': pos_dest['range']}
        else:
            #clean old positions
            db.del_item_position(session.get('app_id'), from_id, 'book',
                                 pos_from['row'])
            db.del_item_position(session.get('app_id'), dest_id, 'book',
                                 pos_dest['row'])
            #add new position for first book
            led_column_1 = db.set_position(session.get('app_id'), from_id, pos_dest['position'], pos_dest['row'], \
              pos_dest['range'], 'book', pos_dest['led_column'])
            #add new position for destination book
            led_column_2 = db.set_position(session.get('app_id'), dest_id, pos_from['position'], pos_from['row'], \
              pos_from['range'], 'book', pos_from['led_column'])
            message = {
                'success': True,
                from_id: led_column_1,
                dest_id: led_column_2
            }

        response = app.response_class(response=json.dumps(message),
                                      mimetype='application/json')
        return response
예제 #9
0
 def customCodeDelete():
   globalVars = tools.initApp()
   code_id = request.form['id']
   customcode = db.get_customcode(globalVars['arduino_map']['user_id'], session['app_id'], code_id)
   if customcode: 
     db.del_customcode(code_id, globalVars['arduino_map']['user_id'])
     flash('Code "{}" is deleted'.format(customcode['title']), 'warning')
     return redirect(url_for('customCodes', _scheme='https', _external=True))  
예제 #10
0
    def ajaxSort():
        globalVars = tools.initApp()
        book_ids = []

        if request.method == 'POST' and session.get('app_id'):

            if request.json and 'book_ids' in request.json:
                book_ids = request.json['book_ids']
                current_row = request.json['row']
            elif 'row' in request.form:
                current_row = request.form['row']
                book_ids = request.form.getlist('book[]')

            if len(book_ids) > 0:
                app_id = session.get('app_id')
                i = 0
                sortable = []
                for book_id in book_ids:
                    position = db.get_position_for_book(app_id, book_id)
                    if position:
                        interval = position['range']
                    else:
                        book = db.get_book(
                            book_id, globalVars['arduino_map']['user_id'])
                        interval = tools.led_range(
                            book, globalVars['arduino_map']['leds_interval'])
                    i += 1
                    db.set_position(app_id, book_id, i, current_row, interval,
                                    'book', 0)  #reinit led column

                #update new leds number
                positions = db.get_positions_for_row(app_id, current_row)
                for pos in positions:
                    led_column = db.get_led_column(app_id, pos['id_item'],
                                                   current_row,
                                                   pos['position'])
                    db.set_led_column(app_id, pos['id_item'], current_row,
                                      led_column)
                    sortable.append({
                        'book':
                        pos['id_item'],
                        'position':
                        pos['position'],
                        'fulfillment':
                        int(led_column + pos['range']),
                        'shelf':
                        current_row
                    })

            #save order for customcodes
            if 'customcode' in request.form:
                code_ids = request.form.getlist('code[]')
                sortable = db.sort_customcodes(
                    globalVars['arduino_map']['user_id'],
                    session.get('app_id'), code_ids)
            response = app.response_class(response=json.dumps(sortable),
                                          mimetype='application/json')
        return response
예제 #11
0
 def ajaxSetShelf(): 
   globalVars = tools.initApp()
   if request.method == 'GET' and request.args.get('rownum'):
     session['app_numshelf'] = int(request.args.get('rownum'))
   response = app.response_class(
       response=json.dumps(session['app_numshelf']),
       mimetype='application/json'
   )
   return response
예제 #12
0
 def setResetForModule():
     globalVars = tools.initApp()
     if globalVars['arduino_map'] != None:
         data = db.set_request_remove(
             session['app_id'])  #force remove for all module's request
         response = app.response_class(response=json.dumps(data),
                                       mimetype='application/json')
         return response
     abort(404)
예제 #13
0
  def ajaxSearch():
    globalVars = tools.initApp()
    term = request.args.get('term')
    data = {}
    if len(term) > 2:
      results = db.search_book(session['app_id'], term)
      #search for mobile app
      if request.method == 'GET' and request.args.get('token'):
        books = []   
        #when results
        if results:

          #search for tag
          tag_id = None
          tag_color = None        
          tag = db.get_tag(term)
          if tag:
            tag_id = tag['id']
            tag_color = tag['color']

          for i in range(len(results)):
            book = db.get_book(results[i]['id'], globalVars['arduino_map']['user_id'])
            books.append(book)
            app_modules = db.get_arduino_for_user(flask_login.current_user.id)
            for module in app_modules:
              address = db.get_position_for_book(module['id'], book['id'])
              if address:
                books[i]['address'] = address
                books[i]['hasRequest'] = False
                #for display mode, force set request 
                if 'display' in request.args and int(request.args.get('display'))==1:
                  db.set_request(session['app_id'], book['id'], address['row'], address['position'], \
                    address['range'], address['led_column'], 'book', 'server', 'add', tag_id, tag_color)
                  books[i]['hasRequest'] = True

            data['list_title'] = str(len(results)) 
            data['list_title'] += " books " if len(results) > 1 else " book "
            data['list_title'] += "for \""+request.args.get('term')+"\""
        #no result
        else:
          data['list_title'] = "No result for \""+request.args.get('term')+"\""
        data['items'] = books

      #autcomplete for book permutation for server
      else:
        data = []
        if results:
          for result in results:
            data.append({'id':result['id'], 'label':result['author']+' - '+result['title'], \
              'value':result['title']})

    response = app.response_class(
      response=json.dumps(data),
      mimetype='application/json'
    )
    return response  
예제 #14
0
  def myBookShelf():
    globalVars = tools.initApp()
    apiCall = False

    if globalVars['arduino_map'] != None:
      app_id = globalVars['arduino_map']['id']

      if 'api' in request.path and 'uuid' in request.args:
        apiCall = True

      if 'app_numshelf' not in session:
        session['app_numshelf'] = 1
      shelfs = range(1,globalVars['arduino_map']['nb_lines']+1)
      elements = {}
      stats = {}
      statics = {}

      for shelf in shelfs:
        books = db.get_books_for_row(app_id, shelf) 
        statics[shelf] = db.get_static_positions(app_id, shelf)     
        if books:
          statBooks = db.stats_books(app_id, shelf)
          statPositions = db.stats_positions(app_id, shelf)
          positionRate = 0
          if statPositions['totpos'] != None:
            positionRate = round((statPositions['totpos']/globalVars['arduino_map']['nb_cols'])*100)
          stats[shelf] = {'nbbooks':statBooks['nbbooks'], 'positionRate':positionRate}        
          element = {}
          for row in books:     
            element[row['led_column']] = {'item_type':row['item_type'],'id':row['id'], \
        'title':row['title'], 'author':row['author'], 'position':row['position'], 'range':row['range'], \
        'borrowed':row['borrowed'], 'url':'/book/'+str(row['id'])}
            requested = db.get_request_for_position(app_id, row['position'], shelf) #get requested elements from server (mobile will be set via SSE)
            if requested:
              element[row['led_column']]['requested']=True

          for static in statics[shelf]:
            element[static['led_column']] = {'item_type':static['item_type'],'id':None, 'position':static['position']}
          elements[shelf] = sorted(element.items())
      bookstorange = db.get_books_to_range(globalVars['arduino_map']['user_id']) #books without position

      #return Json for API
      if apiCall:
        results = {'shelfInfos': globalVars['arduino_map'], 'storedBooks':elements, 'statsBooks':stats}
        response = app.response_class(
          response=json.dumps(results),
          mimetype='application/json'
        )
        return response

      #return html    
      return render_template('bookshelf.html',user_login=globalVars['user_login'], tidybooks=elements, \
          bookstorange=bookstorange, lines=shelfs, shelf_infos=globalVars['arduino_map'], \
          nb_lines=globalVars['arduino_map']['nb_lines'], max_cols=globalVars['arduino_map']['nb_cols'], \
          session=session, stats=stats, json_statics = statics)
    abort(404)
예제 #15
0
 def bookDelete():
   globalVars = tools.initApp()
   book_id = request.form['id']
   book = db.get_book(book_id, globalVars['arduino_map']['user_id'])
   if book: 
     db.clean_tag_for_node(book_id, 1)#clean tags for categories
     db.clean_tag_for_node(book_id, 2)#clean tags for authors
     db.del_book(book_id, globalVars['arduino_map']['user_id'])
     flash('Book "{}" is deleted'.format(book['title']), 'warning')
     return redirect(url_for('myBookShelf', _scheme='https', _external=True))
예제 #16
0
 def getCustomColors():
   globalVars = tools.initApp()
   user_id = globalVars['arduino_map']['user_id']
   dbcoords = db.get_customcolors(user_id, session['app_id'])
   if(dbcoords and dbcoords['coordinates']!='' and dbcoords['coordinates']!='{}'):
     response = app.response_class(
       response=dbcoords['coordinates'],
       mimetype='application/json'
     )
     return response
   abort(404) 
예제 #17
0
 def ajaxCategories():
   globalVars = tools.initApp()
   user_taxo = []
   other_categ = db.get_categories_for_term(request.args.get('term'))
   if other_categ:
     for i in range(len(other_categ)):
       user_taxo.append(other_categ[i]['tag'])
   response = app.response_class(
     response=json.dumps(user_taxo),
     mimetype='application/json'
   )
   return response
예제 #18
0
 def customCodeTemplate(template):
   globalVars = tools.initApp()
   if template=='timer':
     return render_template('_customcode_timer.html')
   if template=='sample':
     return render_template('_customcode_sample.html')
   if template=='wait':
     return render_template('_customcode_wait.html') 
   if template=='effect':
     effects = tools.get_leds_effects()
     return render_template('_customcode_effect.html', effects=effects)        
   abort(404)
예제 #19
0
    def locateBooksForTag(tag_id, methods=['GET', 'POST']):
        globalVars = tools.initApp()
        nodes = db.get_node_for_tag(tag_id,
                                    globalVars['arduino_map']['user_id'])
        tag = db.get_tag_by_id(tag_id, globalVars['arduino_map']['user_id'])
        if tag['color'] is not None:
            colors = tag['color'].split(",")
            tag['red'] = colors[0]
            tag['green'] = colors[1]
            tag['blue'] = colors[2]

        action = 'add'
        if ('action' in request.args):  #for add or remove
            action = request.args.get('action')

        client = 'server'
        if ('token' in request.args):
            client = 'mobile'

        positions = []
        for node in nodes:
            address = db.get_position_for_book(session['app_id'],
                                               node['id_node'])
            if address:
                book = db.get_book(node['id_node'],
                                   globalVars['arduino_map']['user_id'])

                #manage request
                db.set_request(session['app_id'], node['id_node'], address['row'], address['position'], address['range'], \
                  address['led_column'], 'book', client, action, tag_id, tag['color'])

                if tag['color'] is None:
                    tag['color'] = ''

                positions.append({'item':book['title'], 'action':action, 'row':address['row'], 'led_column':address['led_column'], \
                  'interval':address['range'], 'id_tag':tag_id, 'color':tag['color'], 'id_node':node['id_node'], 'client':client})
        '''get elements for block build'''
        positions.sort(key=tools.sortPositions)
        blocks = tools.build_block_position(positions, action)
        #print(blocks)

        #send json when token mode
        if ('api' in request.path and 'token' in request.args):
            response = app.response_class(response=json.dumps(blocks),
                                          mimetype='application/json')
            return response
        for i, book in enumerate(positions):
            flash('Location requested for book {}'.format(book['item']),
                  'info')
        return redirect(url_for('listAuthors', _scheme='https',
                                _external=True))
예제 #20
0
 def borrowBook():
   globalVars = tools.initApp()
   ret = []
   if('api' in request.path and 'token' in request.args):
     app_id = session['app_id']
     book_id = request.args.get('book_id')
     action = request.args.get('action')
     db.set_borrow_book(app_id, book_id, action)
     address = db.get_position_for_book(app_id, book_id)
     ret.append({'item':book_id,'action':'borrow','address':address}) 
     response = app.response_class(
       response=json.dumps(ret),
       mimetype='application/json'
     )
     return response    
예제 #21
0
 def customEffects():
   globalVars = tools.initApp()
   if globalVars['arduino_map'] != None:
     if('token' in request.args):
       effects = tools.get_leds_effects()
       data = {}
       data['list_title'] = 'Effects for ' + session['app_name']
       token = models.get_token('guest',flask_login.current_user.id)
       data['elements']= effects
       response = app.response_class(
         response=json.dumps(data),
         mimetype='application/json'
       )
       return response
   abort(404) 
예제 #22
0
 def ajaxTagColor(tag_id):
   globalVars = tools.initApp()
   if globalVars['arduino_map'] != None:  
     if request.method == 'POST':
       red = request.form['red'] 
       green = request.form['green'] 
       blue = request.form['blue']
       color = red+','+green+','+blue
       result = False
       if db.set_color_for_tag(globalVars['arduino_map']['user_id'], tag_id, color):
         result = True
       response = app.response_class(
         response=json.dumps(result),
         mimetype='application/json'
       )
       return response
예제 #23
0
 def jsonBookshelf():
     globalVars = tools.initApp()
     app_id = globalVars['arduino_map']['id']
     if request.method == 'GET' and request.args.get('row'):
         numrow = request.args.get('row')
         books = db.get_books_for_row(app_id, numrow)
         element = {}
         if books:
             for row in books:
                 element[row['led_column']] = {'item_type':row['item_type'],'id':row['id'], \
               'title':row['title'], 'author':row['author'], 'position':row['position'], 'url':'/book/'+str(row['id'])}
                 requested = db.get_request_for_position(
                     app_id, row['position'], numrow)
                 if requested:
                     element[row['led_column']]['requested'] = True
             element = sorted(element.items())
         response = app.response_class(response=json.dumps(element),
                                       mimetype='application/json')
         return response
예제 #24
0
 def newArduino(app_id = None):
   globalVars = tools.initApp()
   if flask_login.current_user.id == app.config['SHELF_ADMIN_EMAIL']:
     if app_id is not None:
       module = db.get_module(app_id)
     else:
       module = {}
     #user_id = globalVars['arduino_map']['user_id']
     users = db.get_users()
     if request.method == 'POST':
       #print(request.form)
       data = {}
       data['action'] = request.form.get('action')
       data['module_name'] = request.form.get('module_name')
       data['nb_lines'] = request.form.get('nb_lines')
       data['strip_length'] = request.form.get('striplength')
       ledspermeter = request.form.get('ledspermeter')
       leds_interval = (100/int(ledspermeter)) 
       nb_cols = round((float(data['strip_length'])/leds_interval)+0.5) # nb_leds per strip
       data['leds_interval'] = math.floor(leds_interval*100)/100 # interval btw leds in mm
       data['nb_cols'] = nb_cols
       data['id_user'] = request.form.get('user')
       #don't erease current BLE gatt 
       if request.form.get('module_id'):
         data['module_id'] = request.form.get('module_id')
         data['id_ble'] = module['id_ble']
       else:
         data['id_ble'] = "xxxx" #set empty id_ble
       #save module, set user_app, and set id_ble
       new_module = db.set_module(data)
       if 'id' in new_module:
           db.set_user_app(data['id_user'], new_module['id'])
           module = db.get_module(new_module['id'])
           if module['id_ble']=='xxxx':
             id_ble = tools.set_id_ble(module)
             db.update_id_ble(module['id'], id_ble)
           return redirect(url_for('newArduino', _scheme='https', _external=True, app_id=new_module['id']))
     if request.args.get('module_id'):
       module = db.get_module(request.args.get('module_id'))
     return render_template('module_admin.html', user_login=flask_login.current_user.name, module=module, users=users, \
       shelf_infos=globalVars['arduino_map'])
   abort(404)
예제 #25
0
 def listNodesForTag(tag_id):
   globalVars = tools.initApp()
   if globalVars['arduino_map'] != None:
     nodes = db.get_node_for_tag(tag_id, globalVars['arduino_map']['user_id'])
     tag = db.get_tag_by_id(tag_id, globalVars['arduino_map']['user_id'])   
     data = {}
     books = []
     data['list_title'] = tag['tag']
     client = 'server'
     if('token' in request.args):
       client = 'mobile'
     if nodes:
         #for node in nodes:
         for i in range(len(nodes)):
             book = db.get_book(nodes[i]['id_node'], globalVars['arduino_map']['user_id'])
             books.append(book)
             app_modules = db.get_arduino_for_user(flask_login.current_user.id)
             for module in app_modules:
               address = db.get_position_for_book(module['id'], book['id'])
               if address:
                 hasRequest = db.get_request_for_position(module['id'], address['position'], address['row'])
                 books[i]['address'] = address
                 books[i]['arduino_name'] = module['arduino_name']
                 books[i]['uuid_encode'] = tools.uuid_encode(module['id_ble'])
                 books[i]['app_id'] = module['id']
                 books[i]['app_uuid'] = module['uuid']
                 books[i]['app_mac'] = module['mac']
                 books[i]['hasRequest'] = hasRequest
                 if tag['color'] is not None:
                   books[i]['color'] = tag['color']
         data['items'] = books
     #send json when token mode
     if('api' in request.path and 'token' in request.args):
       response = app.response_class(
         response=json.dumps(data),
         mimetype='application/json'
       )
       return response     
     return render_template('tag.html', books=books, user_login=globalVars['user_login'], \
       shelf_infos=globalVars['arduino_map'], tag=tag)
   abort(404)
예제 #26
0
 def ajaxSetPosition():
     globalVars = tools.initApp()
     if request.method == 'POST' and session.get('app_id'):
         book_id = request.form.get('book_id')
         #leds_range = request.form.get('range')
         #update book width
         book = db.get_book(book_id, globalVars['arduino_map']['user_id'])
         book_width = request.form.get('new_book_width')
         book['width'] = round(float(book_width))
         db.set_book(book, globalVars['arduino_map']['user_id'])
         leds_range = tools.led_range(
             book, globalVars['arduino_map']['leds_interval'])
         #update position
         column = request.form.get('column')
         row = request.form.get('row')
         app_id = session.get('app_id')
         db.set_position(app_id, book_id, column, row, leds_range, 'book',
                         0)  #reinit led column
         led_column = db.get_led_column(app_id, book_id, row, column)
         db.set_led_column(app_id, book_id, row, led_column)
         ret = {'led_column': int(led_column)}
         response = app.response_class(response=json.dumps(ret),
                                       mimetype='application/json')
         return response
예제 #27
0
    def ajaxDelPosition():
        globalVars = tools.initApp()
        if request.method == 'POST' and session.get('app_id'):
            for elem in request.form:
                book = elem.split('_')  #vars book_[id]
                item_id = book[1]
                item_type = book[0]
                #clean all position for books
                position = db.get_position_for_book(session.get('app_id'),
                                                    item_id)
                sortable = []
                if position:
                    db.del_item_position(session.get('app_id'), item_id,
                                         item_type, position['row'])
                    has_request = db.get_request_for_position(
                        session.get('app_id'), position['position'],
                        position['row'])
                    #remove request
                    if has_request:
                        db.del_request(session.get('app_id'),
                                       position['led_column'], position['row'])

                    #get list for remaining items and sort them again
                    items = db.get_positions_for_row(session.get('app_id'),
                                                     position['row'])
                    if items:
                        app_id = session.get('app_id')
                        i = 0
                        sortable = []
                        for item in items:
                            position = db.get_position_for_book(
                                app_id, item['id_item'])
                            if position:
                                interval = position['range']
                            else:
                                book = db.get_book(item['id_item'], user_id)
                                interval = tools.led_range(
                                    book,
                                    globalVars['arduino_map']['leds_interval'])
                            i += 1
                            db.set_position(app_id, item['id_item'], i,
                                            position['row'], interval, 'book',
                                            0)  #reinit led column

                        #update new leds number
                        positions = db.get_positions_for_row(
                            app_id, position['row'])
                        for pos in positions:
                            led_column = db.get_led_column(
                                app_id, pos['id_item'], pos['row'],
                                pos['position'])
                            db.set_led_column(app_id, pos['id_item'],
                                              pos['row'], led_column)
                            sortable.append({
                                'book':
                                pos['id_item'],
                                'position':
                                pos['position'],
                                'fulfillment':
                                int(led_column + pos['range']),
                                'shelf':
                                pos['row']
                            })

        response = app.response_class(response=json.dumps(sortable),
                                      mimetype='application/json')
        return response
예제 #28
0
    def locateBook():
        globalVars = tools.initApp()
        action = 'add'
        positions = []
        color = ''
        app_id = session['app_id']
        book_id = None
        address = None
        client = 'server'
        if ('api' in request.path and 'token' in request.args):
            client = 'mobile'
        '''get form request params'''
        if (request.method == 'POST'):
            app_id = request.form.get('app_id')
            column = request.form.get('column')
            row = request.form.get('row')
            book_id = request.form.get('book_id')
            leds_range = request.form.get('range')
            address = db.get_position_for_book(app_id, book_id)
            if address['borrowed'] == 1:
                color = '255,0,0'
            if 'remove_request' in request.form:
                action = 'remove'
        '''get params for location'''
        if (request.method == 'GET'):
            app_id = session['app_id']
            book_id = request.args.get('book_id')
            color = request.args.get('color')
            address = db.get_position_for_book(app_id, book_id)
            if 'remove_request' in request.args:
                action = 'remove'

        #manage request
        if address != None and book_id != None:
            db.set_request(app_id, book_id, address['row'], address['position'], address['range'], address['led_column'], \
            'book', client, action, None, color)
            if action == 'remove':
                retMsg = 'Location removed for book {}'.format(book_id)
            else:
                retMsg = 'Location requested for book {}'.format(book_id)
            flash(retMsg, 'info')
        else:
            retMsg = 'Unable to find book'
            flash(retMsg, 'danger')

        #send data for mobile
        if ('api' in request.path and 'token' in request.args):
            data = {'action':action, 'row':address['row'], 'start':address['led_column'], 'interval':address['range'], \
              'id_node':book_id, 'borrowed':address['borrowed']}
            if color != None:
                data.update({'color': color})
            positions.append(data)
            response = app.response_class(response=json.dumps(positions),
                                          mimetype='application/json')
            return response

        if (request.referrer and 'tag' in request.referrer):
            return redirect(
                url_for('listAuthors', _scheme='https', _external=True))
        return redirect(url_for('myBookShelf', _scheme='https',
                                _external=True))
예제 #29
0
    def getRequestForModule():
        globalVars = tools.initApp()
        if globalVars['arduino_map'] != None:

            #get request for distant mobile app
            #if('uuid' in request.args):
            source = 'server'
            if 'api' in request.path and 'token' in request.args:
                source = 'mobile'

            positions_add = []
            blocks = []
            if source == 'mobile':
                datas_add = db.get_request_for_mobile(session['app_id'], 'add',
                                                      0)
            else:
                datas_add = db.get_request(session['app_id'], 'add')
            if datas_add:
                for data in datas_add:

                    if data['color'] is None:
                        data['color'] = ''

                    positions_add.append({'action':data['action'], 'row':data['row'], 'led_column':data['led_column'], \
                    'interval':data['range'], 'id_tag':data['id_tag'], 'color':data['color'], 'id_node':data['id_node'], \
                    'client':data['client']})
                    #flag sent nodes for mobile
                    if source == 'mobile':
                        db.set_request_sent(session['app_id'], data['id_node'],
                                            1)

                positions_add.sort(key=tools.sortPositions)
                blocks = tools.build_block_position(positions_add, 'add')

            positions_remove = []
            datas_remove = db.get_request(session['app_id'], 'remove')
            resp = "event: ping\n"
            if datas_remove:
                #soft remove
                for data in datas_remove:
                    #send remove for mobile only when request come from server
                    if (source == 'mobile'
                            and data['client'] == 'server') or (source
                                                                == 'server'):
                        positions_remove.append({'action':data['action'], 'row':data['row'], 'led_column':data['led_column'], \
                      'interval':data['range'], 'id_tag':'', 'color':'', 'id_node':data['id_node'], 'client':data['client']})

                positions_remove.sort(key=tools.sortPositions)
                blocks += tools.build_block_position(positions_remove,
                                                     'remove')

                #hard remove
                for data in datas_remove:
                    diff = tools.seconds_between_now(data['date_add'])
                    #wait for other clients before remove
                    if diff > 3:
                        db.del_request(session['app_id'], data['led_column'],
                                       data['row'])

            #print(blocks)

            #set message for SSE
            resp = "event: ping\n"
            if len(blocks) > 0:
                json_dump = json.dumps(blocks)
                resp += "data: " + json_dump
                resp += "\nid: " + hashlib.md5(
                    json_dump.encode("utf-8")).hexdigest()
                resp += "\nretry: 2000"
            else:
                resp += "\ndata: {}"
                resp += "\nid: 0"
                resp += "\nretry: 5000"
            resp += "\n\n"
            return Response(resp, mimetype='text/event-stream')
예제 #30
0
  def customColors(app_id):
    globalVars = tools.initApp()
    user_id = globalVars['arduino_map']['user_id']
    module = db.get_arduino_map(flask_login.current_user.id, app_id)
    #print(module)
    if module:
      #session['app_id'] = module['id']
      #session['app_name'] = module['arduino_name']
      
      #parse coordinates from db
      customcoords = ''
      dbcoords = db.get_customcolors(user_id, app_id)
      if(dbcoords and dbcoords['coordinates']!=''):
        customcoords = json.loads(dbcoords['coordinates'])
      #print(customcoords)

      if request.method == 'POST':
        if request.is_json:
          mode = request.args.get('mode')
          data = request.get_json()
          #print(data)

          #group data by colors and positions
          colorpos = {}
          for numrow, positions in data.items():
            for i, position in enumerate(positions):
              start = 0
              if(i>0):
                start = int(positions[i-1]['handle'])+1
              tmp = [[start,int(position['handle'])],int(numrow)+1]
              if position['color'] not in colorpos:
                colorpos.update({position['color']: [tmp]})
              else:
                colorpos[position['color']].append(tmp)

          #set coordinates : group by colors and "x" positions for computing "y" coords 
          coords = {}
          for color, positions in colorpos.items():
            #sort list by x position
            positions.sort(key=tools.sortCoords)
            #compute y coords size
            for i, position in enumerate(positions):
              #set variables
              row = int(position[1])
              x_start = int(position[0][0])
              x_end = int(position[0][1])
              x_offset = int(x_end-x_start)
              #set key for grouping dict : color, x pos, x end, first row
              group_key = str(x_start)+'-'+str(x_end)
              
              #check for grouping colors wich have the same position on different rows
              if(i>0):
                if (position[0]==last_pos and row==int(last_row+1)): #matching with previous color position
                  y_start = (row-y_offset)-1
                  y_offset += 1         
                  #print('match', position[1], row, last_row)
                else: #not matching
                  y_start = row-1
                  y_offset = 1
                  #print('nomatch', position[1], row, last_row)
              else: #not matching
                y_start = row-1
                y_offset = 1
                #print('nomatch', position[1], row)              

              #store value for next iteration
              last_pos = position[0] 
              last_row = position[1]

              group_key += '_'+str(y_start)+'_'+color #update key

              #coord = color+'_'+str(x_start)+'-'+str(x_end)+'_'+str(y_start)+'-'+str(y_offset)
              rgb = color.split('(')[1].split(')') #extract rgb
              coord = {'color':rgb[0], 'x_start':x_start, 'x_offset':x_offset, 'y_start':y_start, 'y_offset':y_offset}
              coords[group_key] = coord

          #save datas
          coordinates = json.dumps(coords)
          print(coordinates)        
          db.set_customcolors(user_id, app_id, "test", coordinates)

      return render_template('customcolors.html', user_login=flask_login.current_user.name, customcoords=customcoords, \
       module=module, shelf_infos=globalVars['arduino_map'])
    abort(404)