def __init__(self): if self.token == None: tm = TokenManager("Portal", "https://nps.maps.arcgis.com", "IMDGISTeam", "G3010g!c2016", "https://irma.nps.gov") tm.getToken() self.token = tm.token if self.admin == None: self.admin = tm.admin
def __init__ (self): super(TasksLens, self).__init__() # Object to manage RTM lists self._listsInfoManager = ListsInfoManager() # Object to manage RTM tasks self._tasksInfoManager = TasksInfoManager(self._listsInfoManager) # Object to handle the token (save to file, read from file) self._tokenManager = TokenManager() # RTM auth manager object self._authManager = AuthManager(ICON + 'cpN' + ICON_EXTENSION, self.tasks) # RTM auth token self._token = self._tokenManager.readTokenFromFile() # RTM object self._rtm = Rtm(RAK, RSS, "write", self._token) # Database self._db = TasksDB() # The user's current system timezone offset tzoffset = timezone if not localtime().tm_isdst else altzone self._tzoffset = timedelta(seconds = tzoffset * -1)
def __init__(self, report_id: str, start_date: str): # Todo rework token stuff self.token = TokenManager( '/Users/brian.kalinowski/IdeaProjects/RingCentralData/creds.yml') self.report_id = report_id self.start_date = pd.to_datetime(start_date) self.end_date = (self.start_date + pd.DateOffset(days=1)) self.data = None
def __init__(self): super(TasksLens, self).__init__() # Object to manage RTM lists self._listsInfoManager = ListsInfoManager() # Object to manage RTM tasks self._tasksInfoManager = TasksInfoManager(self._listsInfoManager) # Object to handle the token (save to file, read from file) self._tokenManager = TokenManager() # RTM auth manager object self._authManager = AuthManager(ICON + ICON_EXTENSION, self.tasks) # RTM auth token self._token = self._tokenManager.readTokenFromFile() # RTM object self._rtm = Rtm(RAK, RSS, "read", self._token)
def getTheCategoriesListStatically(apiKey, sharedSecret): ''' This method uses the RTM service by instantiating a new RTM object and tries to retrieve the list of listnames from the service. It can be run independently, as it uses an extra instance of the RTM object ''' listsNames = [] tokenManager = TokenManager() token = tokenManager.readTokenFromFile() if (token is None): # If the token doesn't exist, it won't work return listsNames rtm = Rtm(apiKey, sharedSecret, "read", token) if not rtm.token_valid(): # The token wasn't vaid return listsNames # Get the lists description, see http://www.rememberthemilk.com/services/api/methods/rtm.lists.getList.rtm listsList = rtm.rtm.lists.getList() # Get the name of each list for element in listsList.lists: listsNames.append(element.name) return listsNames
def getTheCategoriesListStatically(apiKey, sharedSecret): ''' This method uses the RTM service by instantiating a new RTM object and tries to retrieve the list of listnames from the service. It can be run independently, as it uses an extra instance of the RTM object ''' listsNames = [] tokenManager = TokenManager() token = tokenManager.readTokenFromFile() if (token is None): # If the token doesn't exist, it won't work return listsNames rtm = Rtm(apiKey, sharedSecret, "read", token) if not rtm.token_valid(): # The token wasn't vaid return listsNames # Get the lists description, see http://www.rememberthemilk.com/services/api/methods/rtm.lists.getList.rtm listsList = rtm.rtm.lists.getList() # Get the name of each list for element in listsList.lists: listsNames.append(element.name) return listsNames
def __init__(self, start_date: str, end_date: str): # TODO change this for service account self.token = TokenManager('/Users/brian.kalinowski/IdeaProjects/RingCentralData/creds.yml') # gets 30 day intervals of dates from start till end self.date_batches = self.get_date_range(start_date, end_date) # holds the df for each batch in the date range self.report_df_batches = [] # Default API headers self.request_headers = {'Authorization': 'Bearer {}'.format(self.token()), 'Content-Type': 'x-www-form-urlencoded', 'Accept': 'application/json' }
def __init__ (self): super(TasksLens, self).__init__() # Object to manage RTM lists self._listsInfoManager = ListsInfoManager() # Object to manage RTM tasks self._tasksInfoManager = TasksInfoManager(self._listsInfoManager) # Object to handle the token (save to file, read from file) self._tokenManager = TokenManager() # RTM auth manager object self._authManager = AuthManager(ICON + ICON_EXTENSION, self.tasks) # RTM auth token self._token = self._tokenManager.readTokenFromFile() # RTM object self._rtm = Rtm(RAK, RSS, "read", self._token)
import requests import json from TokenManager import TokenManager tm = TokenManager() BASE_URL = 'https://graph.facebook.com/v2.6/me/messages' def get_profile(psid): headers = { 'Content-Type':'application/json' } params = ( ('access_token=%s' % tm.get('MESSENGER_ACCESS_TOKEN')) + '&fields=first_name,last_name,profile_pic,locale,timezone,gender' ) PROFILE_URL = 'https://graph.facebook.com/v2.6/%s' % str(psid) response = requests.get(PROFILE_URL, headers=headers, params=params) return response.json() def send_message(msg): headers = { 'Content-Type':'application/json' } params = { 'access_token': tm.get('MESSENGER_ACCESS_TOKEN') } response = requests.post(BASE_URL, headers=headers, data=str(msg), params=params)
from django.shortcuts import render from django.http import HttpResponse, JsonResponse from django.views.decorators.csrf import csrf_exempt import os, sys from slack.modules import * from TokenManager import TokenManager tm = TokenManager() SLACK_TOKEN = tm.get('SLACK_TOKEN') def index(request): return HttpResponse('Front page of ECEUSC Slack Bot should go here!') @csrf_exempt def command(request): if request.method == 'GET': return HttpResponse('Lol lets do this') elif request.method == 'POST': req_token = request.POST.get('token') if req_token != SLACK_TOKEN: return HttpResponse('WRONG TOKEN', status=401) user_id = request.POST.get('user_id') channel_id = request.POST.get('channel_id') channel_name = request.POST.get('channel_name') text = request.POST.get('text') words = text.split(' ')
class TasksLens(SingleScopeLens): class Meta: name = 'tasks' title = 'Search Tasks' description = 'Tasks Search' search_hint = 'Search Tasks' icon = 'tasks.svg' category_order = ['tasks'] filter_order = ['categoryFilter', 'displayedFieldsFilter', 'orderFilter'] tasks = ListViewCategory("Tasks", 'stock_yes') # id, display name, icon, contracted state categoryFilter = Unity.RadioOptionFilter.new("categoryFilter", "Sections", None, False) # Get the lists names if possible catNames = ListsInfoManager.getTheCategoriesListStatically(RAK, RSS) # Maps a filter id to the corresponding string to which fitering must be # applied. This is necessary to support different languages # e.g.: '0': 'Inbox', # '1': 'Work', # '2': 'Personal', # '3': 'Study', # '4': 'Sent' categoryIdToNameMappingTable = {} # Populate the category map for i in range(0, len(catNames)): categoryIdToNameMappingTable[str(i)] = catNames[i] # Populate the category filters if len(categoryIdToNameMappingTable) == 0: categoryFilter.add_option('0', "Lens restart needed", None) else: for i in range(0, len(categoryIdToNameMappingTable)): categoryFilter.add_option(categoryIdToNameMappingTable.keys()[i], categoryIdToNameMappingTable.values()[i], None) # Populate the ID filters displayedFieldsFilter = Unity.CheckOptionFilter.new("fieldsFilter", "Fields to display", None, False) displayedFieldsFilter.add_option(CATEGORY_FIELD_FILTER_ID, "Category", None) displayedFieldsFilter.add_option(DUE_FIELD_FILTER_ID, "Due", None) displayedFieldsFilter.add_option(PRIORITY_FIELD_FILTER_ID, "Priority", None) # Populate the ordering filter orderFilter = Unity.RadioOptionFilter.new("orderingFilter", "Sort by", None, False) orderFilter.add_option(TasksInfoManager.ORDERING_PRIORITY_ID, "Priority", None) orderFilter.add_option(TasksInfoManager.ORDERING_DUE_ID, "Due dates", None) orderFilter.add_option(TasksInfoManager.ORDERING_NAMES_ID, "Names", None) # Category visualization must be active by default displayedFieldsFilter.get_option(CATEGORY_FIELD_FILTER_ID).props.active = True displayedFieldsFilter.get_option(DUE_FIELD_FILTER_ID).props.active = True displayedFieldsFilter.get_option(PRIORITY_FIELD_FILTER_ID).props.active = True # Priority order as default orderFilter.get_option(TasksInfoManager.ORDERING_PRIORITY_ID).props.active = True # Minimum characters to filter results using the search bar MIN_SEARCH_LENGTH = 3 def __init__ (self): super(TasksLens, self).__init__() # Object to manage RTM lists self._listsInfoManager = ListsInfoManager() # Object to manage RTM tasks self._tasksInfoManager = TasksInfoManager(self._listsInfoManager) # Object to handle the token (save to file, read from file) self._tokenManager = TokenManager() # RTM auth manager object self._authManager = AuthManager(ICON + ICON_EXTENSION, self.tasks) # RTM auth token self._token = self._tokenManager.readTokenFromFile() # RTM object self._rtm = Rtm(RAK, RSS, "read", self._token) # # Update results model (currently disabled) # def global_search(self, search, model): #self._handleSearch(search, model) return # # Update results model # def search(self, search, model): self._handleSearch(search, model) return def _handleSearch(self, search, model): """ Handles search operations on the lens """ # Authenticate if necessary if self._authManager.checkAndRequireAuthentication(self._rtm, model) == True: return # Download the tasks list self._tasksInfoManager.downloadTasksList(self._rtm) # Get categories filter active option try: filteredCategoryId = self._scope.get_filter('categoryFilter').get_active_option().props.id filteredCategory = self.categoryIdToNameMappingTable[filteredCategoryId] except (AttributeError): filteredCategory = 'All' except (KeyError): filteredCategory = 'All' # Get fields filter active options optionalDisplayFields = [] for option in self._scope.get_filter('fieldsFilter').options: if option.props.active == True: optionalDisplayFields.append(option.props.id) # Get the tasks for the specified category (all categories are returned # filteredCategory doesn't name an existing category) tasks = self._tasksInfoManager.getTasksOfCategory(filteredCategory) # Get the ordering filter status try: filteringId = self._scope.get_filter('orderingFilter').get_active_option().props.id except (AttributeError): filteringId = 'Unspecified' self._tasksInfoManager.orderTasksList(tasks, filteringId) for taskDescriptor in tasks: categoryName = taskDescriptor.category if CATEGORY_FIELD_FILTER_ID in optionalDisplayFields else "" dueTime = taskDescriptor.prettyDue if DUE_FIELD_FILTER_ID in optionalDisplayFields else "" priority = taskDescriptor.priority if PRIORITY_FIELD_FILTER_ID in optionalDisplayFields else "" name = taskDescriptor.name self._updateModel(categoryName, name, dueTime, priority, search, model) def _updateModel(self, categoryName, taskName, due, priority, search, model): if len(due) > 0: due = ' ' + '[' + due + ']' icon = ICON + priority + ICON_EXTENSION if len(search) < self.MIN_SEARCH_LENGTH or search in taskName: model.append('rtmLens://select/%s' % taskName, icon, self.tasks, 'text/plain', categoryName + due, taskName, '') def handle_uri(self, scope, uri): action = uri.split('/')[-2] word = uri.split('/')[-1] print "on_activate_uri: %s %s" % (action, word) if action == 'auth': self._token = self._authManager.rtmCompleteAuthentication(self._rtm, self._tokenManager) # Clear results (icon asking for auth) results = self._scope.props.results_model results.clear() # Update the lens by simulating an empty search self.search ("", results) return self.update_dash_response() elif action == 'select': webbrowser.open(RTM_PAGE)
import telegram # importamos las librerias import logging from telegram.ext import Updater, CommandHandler, MessageHandler, Filters from TokenManager import TokenManager TOKEN = TokenManager.getToken('text_files/secured_token.txt') bot = telegram.Bot(token=TOKEN) updater = Updater(token=TOKEN) dispatcher = updater.dispatcher # To know when things dont work as expected LOG_FILE = 'text_files/lost_err.txt'; logging.basicConfig(filename=LOG_FILE, level=logging.DEBUG, format='%(asctime)s %(levelname)s %(name)s %(message)s') logger = logging.getLogger(__name__) # Functions that contains the actions of the commands when they are pressed def start(bot, update): bot.send_message(chat_id=update.message.chat_id, text='<b>Lost Wiki</b>.\r\nHere you can find information about the show.', parse_mode=telegram.ParseMode.HTML) bot.send_photo(chat_id=update.message.chat_id, photo=open('img/lost1.png', 'rb')) def character(bot, update): bot.send_message(chat_id=update.message.chat_id, text='<a href="http://es.lostpedia.wikia.com/wiki/Portal:Personajes_Principales">Main Characters</a>', parse_mode=telegram.ParseMode.HTML) def description(bot, update): bot.send_message(chat_id=update.message.chat_id,
https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! # https://docs.djangoproject.com/en/2.0/ref/settings/#secret-key from TokenManager import TokenManager tm = TokenManager() SECRET_KEY = tm.get('DJANGO_TOKEN') or 'CHANGE_ME_TO_LARGE_RANDOM_VALUE' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [ 'peaceful-river-18332.herokuapp.com', 'eceusc.herokuapp.com', 'ngrok.io', '*', ] import socket HOSTNAME = None
class TasksLens(SingleScopeLens): class Meta: name = 'tasks' title = _(u'Search Tasks').decode('utf-8') description = _(u'Tasks Search').decode('utf-8') search_hint = _(u'Search Tasks').decode('utf-8') icon = 'tasks.svg' category_order = ['tasks'] filter_order = ['categoryFilter', 'displayedFieldsFilter', 'orderFilter', 'completedFilter'] tasks = ListViewCategory(_(u"Tasks").decode('utf-8'), 'stock_yes') # id, display name, icon, contracted state categoryFilter = Unity.RadioOptionFilter.new("categoryFilter", _(u"Sections").decode('utf-8'), None, False) # Get the lists names if possible catNames = ListsInfoManager.getTheCategoriesListStatically(RAK, RSS) # Maps a filter id to the corresponding string to which fitering must be # applied. This is necessary to support different languages # e.g.: '0': 'Inbox', # '1': 'Work', # '2': 'Personal', # '3': 'Study', # '4': 'Sent' categoryIdToNameMappingTable = {} PRIORITIES = {'0': _(u'Oops, error!').decode('utf-8'), '1': _(u'High Priority').decode('utf-8'), '2': _(u'Medium Priority').decode('utf-8'), '3': _(u'Low Priority').decode('utf-8'), 'N': _(u'Unspecified').decode('utf-8')} # Populate the category map for i in range(0, len(catNames)): categoryIdToNameMappingTable[str(i)] = catNames[i] # Populate the category filters if len(categoryIdToNameMappingTable) == 0: categoryFilter.add_option('0', _(u"Lens restart needed").decode('utf-8'), None) else: for i in range(0, len(categoryIdToNameMappingTable)): categoryFilter.add_option(categoryIdToNameMappingTable.keys()[i], categoryIdToNameMappingTable.values()[i], None) # Populate the ID filters displayedFieldsFilter = Unity.CheckOptionFilter.new("fieldsFilter", _(u"Fields to display").decode('utf-8'), None, False) displayedFieldsFilter.add_option(CATEGORY_FIELD_FILTER_ID, _(u"Category").decode('utf-8'), None) displayedFieldsFilter.add_option(DUE_FIELD_FILTER_ID, _(u"Due").decode('utf-8'), None) displayedFieldsFilter.add_option(PRIORITY_FIELD_FILTER_ID, _(u"Priority").decode('utf-8'), None) # Populate the ordering filter orderFilter = Unity.RadioOptionFilter.new("orderingFilter", _(u"Sort by").decode('utf-8'), None, False) orderFilter.add_option(TasksInfoManager.ORDERING_PRIORITY_ID, _(u"Priority").decode('utf-8'), None) orderFilter.add_option(TasksInfoManager.ORDERING_DUE_ID, _(u"Due dates").decode('utf-8'), None) orderFilter.add_option(TasksInfoManager.ORDERING_NAMES_ID, _(u"Names").decode('utf-8'), None) # Filter for complete/uncomplete tasks completedFilter = Unity.RadioOptionFilter.new("completedFilter", _(u"Show/Hide").decode('utf-8'), None, False) completedFilter.add_option(SHOW_COMPLETED_FILTER_ID, _(u"Show completed tasks").decode('utf-8'), None) # Category visualization must be active by default displayedFieldsFilter.get_option(CATEGORY_FIELD_FILTER_ID).props.active = True displayedFieldsFilter.get_option(DUE_FIELD_FILTER_ID).props.active = True displayedFieldsFilter.get_option(PRIORITY_FIELD_FILTER_ID).props.active = True # Priority order as default orderFilter.get_option(TasksInfoManager.ORDERING_PRIORITY_ID).props.active = True # Do not show complete tasks as default completedFilter.get_option(SHOW_COMPLETED_FILTER_ID).props.active = False # Minimum characters to filter results using the search bar MIN_SEARCH_LENGTH = 3 def __init__ (self): super(TasksLens, self).__init__() # Object to manage RTM lists self._listsInfoManager = ListsInfoManager() # Object to manage RTM tasks self._tasksInfoManager = TasksInfoManager(self._listsInfoManager) # Object to handle the token (save to file, read from file) self._tokenManager = TokenManager() # RTM auth manager object self._authManager = AuthManager(ICON + 'cpN' + ICON_EXTENSION, self.tasks) # RTM auth token self._token = self._tokenManager.readTokenFromFile() # RTM object self._rtm = Rtm(RAK, RSS, "write", self._token) # Database self._db = TasksDB() # The user's current system timezone offset tzoffset = timezone if not localtime().tm_isdst else altzone self._tzoffset = timedelta(seconds = tzoffset * -1) # # Update results model (currently disabled) # def global_search(self, search, model): #self._handleSearch(search, model) return # # Update results model # def search(self, search, model): self._handleSearch(search, model) return def _handleSearch(self, search, model): """ Handles search operations on the lens """ # Authenticate if necessary if self._authManager.checkAndRequireAuthentication(self._rtm, model) == True: return # Download the tasks list self._tasksInfoManager.downloadTasksList(self._rtm, self._db) # Get the category to be displayed (if None, display them all) try: filteredCategoryId = self._scope.get_filter('categoryFilter').get_active_option().props.id filteredCategory = self.categoryIdToNameMappingTable[filteredCategoryId] except (AttributeError): filteredCategory = None except (KeyError): filteredCategory = None # Get the status of the show completed filter try: showCompleted = self._scope.get_filter('completedFilter').get_active_option().props.id showCompleted = True except (AttributeError): showCompleted = False # Get the lists of fields to be displayed for each task element optionalDisplayFields = [] for option in self._scope.get_filter('fieldsFilter').options: if option.props.active == True: optionalDisplayFields.append(option.props.id) # Get the ordering, if any try: orderBy = self._scope.get_filter('orderingFilter').get_active_option().props.id except (AttributeError): orderBy = None # Filters at this point: # filteredCategoryId: id of the category (list id) to be displayed # orderBy: priority, due date or name # optionalDisplayFields: contains elements of this set: ("category", "due", "priority") # get the tasks of the specified category (if not None), ordered on orderBy # and also completed tasks if required tasks = self._db.getTasks(filteredCategory, orderBy, showCompleted) for taskDictionary in tasks: categoryName = taskDictionary[TasksDB.TCATEGORY] if CATEGORY_FIELD_FILTER_ID in optionalDisplayFields else "" dueTime = self._prettyFormatDueDate(taskDictionary[TasksDB.TDUE]) if DUE_FIELD_FILTER_ID in optionalDisplayFields else "" priority = taskDictionary[TasksDB.TPRIORITY] if PRIORITY_FIELD_FILTER_ID in optionalDisplayFields else "N" name = taskDictionary[TasksDB.TNAME] listId = taskDictionary[TasksDB.TLIST_ID] taskseriesId = taskDictionary[TasksDB.TSERIES_ID] taskId = taskDictionary[TasksDB.TID] completed = taskDictionary[TasksDB.TCOMPLETED] self._updateModel(categoryName, name, dueTime, priority, search, model, listId, taskseriesId, taskId, completed) def _updateModel(self, categoryName, taskName, due, priority, search, model, listId, taskseriesId, taskId, completed): if len(due) > 0: due = ' ' + '[' + due + ']' icon = self._getIconForTask(priority, completed) if len(search) < self.MIN_SEARCH_LENGTH or search.lower() in taskName.lower(): model.append('rtmLens://select/lid={}&tsid={}&tid={}'.format(listId, taskseriesId, taskId), icon, self.tasks, 'text/plain', categoryName + due, taskName, '') def _getIconForTask(self, priority, completed): ''' Returns the file name of the icon to be used for the task with a given priority and complete status ''' if completed == u'': # not completed completed = 'u' else: # completed completed = 'c' icon = ICON + completed + 'p' + priority + ICON_EXTENSION return icon def handle_uri(self, scope, uri): action = uri.split('/')[-2] word = uri.split('/')[-1] print "on_activate_uri: %s %s" % (action, word) if action == 'auth': self._token = self._authManager.rtmCompleteAuthentication(self._rtm, self._tokenManager) # Clear results (icon asking for auth) results = self._scope.props.results_model results.clear() # Update the lens by simulating an empty search self.search ("", results) return self.update_dash_response() elif action == 'select': webbrowser.open(RTM_PAGE) def _getTaskIdsFromUri(self, uri): ''' Parses the URI of a model, which contains the three identifiers of a tasks and returns them in a dictionary. The input string is like: rtmLens://select/lid=20897253&tsid=172048629&tid=273082817 The output is a dictionary with the following format: {'lid': '20897253', 'tid': '273082817', 'tsid': '172048629'} where the keys are directly extracted from each id=value pair contained in the uri. ''' d = {} # Generate a list of key=value pairs (one for each id) for ids in (key_value.split('=') for key_value in uri.split('/')[-1].split('&')): d[ids[0]] = ids[1] return d def on_preview_uri(self, scope, uri): ''' Callback method called when the preview for an element is requested (i.e., someone right-clicked a task) ''' # Download the tasks list self._tasksInfoManager.downloadTasksList(self._rtm, self._db) identifiers = self._getTaskIdsFromUri(uri) model = scope.props.results_model current_task = model.get_first_iter() last_task = model.get_last_iter() # Get, from all the elements, the one that was clicked while current_task != last_task: if model.get_value(current_task, 0) == uri: break else: current_task = model.next(current_task) if current_task == last_task: # not found!! something very wrong happened raise ValueError('Unable to load task preview') taskInfo = self._db.getTaskById(identifiers['tid'], identifiers['lid'], identifiers['tsid']) # Title, description (not visible ?!), icon (set later) preview = Unity.GenericPreview.new(taskInfo[TasksDB.TCATEGORY], taskInfo[TasksDB.TNAME], None) icon = self._getIconForTask(taskInfo[TasksDB.TPRIORITY], taskInfo[TasksDB.TCOMPLETED]) preview.props.image_source_uri = icon icon = Gio.ThemedIcon.new(icon) preview.props.image = icon # Text preview.props.description_markup = self._getPreviewText(taskInfo[TasksDB.TCATEGORY], taskInfo[TasksDB.TDUE], taskInfo[TasksDB.TPRIORITY], taskInfo[TasksDB.TNAME], taskInfo[TasksDB.TCOMPLETED]) # add complete/uncomplete button if taskInfo[TasksDB.TCOMPLETED] is u'': # task has not been completed # description, string, icon view_action = Unity.PreviewAction.new('complete', _(u'Mark completed').decode('utf-8'), None) view_action.connect('activated', self.complete_task) else: view_action = Unity.PreviewAction.new('uncomplete', _(u'Mark uncompleted').decode('utf-8'), None) view_action.connect('activated', self.uncomplete_task) preview.add_action(view_action) return preview def _getPreviewText(self, category, due, priority, name, completed): ''' Given task information returns the (formatted) text to be put in the preview screen for this task ''' due = self._prettyFormatDueDate(due) s = u"<b>" + _(u"Category").decode('utf-8') + u"</b>: " + category + u"\n" s += u"<b>" + _(u"Priority").decode('utf-8') + u"</b>: " + self.PRIORITIES[priority] + u"\n" s += u"<b>" + _(u"Due date") + u"</b>: " + due + u"\n" if completed is not u'': s += u"<b>" + _(u"Completed on").decode('utf-8') + u"</b>: " + self._prettyFormatDueDate(completed) + u"\n" s += u"\n" s += u"<b>" + _(u"Description").decode('utf-8') + u"</b>\n" s += u"<i>{}</i>".format(name) return s def complete_task(self, scope, uri): print "Completing task...: ", uri ids = self._getTaskIdsFromUri(uri) self._tasksInfoManager.markCompleted(self._rtm, ids['lid'], ids['tsid'], ids['tid']) self._tasksInfoManager.refreshTasks() # http://developer.ubuntu.com/api/ubuntu-12.04/python/Unity-5.0.html#Unity.HandledType return Unity.ActivationResponse(handled = Unity.HandledType.SHOW_PREVIEW)#, goto_uri=uri) def uncomplete_task(self, scope, uri): print "Uncompleting task...: ", uri ids = self._getTaskIdsFromUri(uri) self._tasksInfoManager.markUncompleted(self._rtm, ids['lid'], ids['tsid'], ids['tid']) self._tasksInfoManager.refreshTasks() # http://developer.ubuntu.com/api/ubuntu-12.04/python/Unity-5.0.html#Unity.HandledType return Unity.ActivationResponse(handled = Unity.HandledType.SHOW_PREVIEW) def _prettyFormatDueDate(self, dueDateString): ''' Parses the due date as provided by the service and produces a pretty representation ''' if dueDateString == '': return '' # Input format example: 2012-03-29T22:00:00Z # Collect the tokens start = 0; firstHyphen = dueDateString.find('-') secondHyphen = dueDateString.rfind('-') bigT = dueDateString.find('T') firstColon = dueDateString.find(':') secondColon = dueDateString.rfind(':') bigZ = dueDateString.find('Z') # Extract the strings year = dueDateString[start : firstHyphen] month = dueDateString[firstHyphen + 1 : secondHyphen] day = dueDateString[secondHyphen + 1 : bigT] hour = dueDateString[bigT + 1 : firstColon] minutes = dueDateString[firstColon + 1 : secondColon] seconds = dueDateString[secondColon + 1 : bigZ] # Build the formatted string dt = datetime (int(year), int(month), int(day), int(hour), int(minutes), int(seconds)) dt = dt + self._tzoffset # E.g. 'Wed 07 Nov 2012 11:09AM' return dt.strftime("%a %d %b %Y %I:%M%p")
class TasksLens(SingleScopeLens): class Meta: name = 'tasks' title = 'Search Tasks' description = 'Tasks Search' search_hint = 'Search Tasks' icon = 'tasks.svg' category_order = ['tasks'] filter_order = [ 'categoryFilter', 'displayedFieldsFilter', 'orderFilter' ] tasks = ListViewCategory("Tasks", 'stock_yes') # id, display name, icon, contracted state categoryFilter = Unity.RadioOptionFilter.new("categoryFilter", "Sections", None, False) # Get the lists names if possible catNames = ListsInfoManager.getTheCategoriesListStatically(RAK, RSS) # Maps a filter id to the corresponding string to which fitering must be # applied. This is necessary to support different languages # e.g.: '0': 'Inbox', # '1': 'Work', # '2': 'Personal', # '3': 'Study', # '4': 'Sent' categoryIdToNameMappingTable = {} # Populate the category map for i in range(0, len(catNames)): categoryIdToNameMappingTable[str(i)] = catNames[i] # Populate the category filters if len(categoryIdToNameMappingTable) == 0: categoryFilter.add_option('0', "Lens restart needed", None) else: for i in range(0, len(categoryIdToNameMappingTable)): categoryFilter.add_option(categoryIdToNameMappingTable.keys()[i], categoryIdToNameMappingTable.values()[i], None) # Populate the ID filters displayedFieldsFilter = Unity.CheckOptionFilter.new( "fieldsFilter", "Fields to display", None, False) displayedFieldsFilter.add_option(CATEGORY_FIELD_FILTER_ID, "Category", None) displayedFieldsFilter.add_option(DUE_FIELD_FILTER_ID, "Due", None) displayedFieldsFilter.add_option(PRIORITY_FIELD_FILTER_ID, "Priority", None) # Populate the ordering filter orderFilter = Unity.RadioOptionFilter.new("orderingFilter", "Sort by", None, False) orderFilter.add_option(TasksInfoManager.ORDERING_PRIORITY_ID, "Priority", None) orderFilter.add_option(TasksInfoManager.ORDERING_DUE_ID, "Due dates", None) orderFilter.add_option(TasksInfoManager.ORDERING_NAMES_ID, "Names", None) # Category visualization must be active by default displayedFieldsFilter.get_option( CATEGORY_FIELD_FILTER_ID).props.active = True displayedFieldsFilter.get_option(DUE_FIELD_FILTER_ID).props.active = True displayedFieldsFilter.get_option( PRIORITY_FIELD_FILTER_ID).props.active = True # Priority order as default orderFilter.get_option( TasksInfoManager.ORDERING_PRIORITY_ID).props.active = True # Minimum characters to filter results using the search bar MIN_SEARCH_LENGTH = 3 def __init__(self): super(TasksLens, self).__init__() # Object to manage RTM lists self._listsInfoManager = ListsInfoManager() # Object to manage RTM tasks self._tasksInfoManager = TasksInfoManager(self._listsInfoManager) # Object to handle the token (save to file, read from file) self._tokenManager = TokenManager() # RTM auth manager object self._authManager = AuthManager(ICON + ICON_EXTENSION, self.tasks) # RTM auth token self._token = self._tokenManager.readTokenFromFile() # RTM object self._rtm = Rtm(RAK, RSS, "read", self._token) # # Update results model (currently disabled) # def global_search(self, search, model): #self._handleSearch(search, model) return # # Update results model # def search(self, search, model): self._handleSearch(search, model) return def _handleSearch(self, search, model): """ Handles search operations on the lens """ # Authenticate if necessary if self._authManager.checkAndRequireAuthentication(self._rtm, model) == True: return # Download the tasks list self._tasksInfoManager.downloadTasksList(self._rtm) # Get categories filter active option try: filteredCategoryId = self._scope.get_filter( 'categoryFilter').get_active_option().props.id filteredCategory = self.categoryIdToNameMappingTable[ filteredCategoryId] except (AttributeError): filteredCategory = 'All' except (KeyError): filteredCategory = 'All' # Get fields filter active options optionalDisplayFields = [] for option in self._scope.get_filter('fieldsFilter').options: if option.props.active == True: optionalDisplayFields.append(option.props.id) # Get the tasks for the specified category (all categories are returned # filteredCategory doesn't name an existing category) tasks = self._tasksInfoManager.getTasksOfCategory(filteredCategory) # Get the ordering filter status try: filteringId = self._scope.get_filter( 'orderingFilter').get_active_option().props.id except (AttributeError): filteringId = 'Unspecified' self._tasksInfoManager.orderTasksList(tasks, filteringId) for taskDescriptor in tasks: categoryName = taskDescriptor.category if CATEGORY_FIELD_FILTER_ID in optionalDisplayFields else "" dueTime = taskDescriptor.prettyDue if DUE_FIELD_FILTER_ID in optionalDisplayFields else "" priority = taskDescriptor.priority if PRIORITY_FIELD_FILTER_ID in optionalDisplayFields else "" name = taskDescriptor.name self._updateModel(categoryName, name, dueTime, priority, search, model) def _updateModel(self, categoryName, taskName, due, priority, search, model): if len(due) > 0: due = ' ' + '[' + due + ']' icon = ICON + priority + ICON_EXTENSION if len(search) < self.MIN_SEARCH_LENGTH or search in taskName: model.append('rtmLens://select/%s' % taskName, icon, self.tasks, 'text/plain', categoryName + due, taskName, '') def handle_uri(self, scope, uri): action = uri.split('/')[-2] word = uri.split('/')[-1] print "on_activate_uri: %s %s" % (action, word) if action == 'auth': self._token = self._authManager.rtmCompleteAuthentication( self._rtm, self._tokenManager) # Clear results (icon asking for auth) results = self._scope.props.results_model results.clear() # Update the lens by simulating an empty search self.search("", results) return self.update_dash_response() elif action == 'select': webbrowser.open(RTM_PAGE)
from TokenManager import TokenManager import requests token = TokenManager( '/Users/brian.kalinowski/IdeaProjects/RingCentralData/creds.yml') for idx in range(5): print('Token: ', idx) print(token()[0:20], '...') token.refresh_token()
For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! # https://docs.djangoproject.com/en/2.0/ref/settings/#secret-key from TokenManager import TokenManager tm = TokenManager() SECRET_KEY = tm.get('DJANGO_TOKEN') or 'CHANGE_ME_TO_LARGE_RANDOM_VALUE' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [ 'peaceful-river-18332.herokuapp.com', 'eceusc.herokuapp.com', 'ngrok.io', '*', ] # Application definition INSTALLED_APPS = [
from django.views.decorators.csrf import csrf_exempt from django.shortcuts import render from django.http import HttpResponse import os from messengerbot import receive from TokenManager import TokenManager tm = TokenManager() VERIFY_TOKEN = tm.get('MESSENGER_VERIFY_TOKEN') def index(request): return HttpResponse('Front page of ECEUSC Messenger Bot should go here! Heroku 2....') @csrf_exempt def webhook(request): if request.method == 'GET': verify_token = request.GET.get('hub.verify_token') if verify_token == VERIFY_TOKEN: hub_challenge = request.GET.get('hub.challenge') print(hub_challenge) return HttpResponse(hub_challenge) else: return HttpResponse('ERROR') elif request.method == 'POST': obj = request.POST.get('object') if obj == 'page': for entry in request.POST.get('entry'): for msg_event in entry.get('messaging'):
def agsConnection(self, serverURL, agsUser, agsPassword, referer='https://irma.nps.gov'): # Requires an admin connection tm = TokenManager("AGS", serverURL, agsUser, agsPassword, referer) tm.getToken() self.token = tm.token self.agsServer = tm.admin
return data.shape async def get_report_async(loop, header, reports): with ThreadPoolExecutor(max_workers=None) as executor: with requests.Session() as session: tasks = [ loop.run_in_executor(executor, get_report_data, *(session, header, rid)) for rid in reports ] return await asyncio.gather(*tasks) if __name__ == '__main__': access_token = TokenManager( '/Users/brian.kalinowski/IdeaProjects/RingCentralData/creds.yml') request_header = { 'Authorization': 'Bearer {}'.format(access_token()), 'Content-Type': 'x-www-form-urlencoded', 'Accept': 'application/json' } report_ids = ['521', '524', '549', '500'] event_loop = asyncio.get_event_loop() results = event_loop.run_until_complete( get_report_async(event_loop, request_header, report_ids)) print(results)