def initialize(self):
        self.status = self.STATUS_IDLE
        self.currentObject = None # Set this to a string

        self.output = []
        n = DownloadManager.NEW_OUTPUT_NOTIFICATION
        Notification.addObserver(self, n)
    def initialize(self):
        self.queueBox = QueueBox.QueueBox(self, (1, 1))
        self.queueBox.downloadManager = self.downloadManager
        self.queueBoxDetails = QueueBox.DetailsScreen(self, self.queueBox)
        self.addChild(self.queueBox)
        self.addChild(self.queueBoxDetails)

        self.statusBox = StatusBox(self, (1, 1))
        self.addChild(self.statusBox)

        self.doneBox = DoneBox.DoneBox(self, (1, 1))
        self.doneBox.downloadManager = self.downloadManager
        self.doneBoxDetails = DoneBox.DetailsScreen(self, self.doneBox)
        self.addChild(self.doneBox)
        self.addChild(self.doneBoxDetails)

        self.automaticallyCycleThroughChildren = True

        self.__pendingAlert = None
        try:
            self.downloadManager.load()
        except FileNotFoundError:
            pass
        except Exception as e:
            self.__handleException(e)

        ns = [DownloadManager.NEXT_DOWNLOAD_NOTIFICATION,
             DownloadManager.DONE_NOTIFICATION,
             DownloadManager.STOPPED_NOTIFICATION]
        for n in ns:
            Notification.addObserver(self, n)
Exemple #3
0
def create_notification(sender, instance, created, **kwargs):
    """This receiver creates notifications whenever a comment is saved
  """
    if created:
        parent = instance.content_object
        # Some Events don't have authors. In such cases, no need to create notifications.
        try:
            user = parent.author
        except:
            user = None

        if user and not user == instance.user:
            parent_comment = instance.parent
            # If this is a comment alert the commenter instead
            if parent_comment:
                notify_type = "comment"
                user = parent_comment.user
            else:
                notify_type = parent.type_name().lower()
            read = NotificationRead.objects.get(user=user)
            notify = Notification(user=user,
                                  author=instance.user,
                                  content_object=parent,
                                  time=datetime.datetime.utcnow(),
                                  notification_type=notify_type)
            notify.save()
            read.unread = read.unread + 1
            read.save()
Exemple #4
0
 def start_chat(self):
     self.__client_name = self.__name.get().strip('\n').strip(' ')
     client_pass = self.__password.get().strip('\n').strip(' ')
     self.__my_cursor.execute(
         "SELECT * FROM users WHERE name=%s AND Password=%s",
         (self.__client_name, client_pass))
     msg = self.__my_cursor.fetchone()
     if client_pass is not None and self.__client_name is not None:
         if not msg:
             Notification('the user doesn\'t exist').start()
             return
         self.__my_cursor.execute(
             "SELECT connected FROM users WHERE name=%s AND Password=%s",
             (self.__client_name, client_pass))
         msg = self.__my_cursor.fetchone()
         if msg[0] == 'True':
             Notification('the user already connected to the chat').start()
             return
         else:
             sqlf = "UPDATE users SET connected='True' WHERE name=%s AND Password=%s"
             self.__my_cursor.execute(sqlf,
                                      (self.__client_name, client_pass))
             self.__my_database.commit()
             name_len = len(self.__client_name)
             self.__client_name = str(name_len) + self.__client_name
         try:
             Chat(Host, Port, self.__client_name, self.__window,
                  self.__start)
         except:
             Notification('The server is currently unavailable').start()
             sql = "UPDATE users SET connected='False' WHERE name=%s "
             self.__my_cursor.execute(sql, (self.__client_name[1:], ))
             self.__my_database.commit()
class Descompactar:
    def __init__(self):
        self.arquivo = Arquivo()
        self.noticacao = Notification()

    def start(self, origem, destinoPasta, destinoProjeto, app_nome):
        zip_ref = zipfile.ZipFile(origem, 'r')
        zip_ref.extractall(destinoPasta)
        zip_ref.close()

        if os.path.exists(destinoProjeto):
            pass


        shutil.move(destinoPasta + app_nome + "/ios/AppIcon.appiconset", destinoProjeto)
        os.remove(origem)
        #os.remove(destinoPasta + app_nome)
        self.noticacao.send("Imagem AppIcon","AppIcon definido no projeto")

    def downloadZip(self, appName, destinoProjeto):
        app_nome = appName
        nameArquivo = app_nome + ".zip"
        localArquivo = Caminhos.caminhoTesteIOS + nameArquivo

        caminho = "https://github.com/gustaveco1997/imagens/raw/master/Imagens Apps/" + app_nome + ".zip"

        if not os.path.exists(Caminhos.caminhoTesteIOS):
            os.mkdir(Caminhos.caminhoTesteIOS)

        self.arquivo.baixarConteudo(caminho, localArquivo,False)
        self.start(localArquivo, Caminhos.caminhoTesteIOS, destinoProjeto, app_nome)
Exemple #6
0
def create_notification(sender, instance, created, **kwargs):
    """This receiver creates notifications whenever a comment is saved
  """
    if created:
        parent = instance.content_object
        # Some Events don't have authors. In such cases, no need to create notifications.
        try:
            user = parent.author
        except:
            user = None

        if user and not user == instance.user:
            parent_comment = instance.parent
            # If this is a comment alert the commenter instead
            if parent_comment:
                notify_type = "comment"
                user = parent_comment.user
            else:
                notify_type = parent.type_name().lower()
            read = NotificationRead.objects.get(user=user)
            notify = Notification(
                user=user,
                author=instance.user,
                content_object=parent,
                time=datetime.datetime.utcnow(),
                notification_type=notify_type,
            )
            notify.save()
            read.unread = read.unread + 1
            read.save()
	def post(self):
		statusCode = 200
		recurrenceRate = self.request.get('recurrenceRate')
		senderEmail = self.request.get('senderEmail')
		receiverEmail = self.request.get('receiverEmail')
		sender = User.query(User.emailAddress == senderEmail).get()
		if sender:
			receiver = User.query(User.emailAddress == receiverEmail).get()
			if receiver:
				'''
				A lot of this is a repeat of above. One thing that is different is I look for both receiverId and receiverAddress.
				This is because I am not sure what the user will send to the API. Basically, I look for receiverId first, if it
				does exist I move on, if not, then I look for the receiverAddress, use that to get the user, and then set the Id.
				It just adds a little bit of flexibility for the user.

				below is an example of using the request body to populate contents. In this we use json.loads. It is the reverse
				of json.dumps, it takes a string and returns a json object (really just a map with stuff in it). Now that I am
				looking at it, I am not sure if I need to loads and then dumps. I think it is because self.request.body is not
				written in actual characters so we need to load and then dump into an actual string object but I haven't tested
				enough to know either way. But I know this works.
				'''
				contents = json.dumps(json.loads(self.request.body))
				'''
				This is how you create a new entity row. Use the constructor and pass whatever variables you want to it. 
				There are some variables that are auto filled (like creationDate) these should not be given a value. There
				are attributes that have a default value, these can be given values but is not required, if a value is not given
				it uses the default value. Everything else needs a value or it is null. The constructor returns a key to the newly
				created object but it has not been added to the table yet. You need to call .put() to add it. This is also how you
				update rows. Call notification.query().get() to get the row, make any changes, and then call .put() to update the table.

				'''
				notification = Notification(contents=contents, recurrenceRate=recurrenceRate, senderEmail=senderEmail, receiverEmail=receiverEmail)
				notification.put()
		self.response.write(json.dumps({'statusCode': statusCode}))
Exemple #8
0
    def setUp(self):
        self.student = User("user", "password", 1)
        self.lecture = LectureTopic(1, "L1", "author", "Lecture", "info")
        self.comment = Comment(1, "author", "info", 2, self.lecture.getLTid())
        self.subscribe = Subscription(1, self.lecture.getLTid(),
                                      self.student.getUid())
        self.notify = Notification(1, self.subscribe.getSid())

        self.db_fd, app.app.config['DATABASE'] = tempfile.mkstemp()
        app.app.testing = True
        self.app = app.app.test_client()
        with app.app.app_context():
            app.init_db()
Exemple #9
0
    def __init__(self,data,dataManager,monitor):

        self.__dataLogger = data
        self.__databaseManager = dataManager
        self.__monitor = monitor
        self.__notifier = Notification(self.__databaseManager)
        
        self.__temperature = self.__dataLogger.getTemperature()
        self.__humidity = self.__dataLogger.getHumidity()
        self.__minTemperature = self.__monitor.getMinTemperature()
        self.__maxTemperature = self.__monitor.getMaxTemperature()
        self.__minHumidity = self.__monitor.getMinHumidity()
        self.__maxHumidity = self.__monitor.getMaxHumidity()
    def __downloadNextItem(self):
        with self.__lock:
            if self.__shouldStop == True:
                self.__shouldStop = False
                self.active = None

                notifName = DownloadThread.DONE_NOTIFICATION
                Notification.removeObserver(self, notifName)
                self.__notifyStopped()
                return

            if len(self.queue) == 0:
                self.active = None

                notifName = DownloadThread.DONE_NOTIFICATION
                Notification.removeObserver(self, notifName)
                self.__notifyDone()
                return

            # Start the download-thread
            notifName = DownloadThread.DONE_NOTIFICATION
            Notification.addObserver(self, notifName)

            notifName = DownloadThread.NEW_OUTPUT_NOTIFICATION
            Notification.addObserver(self, notifName)

            self.active = self.queue[0]
            del self.queue[0]
            self.__downloadThread = DownloadThread(self.active)
            self.__downloadThread.start()

            self.__notifyNextDownload()
Exemple #11
0
    def __init__(self, severity, client, cust, server, tech, link):
        Notification.__init__(self, client, cust, server, tech, link)
        self.severity = severity

        st = "Hi, I found a"
        if self.severity == 'Important':
            st += "n "
        st += f"{self.severity} security Update On \n"
        st += self.link
        st += f"\nThe Update is for {self.tech}"
        st += "\nGo Check It Out, it emplies to "
        st += f"{self.client} at {self.cust} enviorment, on {self.server}"

        self.text = st
Exemple #12
0
    def definirConstantes(self, master):
        self.ANDROID = "android"
        self.IOS = "IOS"

        self.notify = Notification()

        self.caminhoTodosApps = Caminhos.todosAppsAndroid
        self.caminhoNovosApps = Caminhos.novosAppsAndroid

        self.caminhoTodosAppsIOS = Caminhos.todosAppsIOS
        self.caminhoNovosAppsIOS = Caminhos.novosAppsIOS

        self.caminhoTodasImagens = Caminhos.origemImagens
        self.caminhoNovasImagens = Caminhos.todasImagens

        self.caminhoSelecionado = ""
        self.caminhoSelecionadoImagens = ""

        self.isGerarSelecionados = 1
        self.isPublicarLoja = 0
        self.isGerarApk = 1
        self.isAtualizarAntes = 0

        self.lista = []
        self.master = master
Exemple #13
0
 def run(self):
     config = Config('./credentials.properties')
     exchangeName = "test"
     notification = Notification(config, exchangeName)
     interval = 10  #this is the time interval in second where the system load is check (i.e., control Interval)
     loadDetectionInstance = PMLoadDetection(interval, notification)
     loadDetectionInstance.start()
	def getDetail(self, notificationId):
		#statusCodes:
		#200 ok
		#201 other error
		statusCode = 202
		notifications = []
		#USE workout.query to return all workouts and select the one that has the right id
		# also use debug.log to return inportant information 
		for notification in Notification.query():
			logging.debug(notification.JSONOutputDetail())
		logging.debug(notificationId)
		notification = Notification.get_by_id(int(notificationId))
		if notification:
			statusCode = 200
			notifications.append(notification.JSONOutputDetail())
		self.response.write(json.dumps({'statusCode': statusCode, 'notifications': notifications}))
 def run(self):
     logger.info("Thread of TriggerHandler initialized")
     count = 0
     try:
         while True:
             count += 1
             time.sleep(self.sleepTime)
             logger.debug(f"Checking, Run: {count}")
             for i in self.triggers.values():
                 if not i.activated:
                     continue
                 ticker = yf.Ticker(i.symbol)
                 logging.debug(f"Obtained Ticker, {i.symbol}")
                 information = ticker.info
                 logging.debug(
                     f"Checking ticker.info, {information['previousClose']} for stock {information['longName']}"
                 )
                 price = None
                 if information['ask'] == 0:
                     price = float(information['previousClose'])
                 else:
                     price = float(information['ask'])
                 if i.relation(price, float(i.value)):
                     Notification(i, information['longName'])
                     if i.autoDeactivateOnTrigger:
                         i.activated = False
     except:  # noqa: E722
         exc_type, exc_obj, exc_tb = sys.exc_info()
         fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
         logger.error("ERROR! Type: {}, File: {}, Line: {}".format(
             exc_type, fname, exc_tb.tb_lineno))
    def __cursesWrapper(self, stdscr):
        curses.curs_set(0) # No cursor
        stdscr.nodelay(1) # getch returns immediately
        stdscr.notimeout(1) # escape sequences come immediately

        # Begin with the initialization screen
        prefs = self.preferences
        doneHandler = self.__initializationFinished
        self.mainScreen = InitializationScreen(prefs, doneHandler, None, (0, 0))
        self.mainScreen.stdscr = stdscr

        # Make sure the terminal has enough space
        self.__handleTerminalResize(False)
        self.mainScreen.makeFirstResponder()

        # Main runloop
        while True:
            # Notifications
            Notification.handleNotifications()

            # List of responders
            c = stdscr.getch()
            if c == -1:
                continue
            
            if c == curses.KEY_RESIZE:
                self.__handleTerminalResize()
                continue

            r = self.mainScreen
            responders = [r]
            while True: 
                r = r.parentResponder
                if r != None:
                    responders.append(r)
                else:
                    break

            # Top down
            for i in range(len(responders)-1, -1, -1):
                r = responders[i]
                if r.activeModalSession() != None:
                    break
                
                if r.respondsTo(c):
                    r.handleEvent(c)
                    break
Exemple #17
0
async def on_message(message):
    fmt = "%H:%M:%S %m/%d/%Y"
    if message.author == client.user:  #client.user is remindbot.
        return  #avoid infinite loop.
    #$remind time date
    #time 00:00-23:59
    #date MM/DD/YYYY
    if message.content.startswith('$help'):
        await message.channel.send(
            'Syntax: \n $remind Hour:Min Month/Date/Year Meeting_Title')
        await message.channel.send(
            'All times are in PST, and Hours are recorded from 0 to 24. React to RemindBot\'s reply to sign up for the event.'
        )
    if message.content.startswith('$remind'):
        splitStr = []
        splitStr = message.content.split(" ")
        #print(splitStr)
        time = splitStr[1].split(
            ":")  # Get Time divided into a list 0:Hours 1:Min
        date = splitStr[2].split(
            "/")  # Get Date divided into a list 0:Months 1:Day 2:Year
        if int(time[0]) > 23 or int(time[0]) < 0 or int(time[1]) < 0 or int(
                time[1]) > 59 or int(date[0]) > 12 or int(date[0]) < 1:
            await message.channel.send('Bad format')
            return
        time_object_current = datetime.now(timezone('US/Pacific'))
        time_object_current_new = time_object_current  #.replace(second = 0)
        current_time = time_object_current_new.strftime(fmt)
        print("Current time: ", current_time)
        #splitStr[1] += ":00" + splitStr[2]
        #print(splitStr[1])
        print(time)
        print(date)
        time_object_user = datetime(int(date[2]),
                                    int(date[0]),
                                    int(date[1]),
                                    hour=int(time[0]),
                                    minute=int(time[1]),
                                    tzinfo=timezone('US/Pacific'))
        user_time = time_object_user.strftime(fmt)
        print("User Time: ", user_time)
        time = (time_object_user -
                time_object_current_new).total_seconds() + 420
        print(time)
        #t = #Timer(time, #method_name_here)#
        #t.start()
        title = " "
        s = title.join(splitStr[3:])
        bot = await message.channel.send(" ***" + s + "*** " +
                                         ' Meeting scheduled at: ' + user_time)
        await bot.add_reaction("\N{THUMBS UP SIGN}")
        #time_funcs.sleep(5)
        print("TITLE:", s)
        print(bot.id)
        print(message.id)
        noti = Notification(s, time, [], bot)
        notificationDict[bot.id] = noti
        print(notificationDict)
        await noti.mention_ping()
Exemple #18
0
 def testPostNotification_empty_message(self):
     self.connection = db_connect()
     self.user = login(self.connection, '*****@*****.**', 'BlackInk')
     notif = Notification()
     try:
         post_notification(self.user, self.connection, notif)
     except ValueError:
         self.failstate = True
     self.assertTrue(self.failstate)
 def fset(self, value):
     old_value = self._percent_complete
     self._percent_complete = value
     notification = Notification(message=NOTIFICATIONS[1],
                                 sender=self,
                                 user_info=dict(
                                     old_percentage=old_value,
                                     new_percentage=value))
     self.notification_center.post_notification(notification)
    def __init__(self):
        """
            On initialisation the BluetoothManager class retrieves the temperature ranges from the Monitor Class
        """

        #declare variables that handle interactions with other classes
        self.__monitor = Monitor()
        self.__notifier = Notification()

        #declare variables that will store the head and message that will be sent via pushbullet
        self.__head = None
        self.__message = None

        #declare variables the store the ranges from the Monitor class using the classes methods
        self.__minTemperature = self.__monitor.getMinTemperature()
        self.__maxTemperature = self.__monitor.getMaxTemperature()
        self.__minHumidity = self.__monitor.getMinHumidity()
        self.__maxHumidity = self.__monitor.getMaxHumidity()
 def post_notification_with_info(self, message, sender, user_info=None):
     """
     TODO: Docstring for post_notification_with_info
     
     @param message TODO
     @param sender TODO
     @param user_info TODO
     """
     self.post_notification(Notification(message, sender, user_info))
Exemple #22
0
    def criarInstancias(self, tela):
        self.notify = Notification()
        self.googleSheets = GoogleSheets()
        self.relatorio = Relatorio()
        self.descompactar = Descompactar()
        self.email = Email()
        self.areaTeste = AreaTestes()

        self.tela = tela
Exemple #23
0
 def change_password(self):
     password = ask_string('Password', 'Enter your new password')
     if password is not None:
         password = password.strip()
         if not password or not password.isalnum():
             Notification('invalid password').start()
             return
         self.__d.get_my_cursor().execute('UPDATE users SET password="******" WHERE name=%s', (self.__me[1:],))
         Info('password has been changed successfully to '+password).start()
 def fset(self, value):
     old_value = self._percent_complete
     if value == old_value:
         # Do not update or send a notification if nothing has changed
         return
     self._percent_complete = value
     notification = Notification(message=NOTIFICATIONS[1],
                                 sender=self,
                                 user_info=dict(old_percentage=old_value, new_percentage=value))
     self.notification_center.post_notification(notification)
Exemple #25
0
 def testPostNotification(self):
     self.connection = db_connect()
     self.user = login(self.connection, '*****@*****.**', 'BlackInk')
     self.failstate = False
     notif = Notification('', 'GOOGL', 0.00, 'Hello World')
     try:
         key = post_notification(self.user, self.connection, notif)
     except ValueError:
         self.failstate = True
     self.assertFalse(self.failstate)
     del_notification(self.user, self.connection, key['name'])
 def awakeFromNib(self):
     def onGrowlClick():
         self.applicationRef.unhide()
         self.cbxInput.becomeFirstResponder()
         
     self.notification = Notification(onGrowlClick)
     self.initControls()
     self.initWindowStates()
     self.readCounters()
     self._timer = NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(Settings.get("timerInterval"), 
                           self, self.timerFunction, None, True)
Exemple #27
0
def main():
    notification = Notification()
    command = input()

    while command.split(' ')[0] != 'EXIT':

        if command.split(' ')[0] == 'SEND':
            notification.set_message(command.split(' ', 2)[2])
            notification.set_state(States[command.split(' ')[1]])
            notifier.send_message(notification, States[command.split(' ')[1]])

        command = input()

    notification.set_message(command)
    notifier.send_message(notification, 0)
    open("legitnetwork.txt", "w").close()
 def fset(self, value):
     value = value.upper()
     if(value == self._status):
         # Do not update or send a notification if nothing has changed
         return
     if(value in STATUS_STRINGS):
         old_value = self._status
         self._status = value
         notification = Notification(message=NOTIFICATIONS[0],
                                     sender=self,
                                     user_info=dict(old_status=old_value, new_status=value))
         self.notification_center.post_notification(notification)
     else:
         raise KeyError('Status (%s) unknown. Use one of %s.' % (value, STATUS_STRINGS))
	def delete(self):
		'''
		This is a very simple delete function that uses notificationId to select the notification and then delete it.
		Although, you need to do .key.delete() in order to delete it. There is no delete function for entities. In fact
		there is no put function either, the constructor above returns a key. So you actually need to call .key.put()
		'''
		statusCode = 201
		notificationId = self.request.get('notificationId')
		logging.info(self.request.get('notificationId'))
		notification = Notification.get_by_id(int(notificationId))
		if notification:
			statusCode = 200
			notification.key.delete()
		logging.info(statusCode)
		self.response.write(json.dumps({'statusCode': statusCode}))
Exemple #30
0
    def sql_retrieve(conn, searchfield=None, searchval=None):
        conn.row_factory = sqlite3.Row
        if searchfield:
            cur = conn.execute(
                'SELECT * FROM Notification WHERE "{}"="{}"'.format(
                    searchfield, searchval))
        else:
            cur = conn.execute('SELECT * from Notification')

        # construct the object
        results = []
        for tablerow in cur.fetchall():
            newobj = Notification(tablerow['Nid'], tablerow['subscription'])
            results.append(newobj)
        return results
Exemple #31
0
 def testDeleteNotification(self):
     self.connection =db_connect()
     self.user = login(self.connection, '*****@*****.**', 'BlackInk')
     self.failstate = False
     notif = Notification('', 'GOOGL', 0.00, 'Hello World')
     key= post_notification(self.user, self.connection, notif)
     notifList = pull_notifications(self.user, self.connection)
     self.assertNotEqual(notifList, None)
     for i in notifList:
         if i == key['name']:
             try:
                 del_notification(self.user, self.connection, i)
             except:
                 self.failstate = True
             self.assertFalse(self.failstate)
             break
Exemple #32
0
def postComment(type, form, LTid):
    body = form.Body.data
    # When creating a new comment the 0 for the id is just a place holder because when put into the database we will auto increment the id
    newPost = Comment(0, session['user_id'], body, 0, LTid)
    persist(newPost)
    subscriptions = retrieve(Subscription, "LTid", LTid)

    for subscription in subscriptions:
        newNotification = Notification(0, subscription.getSid())
        persist(newNotification)

    flash('Comment Created', 'success')
    if type == 'Topic':
        return redirect(url_for("topic_discussion", id = LTid))
    elif type == 'Lecture':
        return redirect(url_for("lecture_discussion", id = LTid))
Exemple #33
0
    def notification_for_ticket(ticket: Ticket):
        title = "Ticket Updated"
        email_address = ticket.email_address

        message = None
        if ticket.status == "Created":
            message = "Your ticket has been created!"
        elif ticket.status == "Waiting on client input":
            message = "Your project is waiting on client input."
        elif ticket.status == "Ready for pickup":
            message = "Your project is ready for pickup!"
        elif ticket.status == "Closed":
            message = "Your ticket has been closed."
        else:
            message = ticket.status

        return Notification(title, message, email_address)
    def __run_daemon(self, TEST_MODE: bool = False):
        # initiaing BatteryMonitor
        try:
            monitor = BatteryMonitor(TEST_MODE)
        except subprocess.CalledProcessError as e:
            # initiaing Notification
            notification = Notification("acpi")
            time.sleep(3)
            del notification
            self.__quit()

        # initiaing Notification
        notification = Notification("success")
        time.sleep(3)
        notification.show_specific_notifications(monitor)
        while True:
            if monitor.is_updated():
                notification.show_specific_notifications(monitor)
            time.sleep(3)
Exemple #35
0
def main():
    initialize_config()

    # Configure logging. Reset with every restart
    logging.basicConfig(
        format='%(asctime)s [%(levelname)s]:[%(threadName)s] %(message)s',
        filename=log_file_path,
        filemode='w',
        level=logging.INFO)
    logging.info("Starting Safe Eyes")

    if not running():
        validate_config()

        global break_screen
        global core
        global notification
        global tray_icon
        global language
        global context

        context = {}
        language = Utility.load_language(config['language'])

        # Initialize the Safe Eyes Context
        context['version'] = SAFE_EYES_VERSION

        tray_icon = TrayIcon(config, language, show_settings, show_about,
                             enable_safeeyes, disable_safeeyes, on_quit)
        break_screen = BreakScreen(on_skipped, on_postponed,
                                   break_screen_glade, style_sheet_path)
        break_screen.initialize(config, language)
        core = SafeEyesCore(context, show_notification, show_alert,
                            close_alert, on_countdown,
                            tray_icon.next_break_time)
        core.initialize(config, language)
        core.start()
        notification = Notification(language)

        handle_system_suspend()

        Gtk.main()
    else:
        logging.info('SafeEyes is already running')
        sys.exit(0)
Exemple #36
0
 def command_1(self, data):
     data = data[1:]
     if 'had been kicked you out from the chat' in data:
         self.kick_from_chat(data)
         return 0
     if 'You have unmuted' in data or 'You have muted' in data or 'You have been muted by' in data \
             or 'You have been unmuted by' in data:
         Info(data).start()
         return 1
     if 'You can\'t kick your self' in data or 'You are not a manager' in data \
             or ' doesn\'t exist in the chat' \
             in data or 'This client does not exist' in data or \
             'You can\'t mute yourself' in data or 'is not in the chat' in data or \
             ' doesn\'t exist in the chat' in data \
             or "You can't send a private message to yourself" in data:
         Notification(data).start()
         return 1
     else:
         self.regular_msg(data)
         return 1
Exemple #37
0
 def get_input(self, event1):
     if self.__handle_data.get_mute() == 'True':
         Notification('You can not speak here').start()
         self.__entry.delete(0, 'end')
         return
     else:
         message = self.__entry.get()
         message = message.strip()
         if message == '' or message is None:
             return ''
         self.__txt.config(state=NORMAL)
         self.__message_tag = 'The message date is ' + DATE + ' ' + str(
             time.strftime("%H:%M"))
         self.__txt.insert(
             END,
             str(time.strftime("%H:%M")) + " " + message + '\n',
             (self.__message_tag, ))
         self.__txt.tag_bind(
             self.__message_tag,
             "<Enter>",
             lambda event, date=self.__message_tag: self.show_info(date))
         self.__txt.tag_bind(
             self.__message_tag,
             "<Leave>",
             lambda event, date=self.__message_tag: self.show_info(""))
         self.__txt.yview(END)
         self.__entry.delete(0, 'end')
         self.__my_chat = self.__my_chat + DATE + ' ' + str(time.strftime("%H:%M")) + " " + self.__client_name[1:]\
                         + ': ' + emoji.demojize(message) + '\n'
         sql = "UPDATE users SET chat = %s "
         self.__my_cursor.execute(sql, (self.__my_chat, ))
         message = '01' + message
         self.__client_socket.write((self.__client_name + message).encode())
         self.__txt.config(state=DISABLED)
         if message == '0101quit':
             self.__root.quit()
             self.exit()
	def getShort(self, recieverEmail, user):
		#statusCodes:
		#200 ok
		#201 other error
		statusCode = 201
		notifications = []
		'''
		I use 'if user' as a check if the user entity actually exists. It is checking if it is null.
		Which, if you check back up in .get is what that function will return if it can't find anything.
		So, if it is not null I know I have something to work with
		'''
		if user:
			statusCode = 200
			'''
			You may have noticed that I said .get after the User.query() function up in get but not here.
			That is because .query returns an iterable list of query objects, not something you can just access
			really well. So you can either do User.query().get() to return the first entry in the list (There are
				ways to get other indexes but I am not sure how). You would only really want to do this if you know
			there is going to be exactly one row returned. Otherwise you can put it into a foreach loop without the
			.get at the end. This lets you iterate through everything where notification is an actual Notification
			object and not some weird query thing.
			'''
			for notification in Notification.query(Notification.receiverEmail == user.emailAddress):
				'''
				I then add each notification information to an array of notifications with append.
				This is the main format I return lists of stuff in since GSON can pull that information
				and put it into an array of a certain object.
				'''
				notifications.append(notification.JSONOutputShort())
		'''
		json.dumps is the way to write json to the response. This is because it takes json and returns a string of json.
		There is a json.dump function but that returns an actual JSON object and does not write correctly.
		Also, notice that there are {} in the .dumps function. This is the other list structure in python, dictionary.
		It is similar to map in java. You give it a string as a key and some other variable as the value
		'''
		self.response.write(json.dumps({'statusCode': statusCode, 'notifications': notifications}))
Exemple #39
0
 def start_chat(self):
     self.__client_name = self.__name.get().strip('\n').strip(' ')
     client_pass = self.__password.get().strip('\n').strip(' ')
     sql = 'INSERT INTO users (name, Password) VALUES(%s, %s)'
     sql2 = 'INSERT INTO private_chats (name) VALUES(%s)'
     if client_pass is not None and self.__client_name is not None:
         client_pass = client_pass.strip()
         self.__client_name = self.__client_name.strip('\n')
         self.__client_name = self.__client_name.strip()
         if not self.__client_name or not client_pass:
             Notification('please try again').start()
             return
         self.__client_name = self.__client_name.replace(' ', '_')
         self.__my_cursor.execute('SELECT name FROM users ')
         msg = self.__my_cursor.fetchall()
         if self.__client_name[0] == '@':
             Notification('the username cannot begins with @').start()
             return
         if not client_pass:
             Notification('invalid password').start()
         if len(self.__client_name) > 9:
             Notification('Please Enter a shorter username').start()
             return
         for i in msg:
             if i[0] == self.__client_name:
                 Notification('The username already exist').start()
                 return
         user1 = (self.__client_name, client_pass)
         sql3 = "ALTER TABLE private_chats ADD COLUMN " + self.__client_name + " TEXT(5000) "
         self.__my_cursor.execute(sql, user1)
         self.__my_cursor.execute(sql2, (self.__client_name,))
         self.__my_cursor.execute(sql3)
         self.__my_database.commit()
         self.__client_name = str(len(self.__client_name)) + self.__client_name
         try:
             Chat(Host, Port, self.__client_name, self.__window, self.__start)
         except:
             Notification('The server is currently unavailable').start()
             sql = "UPDATE users SET connected='False' WHERE name=%s "
             self.__my_cursor.execute(sql, (self.__client_name[1:],))
             self.__my_database.commit()
Exemple #40
0
class UnitTests(TestCase):
    def setUp(self):
        # Setting up mock database
        self.supervisor = User.objects.create(username="******",
                                              password="******",
                                              permissions="1000",
                                              address="testAddress",
                                              phonenumber="TestPhoneNum",
                                              email="TestEmail")
        self.admin = User.objects.create(username="******",
                                         password="******",
                                         permissions="0111",
                                         address="testAddress",
                                         phonenumber="TestPhoneNum",
                                         email="TestEmail")
        self.ta = User.objects.create(username="******",
                                      password="******",
                                      permissions="0001",
                                      address="testAddress",
                                      phonenumber="TestPhoneNum",
                                      email="TestEmail")
        self.instructor = User.objects.create(username="******",
                                              password="******",
                                              permissions="0010",
                                              address="testAddress",
                                              phonenumber="TestPhoneNum",
                                              email="TestEmail")
        self.userNoPriv = User.objects.create(username="******",
                                              password="******",
                                              permissions="0000",
                                              address="testAddress",
                                              phonenumber="TestPhoneNum",
                                              email="TestEmail")
        self.testuser = User.objects.create(username="******",
                                            password="******",
                                            permissions="0000",
                                            address="testAddress",
                                            phonenumber="TestPhoneNum",
                                            email="TestEmail")

    u = UserEdits()
    n = Notification()
    c = CourseEdit()
    d = DataRetrieval()

    def test_add_userUnsuccessful(self):
        self.assertEqual(
            self.u.add_user("bad", "bad", "-1", "home", "4141231234",
                            "*****@*****.**", self.admin),
            "Failed to add user. Improper parameters")

    def test_add_user_TA_NoPermission(self):
        self.assertEqual(
            self.u.add_user("UserName", "userpassword", "0001", "home",
                            "4141231234", "*****@*****.**", self.ta),
            "Illegal permissions to do this action")

    def test_add_user_Instructor_NoPermission(self):
        self.assertEqual(
            self.u.add_user("UserName", "password", "0001", "home",
                            "4141231234", "*****@*****.**",
                            self.instructor),
            "Illegal permissions to do this action")

    def test_add_user_Admin_Successful(self):
        self.assertEqual(
            "User successfully added",
            self.u.add_user("UserName", "password", "0001", "home",
                            "4141231234", "*****@*****.**", self.admin))

    def test_add_user_Supervisor_Successful(self):
        self.assertEqual(
            self.u.add_user("UserName", "password", "0001", "home",
                            "4141231234", "*****@*****.**",
                            self.supervisor), "User successfully added")

    def test_add_user_Admin_Failed(self):
        self.assertEqual(
            self.u.add_user(" ", "password", "0001", "home", "4141231234",
                            "studgmailcom", self.admin),
            "Failed to add user. Improper parameters")

    def test_add_user_Supervisor_Failed(self):
        self.assertEqual(
            self.u.add_user("UserName", " ", "0001", "home", "4141231234",
                            "studgmail.com", self.supervisor),
            "Failed to add user. Improper parameters")

    def test_delete_user_TA_NoPermission(self):
        self.assertEqual(self.u.delete_user(1, self.ta),
                         "Illegal permissions to do this action")

    def test_delete_user_Instructor_NoPermission(self):
        self.assertEqual(self.u.delete_user(1, self.instructor),
                         "Illegal permissions to do this action")

    def test_delete_user_Admin_FailedToDelete(self):
        self.assertEqual(self.u.delete_user(-1, self.admin),
                         "User unsuccessfully deleted")

    def test_delete_user_Supervisor_FailedToDelete(self):
        self.assertEqual(self.u.delete_user(-1, self.supervisor),
                         "User unsuccessfully deleted")

    def test_delete_user_Supervisor_FailedToDelete_Cannot_Delete_Self(self):
        self.assertEqual(self.u.delete_user("superu", self.supervisor),
                         "Unable to delete active user")

    def test_delete_user_Admin_SuccessDelete(self):
        self.assertEqual(self.u.delete_user("testuser", self.admin),
                         "User successfully deleted")

    def test_delete_user_Supervisor_SuccessToDelete(self):
        self.assertEqual(self.u.delete_user("testuser", self.supervisor),
                         "User successfully deleted")

    def test_ChangeUser_Admin_IllegalField(self):
        self.assertEqual(self.u.change_contact("User", "NewField", "BadField"),
                         "Illegal changed field")

    def test_ChangeUser_Supervisor_IllegalField(self):
        self.assertEqual(self.u.change_contact("User", "NewField", "BadField"),
                         "Illegal changed field")

    def test_ChangeUser_Admin_IllegalChangedField(self):
        self.assertEqual(self.u.change_contact("User", "***a!`", "Name"),
                         "Illegal changed field")

    def test_ChangeUser_Supervisor_IllegalChangedField(self):
        self.assertEqual(self.u.change_contact("User", "***a!`", "Name"),
                         "Illegal changed field")

    def test_ChangeUser_Admin_Success(self):
        self.assertEqual(self.u.change_contact("admin", "password", "Name"),
                         "Contact information changed")

    def test_ChangeUser_Supervisor_Success(self):
        self.assertEqual(self.u.change_contact("superu", "password", "Name"),
                         "Contact information changed")

    def test_edit_user_TA_NoPermission(self):
        self.assertEqual(
            self.u.edit_user("testuser", "username", "NewName", self.ta),
            "Illegal permissions to do this action")

    def test_edit_user_Instructor_NoPermission(self):
        self.assertEqual(
            self.u.edit_user("testuser", "username", "NewName",
                             self.instructor),
            "Illegal permissions to do this action")

    def test_edit_user_Admin_UserDNE(self):
        self.assertEqual(
            self.u.edit_user("userdne", "username", "NewName", self.admin),
            "Failed to update user")

    def test_edit_user_Supervisor_UserDNE(self):
        self.assertEqual(
            self.u.edit_user("superdne", "username", "NewName",
                             self.supervisor), "Failed to update user")

    def test_edit_user_Admin_IllegalFieldChange(self):
        self.assertEqual(
            self.u.edit_user("testuser", "IllegalField", "NewName",
                             self.admin), "Tried to change illegal field")

    def test_edit_user_Supervisor_IllegalFieldChange(self):
        self.assertEqual(
            self.u.edit_user("testuser", "IllegalField", "NewName",
                             self.supervisor), "Tried to change illegal field")

    def test_edit_user_Admin_IllegalChangedField(self):
        self.assertEqual(
            self.u.edit_user("testuser", "username", "****", self.admin),
            "Failed to updated user")

    def test_edit_user_Supervisor_IllegalChangedField(self):
        self.assertEqual(
            self.u.edit_user("testuser", "username", "****", self.supervisor),
            "Failed to updated user")

    def test_edit_user_Admin_SuccessfulChange(self):
        self.assertEqual(
            self.u.edit_user("testuser", "username", "NewName", self.admin),
            "User successfully updated")

    def test_edit_user_Supervisor_SuccessfulChange(self):
        self.assertEqual(
            self.u.edit_user("testuser", "username", "NewName",
                             self.supervisor), "User successfully updated")

    def test_SendNotification_TA_NoPermission(self):
        self.assertEqual(
            self.n.send_email("*****@*****.**", "*****@*****.**", "subject",
                              "body", self.ta),
            "Illegal permissions to do this action")

    def test_SendNotification_Instructor_NoPermission(self):
        self.assertEqual(
            self.n.send_email("*****@*****.**", "*****@*****.**", "subject",
                              "body", self.instructor),
            "Illegal permissions to do this action")

    def test_SendNotification_Admin_FromAddressDNE(self):
        self.assertEqual(
            self.n.send_email("*****@*****.**", "*****@*****.**",
                              "subject", "body", self.admin),
            "From user does not exist")

    def test_SendNotification_Supervisor_FromAddressDNE(self):
        self.assertEqual(
            self.n.send_email("*****@*****.**", "*****@*****.**",
                              "subject", "body", self.supervisor),
            "From user does not exist")

    def test_SendNotification_Admin_ToAddressDNE(self):
        self.assertEqual(
            self.n.send_email("*****@*****.**", "*****@*****.**",
                              "subject", "body", self.admin),
            "To user does not exist")

    def test_SendNotification_Supervisor_ToAddressDNE(self):
        self.assertEqual(
            self.n.send_email("*****@*****.**", "*****@*****.**",
                              "subject", "body", self.supervisor),
            "To user does not exist")

    def test_SendNotification_Admin_IllegalEmailBody(self):
        self.assertEqual(
            self.n.send_email("*****@*****.**", "*****@*****.**", "subject",
                              "  ", self.admin), "Illegal subject")

    def test_SendNotification_Supervisor_IllegalEmailBody(self):
        self.assertEqual(
            self.n.send_email("*****@*****.**", "*****@*****.**", "subject",
                              "  ", self.supervisor), "Illegal subject")

    def test_SendNotification_Admin_IllegalEmailSubject(self):
        self.assertEqual(
            self.n.send_email("*****@*****.**", "*****@*****.**", " ", "body",
                              self.admin), "Illegal email body")

    def test_SendNotification_Supervisor_IllegalEmailSubject(self):
        self.assertEqual(
            self.n.send_email("*****@*****.**", "*****@*****.**", " ", "body",
                              self.supervisor), "Illegal email body")

    def test_SendNotification_Admin_Success(self):
        self.assertEqual(
            self.n.send_email("*****@*****.**", "*****@*****.**", "subject",
                              "body", self.admin), "Email sent")

    def test_SendNotification_Supervisor_Success(self):
        self.assertEqual(
            self.n.send_email("*****@*****.**", "*****@*****.**", "subject",
                              "body", self.supervisor), "Email sent")

    def test_SendTaEmail_TA_NoPermission(self):
        self.assertEqual(
            self.n.send_email_to_ta("from@gmail", "to@gmail", "subject",
                                    "body", self.ta),
            "You do not have permission")

    def test_SendTAEmail_Instructor_TADoesNotExist(self):
        self.assertEqual(
            self.n.send_email_to_ta("from@gmail", "nonexistantta@gmail",
                                    "subject", "body", self.instructor),
            "TA does not exist")

    def test_SendTAEmail_Instructor_IllegalFrom(self):
        self.assertEqual(
            self.n.send_email_to_ta("*****@*****.**", "*****@*****.**",
                                    "subject", "body", self.instructor),
            "From user does not exist")

    def test_SendTAEmail_Instructor_IllegalEmailBody(self):
        self.assertEqual(
            self.n.send_email_to_ta("*****@*****.**", "*****@*****.**",
                                    "subject", " ", self.instructor),
            "Illegal email body")

    def test_SendTAEmail_Instructor_IllegalEmailSubject(self):
        self.assertEqual(
            self.n.send_email_to_ta("*****@*****.**", "*****@*****.**", " ",
                                    "body", self.instructor),
            "Illegal subject")

    def test_SendTAEmail_Instructor_Success(self):
        self.assertEqual(
            self.n.send_email_to_ta("*****@*****.**", "*****@*****.**",
                                    "subject", "body", self.instructor),
            "Email sent to TAs successfully")

    def test_SendTAEmail_Admin_Success(self):
        self.assertEqual(
            self.n.send_email_to_ta("*****@*****.**", "*****@*****.**",
                                    "subject", "body", self.admin),
            "Email sent to TAs successfully")

    def test_SendTAEmail_Supervisor_Success(self):
        self.assertEqual(
            self.n.send_email_to_ta("*****@*****.**", "*****@*****.**",
                                    "subject", "body", self.supervisor),
            "Email sent to TAs successfully")

    def test_view_all_courses_TA_NoCourses(self):
        self.assertEqual(self.c.view_all_courses(self.ta), "No courses")

    def test_view_all_courses_TA_Courses(self):
        self.assertEqual(self.c.view_all_courses(self.ta), "List of classes: ")

    def test_view_all_courses_Instructor_Courses(self):
        self.assertEqual(self.c.view_all_courses(self.instructor),
                         "List of classes: ")

    def test_view_all_courses_Admin_Courses(self):
        self.assertEqual(self.c.view_all_courses(self.admin),
                         "List of classes: ")

    def test_view_all_courses_Supervisor_Courses(self):
        self.assertEqual(self.c.view_all_courses(self.supervisor),
                         "List of classes: ")

    def test_assign_ta_TA_NoPermission(self):
        self.assertEqual(self.c.assign_ta("ta", 1, 800, self.ta),
                         "Do not have permissions for this action")

    def test_assign_ta_Instructor_TADNE(self):
        self.assertEqual(
            self.c.assign_ta("TADoesNotExist", 1, 800, self.instructor),
            "Ta does not exist")

    def test_assign_ta_Instructor_CourseDNE(self):
        self.assertEqual(
            self.c.assign_ta("taInDatabase", -1, 800, self.instructor),
            "Course section does not exist")

    def test_assign_ta_Instructor_LabSectionDNE(self):
        self.assertEqual(
            self.c.assign_ta("taInDatabase", 1, -1, self.instructor),
            "Lab section does not exist")

    def test_assign_ta_Instructor_Success(self):
        self.assertEqual(
            self.c.assign_ta("taInDatabase", 1, 800, self.instructor),
            "TA assigned to Course/Lab section")

    def test_assign_ta_Admin_Success(self):
        self.assertEqual(self.c.assign_ta("taInDatabase", 1, 800, self.admin),
                         "TA assigned to Course/Lab section")

    def test_assign_ta_Supervisor_Success(self):
        self.assertEqual(
            self.c.assign_ta("taInDatabase", 1, 800, self.supervisor),
            "TA assigned to Course/Lab section")

    def test_create_course_TA_NoPermission(self):
        self.assertEqual(
            self.c.create_course("instructorInDB", "courseInDb",
                                 datetime.now(), datetime.now(), self.ta),
            "Illegal permissions to do this action")

    def testcreate_course_Instructor_NoPermission(self):
        self.assertEqual(
            self.c.create_course("instructorInDB", "courseInDb",
                                 datetime.now(), datetime.now(),
                                 self.instructor),
            "Illegal permissions to do this action")

    def testcreate_course_Admin_InvalidTeacher(self):
        self.assertEqual(
            self.c.create_course("instructorNotInDb", "courseInDb",
                                 datetime.now(), datetime.now(), self.admin),
            "Teacher entered does not exist")

    def test_create_course_Admin_IllegalClassId(self):
        self.assertEqual(
            self.c.create_course("instructorU", "@@@@@", datetime.now(),
                                 datetime.now(), self.admin),
            "Illegal class id")

    def test_create_course_Admin_IllegalClassTime(self):
        self.assertEqual(
            self.c.create_course("instructorU", "courseInDb", datetime.now(),
                                 datetime.now() - timedelta(days=1),
                                 self.admin), "Illegal class time entered")

    def test_create_course_Admin_Success(self):
        self.assertEqual(
            self.c.create_course("instructorU", "courseInDb", datetime.now(),
                                 datetime.now() + timedelta(days=1),
                                 self.admin), "Course successfully added")

    def test_delete_course_TA_NoPermission(self):
        self.assertEqual(self.c.delete_course(1, self.ta),
                         "Do not have permission to complete this action")

    def test_delete_course_Instructor_NoPermission(self):
        self.assertEqual(self.c.delete_course(1, self.instructor),
                         "Do not have permission to complete this action")

    def test_delete_course_Admin_InvalidCourseId(self):
        self.assertEqual(self.c.delete_course(-1, self.admin),
                         "Invalid course ID entered")

    def test_view_course_assignments_TA_NoPermission(self):
        self.assertEqual(self.d.get_all_courses(self.ta),
                         "Illegal permissions to do this action")

    def test_view_course_assignments_Instructor_NoPermission(self):
        self.assertEqual(self.d.get_all_courses(self.instructor),
                         "Illegal permissions to do this action")

    def test_view_course_assignments_Admin_CourseIdDNE(self):
        self.assertEqual(self.c.view_course_assignments(-1, self.admin),
                         "Course does not exist")

    def test_view_course_assignments_Admin_Success(self):
        self.assertEqual(self.c.view_course_assignments(1, self.admin),
                         "Course assignments: ")

    def test_view_course_assignments_Supervisor_Success(self):
        self.assertEqual(self.c.view_course_assignments(1, self.supervisor),
                         "Course assignments: ")

    def test_view_database_get_info(self):
        list = self.d.view_database()
        self.assertEqual(len(list), 6)
 def __notifyNextDownload(self):
     n = Notification(self.NEXT_DOWNLOAD_NOTIFICATION, self)
     Notification.post(n)
 def __notifyNewOutput(self):
     n = Notification(self.NEW_OUTPUT_NOTIFICATION, self)
     Notification.post(n)
 def __notifyDone(self):
     n = Notification(self.DONE_NOTIFICATION, self)
     Notification.post(n)
 def __notifyStopped(self):
     n = Notification(self.STOPPED_NOTIFICATION, self)
     Notification.post(n)
Exemple #45
0
def parse_source_code(begin: int, end: int, destination: Collection):
    """This method is for parsing the source codes stored by SourceCodeExtractor.py"""

    print("Parsing source code..")

    companies_to_check = [
        "AKBNK", "GARAN", "BIMAS", "TUPRS", "TCELL", "SAHOL", "ISCTR", "EREGL",
        "KCHOL", "HALKB", "EKGYO", "THYAO", "ARCLK", "VAKBN", "PETKIM",
        "YKBNK", "TOASO", "SISE", "ASELS", "ENKA", "ULKER", "TTKOM", "TAVHL",
        "FROTO", "SODA", "TKFEN", "KRDMD", "MAVI", "KOZAL", "BIST30",
        "BIST100", "BORSAISTANBUL"
    ]

    # connecting to MongoDB
    client = MongoClient()
    db = client.web
    collection = db.tmp

    notifications = []
    for i in range(begin, end + 1):
        # print info
        print(i, (i - begin) * 100 / (end - begin + 1), "%")

        # store notifications to mongoDB after every 200
        if i != begin and i % 200 == 0:
            for item in notifications:
                try:
                    destination.insert_one(item)
                except DuplicateKeyError:
                    print(item["_id"], "----This element already exists----")

                    # optional: comment out to override the data in database
                    # collection.delete_one({"_id": item["_id"]})
                    # collection.insert_one(item)
            notifications.clear()

        try:
            # get source code and parse it
            item = collection.find_one({"_id": i})
            notification = Notification(item["source_code"], item["_id"])

            # add to the list if it is about our companies
            for company in notification.related_companies:
                if company in companies_to_check:
                    notifications.append(notification.dump())
                    break

        except TypeError:  # if it is not found
            print(i, "---not found---")

    # store the remaining notifications
    for item in notifications:
        try:
            destination.insert_one(item)
        except DuplicateKeyError:
            print(item["_id"], "---This element already exists---")

            # optional: comment out to override the data in database
            # collection.delete_one({"_id": item["_id"]})
            # collection.insert_one(item)
    # storing the last parsed notifications index
    try:
        destination.insert_one({'_id': 1, 'max_id': end})
    except DuplicateKeyError:
        destination.delete_one({'_id': 1})
        destination.insert_one({'_id': 1, 'max_id': end})

    collection.drop()
    print("Parsing source code is done!")
Exemple #46
0
class JosephPy:
    def criarInstancias(self, tela):
        self.notify = Notification()
        self.googleSheets = GoogleSheets()
        self.relatorio = Relatorio()
        self.tela = tela

    def definirConstantes(self):

        assinatura = "./gradlew assembleRelease "
        assinatura += "-Pandroid.injected.signing.store.file=" + Caminhos.keystore + " "
        assinatura += "-Pandroid.injected.signing.store.password=gtlgtlgtl "
        assinatura += "-Pandroid.injected.signing.key.alias=guilherme.vasconcelos "
        assinatura += "-Pandroid.injected.signing.key.password=gtlgtlgtl"  # a.sort()  # ordem alfabética

        build = "./gradlew build"
        task = "./gradlew task"
        clean = "./gradlew clean"
        publicar = "./gradlew publishApkRelease"

        self.tarefas = [task, build, assinatura, clean, publicar]
        self.dataInicio = datetime.datetime.now()

    def definirCaminhoCD(self):
        self.aplicativoBase = "cd " + Caminhos.aplicativoBaseNucleo
        self.prefixoAntigos = "cd " + Caminhos.todosAppsAndroidModificado
        self.prefixoNovos = "cd " + Caminhos.novosAppsAndroidModificado

    def __init__(self, tela=None):

        self.criarInstancias(tela)
        self.definirConstantes()
        self.definirCaminhoCD()

        self.situacaoAppsOk = []
        self.situacaoAppsFalha = []

        self.todosApps = sorted(os.listdir(Caminhos.todosAppsAndroid))
        self.novosApps = sorted(os.listdir(Caminhos.novosAppsAndroid))

    def makeApp(self, listaSelecionados, gerarSelecionados, publicar, caminho):
        self.situacaoAppsOk.clear()
        self.situacaoAppsFalha.clear()

        if caminho.__eq__(Caminhos.todosAppsAndroid):
            prefixo = self.prefixoAntigos
        else:
            prefixo = self.prefixoNovos

        listaAtual = []
        listaAtual = listaSelecionados

        qnt = 0
        print("Lista:")
        print(listaAtual)

        for app in listaAtual:
            if (not app.__eq__(".idea") and not app.__eq__(".gradle") and not app.__eq__(".DS_Store")):
                nome = app.replace(" ", "\\ ")
                pacote = self.relatorio.getpacote(caminho + app)

                qnt += 1
                print(caminho + nome + Caminhos.logo)
                self.notify.send(app, "App iniciado: " + nome,
                                 caminho+ nome.replace(" ", "\ ") + Caminhos.logo)
                self.appIniciado(app, qnt)
                self.processos(nome, prefixo, publicar, pacote=pacote)
                self.appTerminado(app, qnt)
                self.notify.send(app, "App terminado: " + nome,
                                 caminho + nome.replace(" ", "\ ") + Caminhos.logo)

        self.mostrarRelatorio()



    def gerarApkNovos(self, listaSelecionados, gerarSelecionados, publicar):

        self.situacaoAppsOk.clear()
        self.situacaoAppsFalha.clear()

        listaAtual = []
        lista = self.novosApps
        prefixo = self.prefixoNovos

        if gerarSelecionados:
            listaAtual = listaSelecionados
        else:
            listaAtual = lista

        qnt = 0

        for app in listaAtual:
            if (not app.__eq__(".idea") and not app.__eq__(".gradle") and not app.__eq__(".DS_Store")):
                nome = app.replace(" ", "\\ ")
                qnt += 1
                self.notify.send(app, "App iniciado: " + nome,
                                 Caminhos.novosAppsAndroidModificado + nome + Caminhos.logo)
                self.appIniciado(app, qnt)
                self.processos(nome, prefixo, publicar)
                self.appTerminado(app, qnt)
                self.notify.send(app, "App terminado: " + nome,
                                 Caminhos.novosAppsAndroidModificado + nome + Caminhos.logo)

        print(self.dataInicio)
        print(datetime.datetime.now())

        self.mostrarRelatorio()

    def processos(self, nome, prefixo, isPublicarLoja, pacote=None):
        print("---------- Processo ----------")
        comando1 = prefixo + nome + " ; " + self.tarefas[0]
        comando2 = prefixo + nome + " ; " + self.tarefas[1]

        if isPublicarLoja:
            comando3 = prefixo + nome + " ; " + self.tarefas[3] + " ; " + prefixo + nome + " ; " + self.tarefas[4]
        else:
            comando3 = prefixo + nome + " ; " + self.tarefas[2]

        retorno = subprocess.call(comando1 + " ; " + comando2 + " ; " + comando3, shell=True)
        print(retorno)
        print("Retorno")

        if retorno == 0:
            self.situacaoAppsOk.append(nome)
            # Google Sheet
            if (pacote != None):
                if (self.googleSheets.existeEstabelecimento(pacote=pacote)):
                    if isPublicarLoja:
                        self.googleSheets.alterarSheet(data=Util.getDataAtual(), tipo='Publicação', resultado='Sucesso',
                                                      pacote=pacote, local=prefixo+nome)
                    else:
                        self.googleSheets.alterarSheet(data=Util.getDataAtual(), tipo='Geração', resultado='Sucesso',
                                                      pacote=pacote,local=prefixo+nome)

                else:
                    if isPublicarLoja:
                        self.googleSheets.inserirEstabelecimento(nome, pacote, tipo="Publicação", resultado='Sucesso',
                                                                 data=Util.getDataAtual())
                    else:
                        self.googleSheets.inserirEstabelecimento(nome, pacote, tipo="Geração", resultado='Sucesso',
                                                                 data=Util.getDataAtual())


        else:
            self.situacaoAppsFalha.append(nome)
            # Google Sheet
            if (pacote != None):
                if (self.googleSheets.existeEstabelecimento(pacote=pacote)):
                    if isPublicarLoja:
                        self.googleSheets.alterarSheet(data=Util.getDataAtual(), tipo='Publicação', resultado='Falha',
                                                      pacote=pacote)
                    else:
                        self.googleSheets.alterarSheet(data=Util.getDataAtual(), tipo='Geração', resultado='Falha',
                                                      pacote=pacote)

                else:
                    if isPublicarLoja:
                        self.googleSheets.inserirEstabelecimento(nome, pacote, tipo="Publicação", resultado='Falha',
                                                                 data=Util.getDataAtual())
                    else:
                        self.googleSheets.inserirEstabelecimento(nome, pacote, tipo="Geração", resultado='Falha',
                                                                 data=Util.getDataAtual())

    def appIniciado(self, nome, qnt=0):
        print("\n\n--------------------- " + nome + " Iniciado ---------------------", qnt, "\n\n")

    def appTerminado(self, nome, qnt=0):
        print("\n\n--------------------- " + nome + " Terminado --------------------- ", qnt, "\n\n")

    def mostrarRelatorio(self):

        for success in self.situacaoAppsOk:
            self.tela.areaSucesso.insert("end", success.replace("\\", "") + "\n")
        for failure in self.situacaoAppsFalha:
            self.tela.areaFalha.insert("end", failure.replace("\\", "") + "\n")
Exemple #47
0
 def __init__(self, tela=None):
     self.tela = tela
     self.definirConstantes()
     self.notify = Notification()
 def __init__(self,caller,incoming_message):
     Notification.__init__(self,incoming_message)
     self.caller = caller
     self.notify()
Exemple #49
0
class Arquivo:
    def __init__(self, dados=None):
        self.caminhoNovos = Caminhos.novosAppsAndroid
        self.dados = dados
        self.pacotePendente = "br.com.appsexclusivos.pendente"
        self.notification = Notification()

    def atualizarLocalProperties(self):
        caminhos = []
        caminhos.append(Caminhos.todosAppsAndroid)
        caminhos.append(Caminhos.novosAppsAndroid)

        for caminho in caminhos:
            lista = os.listdir(caminho)

            for nomeProjeto in lista:
                if (not nomeProjeto.__eq__(".idea") and not nomeProjeto.__eq__(".gradle") and not nomeProjeto.__eq__(
                        ".DS_Store")):
                    properties = caminho + nomeProjeto + "/local.properties"
                    exist = os.path.exists(properties)
                    de = Caminhos.aplicativoBase + "local.properties"
                    destino = properties
                    print(nomeProjeto)

                    if (not exist):
                        shutil.copyfile(de, destino)

            self.notification.send("Local Properties Definido", "Atualização Finalizada")


    def getVersion(self, local):
        local = local.replace("cd ", "").replace("\\", "") + Caminhos.sufixoGradle
        existe = os.path.exists(local)
        self.pacote = None

        if existe:
            arquivo = open(local, 'r')
            conteudoAtual = arquivo.readlines()

            for a in conteudoAtual:
                linha = a

                if linha.__contains__("versionCode"):
                    self.code = [int(s) for s in linha.split() if s.isdigit()]
                elif linha.__contains__("applicationId"):
                    self.pacote = linha.replace("applicationId", "").replace("\"", "").replace(" ", "").replace("\\n",
                                                                                                                "").replace("\n", "")

            arquivo.close()
            return self.code[0], self.pacote


        else:
            return None, None

    def getName(self, localManifest):
        local = localManifest.replace("cd ", "").replace("\\", "") + Caminhos.sufixoManifest
        existe = os.path.exists(local)
        self.nomeApp = None

        if existe:
            arquivo = open(local, 'r')
            conteudoAtual = arquivo.readlines()

            for a in conteudoAtual:
                linha = a

                if linha.__contains__("android:label="):
                    self.nomeApp= linha.replace("android:label=", "") \
                        .replace("\n", "")\
                        .replace("\"", "")\
                        .replace("\t","")\
                        .replace("\'", "").strip()

            arquivo.close()

            return self.nomeApp

        else:
            return None


    def getAppName(self, localMainActivity):
        local = localMainActivity.replace("cd ", "").replace("\\", "")
        print(local)
        existe = os.path.exists(local)
        self.appName = None

        if existe:
            arquivo = open(local, 'r')
            conteudoAtual = arquivo.readlines()

            for a in conteudoAtual:
                linha = a

                if linha.__contains__("private String appNome"):
                    self.appName = linha.replace("private String appNome = ", "")\
                        .replace("\"", "") \
                        .replace("\'", "") \
                        .replace("\n", "") \
                        .replace(";","")\
                        .replace("private String appNome= ", "")\
                        .replace("private String appNome=", "")\
                        .replace("private String appNome=", "").strip()

            arquivo.close()
            return self.appName


        else:
            return None

    def atualizarVersionText(self, versionCode, local, versionName=None):
        local = local + Caminhos.sufixoGradle

        arquivo = open(local, 'r')
        conteudoAtual = arquivo.readlines()
        novoConteudo = []

        for a in conteudoAtual:
            linha = a

            if linha.__contains__("versionName"):
                if versionName is None:
                    linha = linha
                else:
                    linha = "\t\tversionName \"" + versionName + "\"\n"

            elif linha.__contains__("versionCode"):
                versionCodeAtual = linha.replace("versionCode", "") \
                    .replace(" ", "") \
                    .replace("\n", "") \
                    .replace("\t", "")


                #if (versionCode is None or versionCode.__eq__("") or versionCode.__eq__("AUTO_INCREMENT")) and versionCodeAtual.isdigit():
                if (versionCode is None and versionCodeAtual.isdigit())  or (versionCode.__str__().__eq__("") or versionCode.__str__().__eq__("AUTO_INCREMENT")) :
                    print("LAST VERSION CODE: ", versionCodeAtual)

                    versionCode = int(versionCodeAtual) + 1
                    print("UPGRADE VERSION CODE: ", versionCode)
                    linha = "\t\tversionCode " + versionCode.__str__() + "\n"
                else:
                    print("UPGRADE VERSION CODE: ", versionCode)
                    linha = "\t\tversionCode " + versionCode.__str__() + "\n"

            novoConteudo.append(linha)

        arquivo = open(local, 'w')
        arquivo.close()

        arquivo = open(local, 'w')
        arquivo.writelines(novoConteudo)

        arquivo.close()



    def baixarConteudo(self, conteudo, destino, apagar=True):
        if (apagar):
            os.remove(destino)

        try:
            wget.download(conteudo, destino)
        except:
            return True

        return False


    def stringXml(self, localString):
        localString = localString + Caminhos.sufixoStringsXml

        arquivo = open(localString, 'r')
        conteudoAtual = arquivo.readlines()
        novoConteudo = []

        for a in conteudoAtual:
            linha = a

            # if linha.__contains__("http://ws.appaguafacil.com.br/ClienteFiel/rest/"):
            if linha.__contains__("http://ws.appclientefiel.com.br/rest/"):
                linha = "\t<string name=\"urlws\">http://ws.appclientefiel.com.br/rest/</string>\n";

            elif linha.__contains__("http://pre.appclientefiel.com.br"):
                linha = "\t<!--<string name=\"urlws\">http://pre.appclientefiel.com.br/ClienteFiel/rest/</string>-->";

            elif linha.__contains__("http://52.86.148"):
                linha = "\t<!--<string name=\"urlws\">http://52.86.148.125:8080/ClienteFiel/rest/</string>-->";

            novoConteudo.append(linha)

        arquivo = open(localString, 'w')
        arquivo.close()

        arquivo = open(localString, 'w')
        arquivo.writelines(novoConteudo)

        arquivo.close()

    def arquivoFirebase(self, localFirebase, packageName, segundoArquivo=False):
        local = localFirebase + Caminhos.sufixoFirebaseIDService

        if segundoArquivo:
                local = localFirebase + Caminhos.sufixoFirebaseMessagingService

        arquivo = open(local, 'r')
        conteudoAtual = arquivo.readlines()
        novoConteudo = []

        for a in conteudoAtual:
            linha = a

            if linha.__contains__(self.pacotePendente):
                    linha = linha.replace(self.pacotePendente, packageName)

            novoConteudo.append(linha)

        arquivo = open(local, 'w')
        arquivo.close()

        arquivo = open(local, 'w')
        arquivo.writelines(novoConteudo)

        arquivo.close()
        if (not segundoArquivo):
            self.arquivoFirebase(localFirebase, packageName= packageName, segundoArquivo=True)

    def mainActivity(self, localMain, packageName,appNome):
        localMain = localMain + Caminhos.sufixoMainActivityCompleto

        arquivo = open(localMain, 'r')
        conteudoAtual = arquivo.readlines()
        novoConteudo = []

        for a in conteudoAtual:
            linha = a

            if linha.__contains__(self.pacotePendente):
                linha = linha.replace(self.pacotePendente, packageName)

            elif linha.__contains__("appNome ="):
                linha = "    " + "private String appNome = \"" + appNome + "\";";

            elif linha.__contains__("private boolean notificacaoFirebase"):
                linha = linha.replace("false", "true")

            novoConteudo.append(linha)

        arquivo = open(localMain, 'w')
        arquivo.close()

        arquivo = open(localMain, 'w')
        arquivo.writelines(novoConteudo)

        arquivo.close()

    def gradle(self, localGradle, packageName):
        localGradle = localGradle + Caminhos.sufixoGradle

        arquivo = open(localGradle, 'r')
        conteudoAtual = arquivo.readlines()
        novoConteudo = []

        for a in conteudoAtual:
            linha = a

            if linha.__contains__(self.pacotePendente):
                linha = linha.replace(self.pacotePendente, packageName)
            elif linha.__contains__("//apply plugin: 'com.google.gms.google-services'"):
                linha = linha.replace("//", "")

            novoConteudo.append(linha)

        arquivo = open(localGradle, 'w')
        arquivo.close()

        arquivo = open(localGradle, 'w')
        arquivo.writelines(novoConteudo)

        arquivo.close()

    def manifest(self, localManifest, nomeProjeto, packageName):
        localManifest = localManifest + Caminhos.sufixoManifest

        arquivo = open(localManifest, 'r')
        conteudoAtual = arquivo.readlines()
        novoConteudo = []

        for a in conteudoAtual:
            linha = a

            if linha.__contains__("android:label"):
                linha = "\t" + "android:label=\"" + nomeProjeto + "\"" + "\n"

            elif linha.__contains__(self.pacotePendente):
                linha = linha.replace(self.pacotePendente, packageName)

            novoConteudo.append(linha)

        arquivo = open(localManifest, 'w')
        arquivo.close()

        arquivo = open(localManifest, 'w')
        arquivo.writelines(novoConteudo)

        arquivo.close()

    def applicationContextIOS(self, local):
        local = local + "/NovoBase/ApplicationContext.swift"

        arquivo = open(local, 'r')
        conteudoAtual = arquivo.readlines()
        novoConteudo = []

        for a in conteudoAtual:
            linha = a

            if linha.__contains__("var nomeApp = "):
                linha = "\t" + "var nomeApp = \"" + self.dados.projectName + "\"" + "\n"

            elif linha.__contains__("var appNome = "):
                linha = "\t" + "var appNome = \"" + self.dados.appNome + "\"" + "\n"

            novoConteudo.append(linha)

        arquivo = open(local, 'w')
        arquivo.close()

        arquivo = open(local, 'w')
        arquivo.writelines(novoConteudo)

        arquivo.close()

    def infoPlistIOS(self, local):
        local = local + "/NovoBase/Info.plist"

        arquivo = open(local, 'r')
        conteudoAtual = arquivo.readlines()
        novoConteudo = []

        for a in conteudoAtual:
            linha = a

            if linha.__contains__("<string>br.com"):
                linha = "\t\t\t" + "<string>" + self.dados.packageName + "</string>" + "\n"

            elif linha.__contains__("<string>Sua Marca Delivery"):
                linha = "\t" + "<string>" + self.dados.projectName + "</string>" + "\n"

            novoConteudo.append(linha)

        arquivo = open(local, 'w')
        arquivo.close()

        arquivo = open(local, 'w')
        arquivo.writelines(novoConteudo)

        arquivo.close()

    def getNameMainActivity(self, localMain):

        arquivo = open(localMain, 'r')
        conteudoAtual = arquivo.readlines()
        novoConteudo = []

        for a in conteudoAtual:
            linha = a

            if linha.__contains__("private String appNome"):
                linha = linha.replace("private String appNome", "") \
                    .replace("\"", "") \
                    .replace("\n", "") \
                    .replace("\\n", "") \
                    .replace(" ", "") \
                    .replace("=", "") \
                    .replace(";", "") \
                    .replace("\t", "")
                arquivo.close()
                return linha

        arquivo.close()
        return None

    def manifestMetadados(self, localManifest):
        localManifest = localManifest + "/pendente/src/main/AndroidManifest.xml"

        arquivo = open(localManifest, 'r')
        conteudoAtual = arquivo.readlines()
        novoConteudo = []

        for a in conteudoAtual:
            linha = a

            if linha.__contains__("android:label"):
                linha = "\t" + "android:label=\"" + self.dados.projectName + "\"" + "\n"

            novoConteudo.append(linha)

        arquivo = open(localManifest, 'w')
        arquivo.close()

        arquivo = open(localManifest, 'w')
        arquivo.writelines(novoConteudo)

        arquivo.close()

    def atualizarDadosAppConfig(self, local, aplicativoDados):
        local = local + "/AppConfig.txt"

        arquivo = open(local, 'r')
        conteudoAtual = arquivo.readlines()
        novoConteudo = []

        for a in conteudoAtual:
            linha = a

            if linha.__contains__("NomeApp"):
                name = linha.split("=", 1)[1]
                novoValor = aplicativoDados.projectName
                linha = linha.replace(name.__str__(), novoValor.__str__())
                linha += "\n"  # necessário
                print(linha)

            novoConteudo.append(linha)

        arquivo = open(local, 'w')
        arquivo.close()

        arquivo = open(local, 'w')
        arquivo.writelines(novoConteudo)

        arquivo.close()

    def atualizarAppConfig(self,local):
        local = local + "/AppConfig.txt"

        arquivo = open(local, 'r')
        conteudoAtual = arquivo.readlines()
        novoConteudo = []

        for a in conteudoAtual:
            linha = a

            if linha.__contains__("VersionCode"):
                code = linha.split("=", 1)[1]
                novoValor = int(code)+1
                linha = linha.replace(code.__str__(), novoValor.__str__())
                linha += "\n" #necessário
                print(linha)

            novoConteudo.append(linha)

        arquivo = open(local, 'w')
        arquivo.close()

        arquivo = open(local, 'w')
        arquivo.writelines(novoConteudo)

        arquivo.close()

    def alteradorEmergencial(self):
        caminho = Caminhos.caminhoTeste
        lista = os.listdir(caminho)

        print(caminho)

        for p in lista:
            if (not p.__eq__(".DS_Store") and not p.__eq__(".idea")):
                localString = caminho + "/" + p + "/AppConfig.txt"

                arquivo = open(localString, 'r')
                conteudoAtual = arquivo.readlines()
                novoConteudo = []

                for a in conteudoAtual:
                    linha = a

                    if linha.__contains__("VersioCode"):
                        linha = linha.replace("VersioCode", "VersionCode")

                    novoConteudo.append(linha)

                arquivo = open(localString, 'w')
                arquivo.close()

                arquivo = open(localString, 'w')
                arquivo.writelines(novoConteudo)

                arquivo.close()

    def alteracaoEmergencial(self):
        caminho = Caminhos.novosAppsAndroid
        lista = os.listdir(caminho)

        for p in lista:
            if (not p.__eq__(".DS_Store") and not p.__eq__(".idea")):
                caminhoCompleto = caminho + p
                caminhoPastaNova = caminhoCompleto

                if(not os.path.exists(caminhoPastaNova)):
                    os.mkdir(caminhoPastaNova)

                versao, pacote = self.getVersion(caminhoCompleto)

                name = self.getName(caminhoCompleto)

                caminho1 = caminhoCompleto+"/pendente/src/main/java/br/com/"
                list = os.listdir(caminho1)
                caminho2 = caminho1 + list[0] + "/"


                try:
                    list = os.listdir(caminho2)
                    caminho3 = caminho2 + list[0]
                    if(os.path.isfile(caminho3)):
                        #caminho2
                        pass
                    else:
                        caminho2 = caminho3
                except:
                    pass

                appName = self.getAppName(caminho2 + "/MainActivity.java" )

                print(versao)
                print(pacote)
                print(name)
                print(appName)
                print("-----------------------")
                print("-----------------------")

                nome_do_arquivo = caminhoPastaNova + "/AppConfig.txt"

                texto = []
                texto.append("NomeApp=" + name)
                texto.append("\n")
                texto.append("VersionName=Versão Beta 3.0 PG")
                texto.append("\n")
                texto.append("VersionCode=" + versao.__str__())
                texto.append("\n")
                texto.append("PackageName=" + pacote)
                texto.append("\n")
                texto.append("AppName=" + appName)
                texto.append("\n")

                arquivo = open(nome_do_arquivo, 'w+')
                arquivo.writelines(texto)
                arquivo.close()

                shutil.copy(caminhoCompleto + Caminhos.logo,caminhoPastaNova + "/logo.png")
                shutil.copy(caminhoCompleto + Caminhos.sufixoGoogleService, caminhoPastaNova + "/google-services.json")
class MainController(NSObject):
    
    outputArea = objc.IBOutlet("outputArea")
    
    lblTimeLeft = objc.IBOutlet("lblTimeLeft")

    lblTimeSpentCurr = objc.IBOutlet("lblTimeSpentCurr")

    cbxInput = objc.IBOutlet("cbxInput")

    lblSlackingTime = objc.IBOutlet("lblSlackingTime")

    lblTimeSpent = objc.IBOutlet("lblTimeSpent")

    lblWorkTill = objc.IBOutlet("lblWorkTill")
    
    pbtnProject = objc.IBOutlet("pbtnProject")
    
    pbtnProject = objc.IBOutlet("pbtnProject")
    
    workTillBox = objc.IBOutlet("workTillBox")
    
    mainWindow = objc.IBOutlet("mainWindow")

    prefWindow = objc.IBOutlet("prefWindow")

    reportWindow = objc.IBOutlet("reportWindow")
    
    reportController = objc.IBOutlet("reportController")
    
    applicationRef = objc.IBOutlet("applicationRef")
    
    btnDone = objc.IBOutlet("btnDone")
    
    tasks = None
    
    def awakeFromNib(self):
        def onGrowlClick():
            self.applicationRef.unhide()
            self.cbxInput.becomeFirstResponder()
            
        self.notification = Notification(onGrowlClick)
        self.initControls()
        self.initWindowStates()
        self.readCounters()
        self._timer = NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(Settings.get("timerInterval"), 
                              self, self.timerFunction, None, True)
                              
    def initControls(self):
        """Init basic controls"""
        self.outputArea.setString_("")
        
        self.tasks = Tasks()
        
        if Settings.get("showWorkTill"):
            self.workTillBox.setHidden_(False)
        else:
            self.workTillBox.setHidden_(True)
            
        self.pbtnProject.removeAllItems()
        self.pbtnProject.addItemsWithTitles_(Projects.get())
        self.pbtnProject.selectItemWithTitle_(Settings.get("selectedProject"))
        
        self.projectChange_(None)
        
        self.initDoneButton()
        
        self.fillTasks()
        self.scrollToEnd()
        
    def initDoneButton(self):
        if self.tasks.dayStarted():
            self.btnDone.setTitle_("Done")
        else:
            self.btnDone.setTitle_("Start")
        
    def initWindowStates(self):
        """Init windows sizes and positions"""
        self.prefWindow.setFrameAutosaveName_("prefWindow")
        self.mainWindow.setFrameAutosaveName_("mainWindow")
        self.reportWindow.setFrameAutosaveName_("reportWindow")
                  
    def timerFunction(self):
        """Timer callback function"""
        self.tasks.setCurrentTask(self.cbxInput.stringValue())
        self.readCounters()
        
        self.notification.idleNotify(self.tasks.timings.currentSeconds)
        
        if self.tasks.timings.isNextDay():
            self.initControls()
        
    def readCounters(self):
        """Read counters"""
        self.lblTimeSpent.setStringValue_(fh.secToTimeStr(self.tasks.timings.spentSeconds))
        self.lblSlackingTime.setStringValue_(fh.secToTimeStr(self.tasks.timings.slackingSeconds))
        self.lblTimeLeft.setStringValue_(fh.secToTimeStr(self.tasks.timings.leftSeconds))
        self.lblTimeSpentCurr.setStringValue_(fh.secToTimeStr(self.tasks.timings.currentSeconds))
        self.lblWorkTill.setStringValue_(fh.timeStructToTimeStr(self.tasks.timings.workTillTime))

    def appendTask(self, taskString, color):
        def appendText(text, color=None):
            """Append text to task text area"""
            endRange = NSRange()
            endRange.location = self.outputArea.textStorage().length()
            endRange.length = 0
            self.outputArea.replaceCharactersInRange_withString_(endRange, text)
            if color:
                colorRange = NSRange()
                colorRange.location = self.outputArea.textStorage().length() - len(text) 
                colorRange.length = len(text)
                self.outputArea.setTextColor_range_(color, colorRange)
        appendText(taskString, color)
        
        if self.reportWindow.isVisible():
            self.reportController.generateChart()
            
    def fillTasks(self):
        """Fill text area with tasks"""
        for task in self.tasks.taskList:
            self.appendTask(*fh.formatTaskString(*task))
            
    def scrollToEnd(self):
        """Scroll tasks textarea to the end"""
        self.outputArea.scrollRangeToVisible_(NSMakeRange(self.outputArea.string().length(), 0))

    def showStartHelpMessage(self):
        """Show alert with help message"""
        alert = NSAlert.alloc().init()
        alert.addButtonWithTitle_('OK')
        alert.setMessageText_("Congrats, you started your working day!")
        alert.setInformativeText_("Now start doing your working activity (e.g reading mail). "
                                  "When you finish with your activity go back to MacTimeLog and type it in. "
                                  "If your activity is slacking, use 2 asterisks (**) at the end of the activity's name.")
        alert.setShowsSuppressionButton_(True)
        alert.runModal()
        if alert.suppressionButton().state() == NSOnState:
            Settings.set("showHelpMessageOnStart", False)
            Settings.sync()

    @objc.IBAction
    def btnDonePress_(self, sender):
        """On done button press"""
        if self.tasks.dayStarted():
            if self.cbxInput.stringValue().strip():
                taskName = self.cbxInput.stringValue()
                self.appendTask(*fh.formatTaskString(*self.tasks.add(taskName, self.pbtnProject.titleOfSelectedItem())))
                self.readCounters()
                self.cbxInput.setStringValue_("")
                self.scrollToEnd()
            
                if  Tasks.taskType(taskName) == "work":
                    Projects.addAutocomplete(self.pbtnProject.titleOfSelectedItem(), taskName)
                else:
                    SlackingAutocompletes.add(taskName)
                self.cbxInput.addItemWithObjectValue_(taskName)
        else:
            if Settings.get("showHelpMessageOnStart"):
                self.showStartHelpMessage()
            taskName = Settings.get("startPlaceholder")
            self.appendTask(*fh.formatTaskString(*self.tasks.add(taskName)))
            self.initDoneButton()

    @objc.IBAction
    def projectChange_(self, sender):
        """Project changed event"""
        if self.pbtnProject.titleOfSelectedItem():
            self.cbxInput.removeAllItems()
            self.cbxInput.addItemsWithObjectValues_(Projects.getAutocomleteList(
                                    self.pbtnProject.titleOfSelectedItem(), SlackingAutocompletes.get()))

        if sender:
            Settings.set("selectedProject", unicode(self.pbtnProject.titleOfSelectedItem()))
        Settings.sync()
        
    @objc.IBAction
    def openLog_(self, sender):
        """ Open log in text editor"""
        os.system(Settings.get("logEditCommand") % Settings.get("logPath"))
        
Exemple #51
0
 def __init__(self, dados=None):
     self.caminhoNovos = Caminhos.novosAppsAndroid
     self.dados = dados
     self.pacotePendente = "br.com.appsexclusivos.pendente"
     self.notification = Notification()
Exemple #52
0
class JosephPy:
    def criarInstancias(self, tela):
        self.notify = Notification()
        self.googleSheets = GoogleSheets()
        self.relatorio = Relatorio()
        self.descompactar = Descompactar()
        self.email = Email()
        self.areaTeste = AreaTestes()

        self.tela = tela


    def definirConstantes(self):

        assinatura = "./gradlew assembleRelease "
        assinatura += "-Pandroid.injected.signing.store.file=" + Caminhos.keystore + " "
        assinatura += "-Pandroid.injected.signing.store.password=gtlgtlgtl "
        assinatura += "-Pandroid.injected.signing.key.alias=guilherme.vasconcelos "
        assinatura += "-Pandroid.injected.signing.key.password=gtlgtlgtl"

        build = "./gradlew build"
        task = "./gradlew task"
        clean = "./gradlew clean"
        publicar = "./gradlew publishApkRelease"

        self.tarefas = [task, build, assinatura, clean, publicar]
        self.dataInicio = datetime.datetime.now()

    def definirCaminhoCD(self):
        self.aplicativoBase = "cd " + Caminhos.aplicativoBaseNucleo
        self.prefixoAntigos = "cd " + Caminhos.todosAppsAndroidModificado
        self.prefixoNovos = "cd " + Caminhos.novosAppsAndroidModificado

    def __init__(self, tela=None):

        self.criarInstancias(tela)
        self.definirConstantes()
        self.definirCaminhoCD()

        self.situacaoAppsOk = []
        self.situacaoAppsFalha = []

        self.todosApps = sorted(os.listdir(Caminhos.todosAppsAndroid))
        self.novosApps = sorted(os.listdir(Caminhos.novosAppsAndroid))

    def makeApp(self, listaSelecionados, gerarSelecionados, publicar, caminho, emails=None):



        self.situacaoAppsOk.clear()
        self.situacaoAppsFalha.clear()

        if caminho.__eq__(Caminhos.todosAppsAndroid):
            prefixo = self.prefixoAntigos
        else:
            prefixo = self.prefixoNovos

        listaAtual = []
        listaAtual = listaSelecionados

        qnt = 0
        print("Apps a Serem Gerados:")
        print(listaAtual)

        for app in listaAtual:
            if (not app.__eq__(".idea") and not app.__eq__(".gradle") and not app.__eq__(".DS_Store")):
                nome = app.replace(" ", "\\ ")
                #pacote = self.relatorio.getpacote(caminho + app)

                # Antes de tudo criar o projeto
                self.areaTeste.iniciar(caminho=caminho + app)

                qnt += 1
                print(caminho + nome + Caminhos.logo)
                self.notify.send(app, "App iniciado: " + nome,
                                 caminho + nome.replace(" ", "\ ") + "logo.png")
                self.appIniciado(app, qnt)
                self.processos(nome, prefixo, publicar)
                self.appTerminado(app, qnt)
                self.notify.send(app, "App terminado: " + nome,
                                 caminho + nome.replace(" ", "\ ") + "logo.png")

        self.mostrarRelatorio()

        if not publicar:
            self.descompactar.compactar(Caminhos.caminhoApksGerados + Util.getDataAtual().replace("/", "."),
                                        enviarEmail=True,emails=emails)

    def gerarApkNovos(self, listaSelecionados, gerarSelecionados, publicar, emails=None):

        self.situacaoAppsOk.clear()
        self.situacaoAppsFalha.clear()

        listaAtual = []
        lista = self.novosApps
        prefixo = self.prefixoNovos

        if gerarSelecionados:
            listaAtual = listaSelecionados
        else:
            listaAtual = lista

        qnt = 0

        for app in listaAtual:
            if (not app.__eq__(".idea") and not app.__eq__(".gradle") and not app.__eq__(".DS_Store")):
                # pacote = self.relatorio.getpacote(caminho + app)

                # Antes de tudo criar o projeto
                self.areaTeste.iniciar(caminho=Caminhos.novosAppsAndroid + app)

                nome = app.replace(" ", "\\ ")
                qnt += 1
                self.notify.send(app, "App iniciado: " + nome,
                                 Caminhos.novosAppsAndroidModificado + nome + Caminhos.logo)
                self.appIniciado(app, qnt)
                self.processos(nome, prefixo, publicar)
                self.appTerminado(app, qnt)
                self.notify.send(app, "App terminado: " + nome,
                                 Caminhos.novosAppsAndroidModificado + nome + Caminhos.logo)

        print(self.dataInicio)
        print(datetime.datetime.now())

        self.mostrarRelatorio()

        if not publicar:
            self.descompactar.compactar(Caminhos.caminhoApksGerados + Util.getDataAtual().replace("/", "."),
                                        enviarEmail=True,emails=emails)

    def processos(self, nome, prefixo, isPublicarLoja, pacote=None):
        print("---------- Processo ----------")
        pastaProjeto = "/AppTemp"
        comando1 = prefixo + nome + pastaProjeto + " ; " + self.tarefas[0]
        comando2 = prefixo + nome + pastaProjeto +" ; " + self.tarefas[1]

        if isPublicarLoja:
            comando3 = prefixo + nome + pastaProjeto + " ; " + self.tarefas[3] + " ; " + prefixo + nome + pastaProjeto + " ; " + self.tarefas[4]
        else:
            comando3 = prefixo + nome + pastaProjeto + " ; " + self.tarefas[2]


        retorno = subprocess.call(comando1 + " ; " + comando2 + " ; " + comando3, shell=True)

        print("Retorno: " + retorno.__str__())


        if retorno == 0:
            self.situacaoAppsOk.append(nome)
            # Google Sheet
            if (not isPublicarLoja):

                prefixo = prefixo.replace("cd ", "").replace("\\", "")
                nome = nome.replace("\\", "")
                pasta =  prefixo + nome + "/AppTemp" + Caminhos.sufixoReleaseApk
                print(pasta)

                dataAtual = Util.getDataAtual().replace("/", ".")

                if (os.path.exists(pasta)):
                    caminho = Caminhos.caminhoApksGerados + dataAtual + "/"

                    if (not os.path.exists(caminho)):
                        os.mkdir(caminho)

                    try:
                        shutil.copy2(pasta, Caminhos.caminhoApksGerados + dataAtual + "/" + nome + ".apk")
                        shutil.rmtree(prefixo+nome+pastaProjeto)

                    except:
                        pass

                    print("Apps Copiado para pasta ApksGerados")

                else:
                    print("Falha ao mover app para pasta ApksGerados")

            if (pacote != None):
                if (self.googleSheets.existeEstabelecimento(pacote=pacote)):
                    if isPublicarLoja:
                        self.googleSheets.alterarSheet(data=Util.getDataAtual(), tipo='Publicação', resultado='Sucesso',
                                                       pacote=pacote, local=prefixo + nome)
                    else:
                        self.googleSheets.alterarSheet(data=Util.getDataAtual(), tipo='Geração', resultado='Sucesso',
                                                       pacote=pacote, local=prefixo + nome)

                else:
                    if isPublicarLoja:
                        self.googleSheets.inserirEstabelecimento(nome, pacote, tipo="Publicação", resultado='Sucesso',
                                                                 data=Util.getDataAtual())
                    else:
                        self.googleSheets.inserirEstabelecimento(nome, pacote, tipo="Geração", resultado='Sucesso',
                                                                 data=Util.getDataAtual())


        else:
            self.situacaoAppsFalha.append(nome)
            # Google Sheet
            if (pacote != None):
                if (self.googleSheets.existeEstabelecimento(pacote=pacote)):
                    if isPublicarLoja:
                        self.googleSheets.alterarSheet(data=Util.getDataAtual(), tipo='Publicação', resultado='Falha',
                                                       pacote=pacote)
                    else:
                        self.googleSheets.alterarSheet(data=Util.getDataAtual(), tipo='Geração', resultado='Falha',
                                                       pacote=pacote)

                else:
                    if isPublicarLoja:
                        self.googleSheets.inserirEstabelecimento(nome, pacote, tipo="Publicação", resultado='Falha',
                                                                 data=Util.getDataAtual())
                    else:
                        self.googleSheets.inserirEstabelecimento(nome, pacote, tipo="Geração", resultado='Falha',
                                                                 data=Util.getDataAtual())

    def appIniciado(self, nome, qnt=0):
        print("\n\n--------------------- " + nome + " Iniciado ---------------------", qnt, "\n\n")

    def appTerminado(self, nome, qnt=0):
        print("\n\n--------------------- " + nome + " Terminado --------------------- ", qnt, "\n\n")

    def mostrarRelatorio(self):

        for success in self.situacaoAppsOk:
            self.tela.areaSucesso.insert("end", success.replace("\\", "") + "\n")
        for failure in self.situacaoAppsFalha:
            self.tela.areaFalha.insert("end", failure.replace("\\", "") + "\n")
Exemple #53
0
class Tela:


    def __init__(self, master=None, abrirTela=True):

        if master != None:
            if abrirTela:
                self.definirConstantes(master)
                self.criarInstancias()

                self.mainPrincipal()
                self.containerTelaPublicadorAtualizador()
                self.criarTelaResultados()
                self.containerTelaGeradorAplicativos(master)
                # self.construcaoTela(master)

    def definirConstantes(self, master):
        self.ANDROID = "android"
        self.IOS = "IOS"

        self.notify = Notification()

        self.caminhoTodosApps = Caminhos.todosAppsAndroid
        self.caminhoNovosApps = Caminhos.novosAppsAndroid

        self.caminhoTodosAppsIOS = Caminhos.todosAppsIOS
        self.caminhoNovosAppsIOS = Caminhos.novosAppsIOS

        self.caminhoTodasImagens = Caminhos.origemImagens
        self.caminhoNovasImagens = Caminhos.todasImagens

        self.caminhoSelecionado = ""
        self.caminhoSelecionadoImagens = ""

        self.isGerarSelecionados = 1
        self.isPublicarLoja = 0
        self.isGerarApk = 1
        self.isAtualizarAntes = 0

        self.lista = []
        self.master = master

    def mainPrincipal(self):
        self.framePrincipal = Frame(self.master)
        self.framePrincipal["width"] = self.width*100
        self.framePrincipal["height"] = self.height*100
        self.framePrincipal.pack()


    def containerTelaPublicadorAtualizador(self):
        self.tela_publicador_atualizador = LabelFrame(self.framePrincipal, text="Publicador/Atualizador", padx=5,
                                                      pady=5)
        self.tela_publicador_atualizador.pack(padx=10, pady=10)
        #self.tela_publicador_atualizador.place(bordermode=OUTSIDE, height=560, width=510, x=5, y=30)
        self.tela_publicador_atualizador.place(bordermode=OUTSIDE, height=self.height*100, width=self.width*49.5, x=self.width*0.5  , y=0)

        textoSelecione = Label(self.tela_publicador_atualizador)
        textoSelecione["text"] = "Selecione:"
        textoSelecione.pack()
        textoSelecione.place(bordermode=OUTSIDE, height=25, x=10, y=20)

        self.listBoxProjetos = Listbox(self.tela_publicador_atualizador, name="caminhoPasta", )
        self.listBoxProjetos["selectmode"] = SINGLE
        self.listBoxProjetos.insert(0, "AND - Todos os Aplicativos")
        self.listBoxProjetos.insert(1, "AND - Novos Aplicativos")

        # la
        self.sistema = platform.system().lower()
        if self.sistema != 'linux' and self.sistema != 'windows':
            self.listBoxProjetos.insert(2, "IOS - Todos os Aplicativos")
            self.listBoxProjetos.insert(3, "IOS - Novos Aplicativos")

            self.listBoxProjetos.insert(4, "AND - TESTE")
            self.listBoxProjetos.insert(5, "IOS - TESTE")
        else:
            self.listBoxProjetos.insert(2, "AND - TESTE")
            pass

        self.listBoxProjetos.bind('<<ListboxSelect>>', self.getListBoxProjetos)
        self.listBoxProjetos.setvar(name="asd1")
        self.listBoxProjetos.pack()
        self.listBoxProjetos.place(bordermode=OUTSIDE, height=120, width=220, x=15, y=self.height*6.5)

        self.listBoxApps = Listbox(self.tela_publicador_atualizador, name="apps")
        self.listBoxApps["selectmode"] = EXTENDED
        self.listBoxApps.bind('<<ListboxSelect>>', self.getListBoxApps)
        self.listBoxApps.setvar(name="dsa2")
        self.listBoxApps.pack()
        self.listBoxApps.place(bordermode=OUTSIDE, height=self.height*90, width=self.width*24.5, x=self.width*24.0, y=self.height*6.5)

        self.isSelecionados = IntVar()
        self.checkBox = Checkbutton(self.tela_publicador_atualizador, text="Gerar Apps Selecionados",
                                    command=self.checkBox,
                                    variable=self.isSelecionados)
        self.checkBox.select()
        self.checkBox.place(bordermode=OUTSIDE, height=25, x=250, y=20)

        self.txtQntidadeApps = Label(self.tela_publicador_atualizador, fg="blue")
        self.txtQntidadeApps.pack()
        self.txtQntidadeApps.place(bordermode=OUTSIDE, height=25, x=250, y=self.height*96.5)

        self.var2 = IntVar()
        self.checkBox2 = Checkbutton(self.tela_publicador_atualizador, text="Publicar Apps na loja",
                                     command=self.checkBox2,
                                     variable=self.var2)
        self.checkBox2.place(bordermode=OUTSIDE, height=25, x=15, y=170)

        self.var3 = IntVar()
        self.checkBox3 = Checkbutton(self.tela_publicador_atualizador, text="Gerar Apk", command=self.checkBox3,
                                     variable=self.var3)
        self.checkBox3.select()
        self.checkBox3.place(bordermode=OUTSIDE, height=25, x=15, y=190)

        self.var4 = IntVar()
        self.checkBox4 = Checkbutton(self.tela_publicador_atualizador, text="Atualizar Antes de Enviar",
                                     command=self.checkBox4,
                                     variable=self.var4)
        # self.checkBox4.select()
        self.checkBox4.place(bordermode=OUTSIDE, height=25, x=15, y=210)

        self.var5 = IntVar()
        self.checkBox5 = Checkbutton(self.tela_publicador_atualizador, text="Enviar Email",
                                     command=self.checkBox5,
                                     variable=self.var5)
        self.checkBox5.select()
        self.checkBox5.place(bordermode=OUTSIDE, height=25, x=15, y=260)

        abaixar = 200

        self.version_variable = StringVar()
        self.email_variable = StringVar()

        self.txtVersion = Entry(self.tela_publicador_atualizador, textvariable=self.version_variable)
        self.txtVersion.insert(END, "8.0 RELEASE")
        self.txtVersion['state'] = 'disabled'
        self.txtVersion["width"] = 25
        self.txtVersion.pack()
        self.txtVersion.place(bordermode=OUTSIDE, height=25, width=220, x=15, y=235)

        self.txtEmail = Entry(self.tela_publicador_atualizador, textvariable=self.email_variable)
        self.txtEmail.insert(END, "")
        self.txtEmail['state'] = 'normal'
        self.txtEmail["width"] = 25
        self.txtEmail.pack()
        self.txtEmail.place(bordermode=OUTSIDE, height=25, width=220, x=15, y=285)

        botaoGerarApps = Button(self.tela_publicador_atualizador)
        botaoGerarApps["text"] = "Gerar/Publicar Apps"
        botaoGerarApps["command"] = lambda: self.gerarAppsApoio()
        botaoGerarApps["width"] = 25
        botaoGerarApps.pack()
        botaoGerarApps.place(bordermode=OUTSIDE, height=25, width=220, x=15, y=230 + abaixar)

        self.botaoAtualizarApps = Button(self.tela_publicador_atualizador)
        self.botaoAtualizarApps["text"] = "Atualizar Núcleo"
        self.botaoAtualizarApps.pack()
        self.botaoAtualizarApps.place(bordermode=OUTSIDE, height=25, width=220, x=15, y=260 + abaixar)

        botaoAdaptarAoSistema = Button(self.tela_publicador_atualizador)
        botaoAdaptarAoSistema["text"] = "------------"
        botaoAdaptarAoSistema["command"] = lambda: self.adaptarProjeto()
        botaoAdaptarAoSistema.pack()
        botaoAdaptarAoSistema.place(bordermode=OUTSIDE, height=25, width=220, x=15, y=290 + abaixar)

        botaoAtualizarMetadados = Button(self.tela_publicador_atualizador)
        botaoAtualizarMetadados["text"] = "Atualizar Metadados"
        botaoAtualizarMetadados["command"] = lambda: self.atualizarMetadados()
        botaoAtualizarMetadados.pack()
        botaoAtualizarMetadados.place(bordermode=OUTSIDE, height=25, width=220, x=15, y=320 + abaixar)

    def containerTelaGeradorAplicativos(self, master=None):
        self.tela_gerador_aplicativos = LabelFrame(self.framePrincipal, text="Gerador de Aplicativos", padx=5, pady=5)
        self.tela_gerador_aplicativos.pack(padx=10, pady=10)
        #self.tela_gerador_aplicativos.place(bordermode=OUTSIDE, height=280, width=510, x=550, y=30)
        self.tela_gerador_aplicativos.place(bordermode=OUTSIDE, height=self.height*45, width=self.width*47.5, x= self.width*52, y=0)

        textoAppName = Label(self.tela_gerador_aplicativos)
        textoAppName["text"] = "App Name:"
        textoAppName.pack()
        textoAppName.place(bordermode=INSIDE, height=25, x=10, y=15)

        self.areaAppName = Text(self.tela_gerador_aplicativos, height=2, width=30)
        self.areaAppName.insert(END, "")
        self.areaAppName.place(bordermode=OUTSIDE, height=200, width=200, x=10, y=40)

        self.variavel_multiplataforma = IntVar()
        self.multiPlataforma = Checkbutton(self.tela_gerador_aplicativos, text="Gerar Multiplataforma",
                                           command=self.gerarApenasMultiplataforma,
                                           variable=self.variavel_multiplataforma)
        self.multiPlataforma.place(bordermode=OUTSIDE, height=25, x=220, y=40)

        self.variavel_android_apenas = IntVar()
        self.apenas_android = Checkbutton(self.tela_gerador_aplicativos, text="Gerar Apenas Android",
                                          command=self.gerarApenasAndroid,
                                          variable=self.variavel_android_apenas)
        self.apenas_android.place(bordermode=OUTSIDE, height=25, x=220, y=65)

        self.variavel_ios_apenas = IntVar()
        self.apenas_ios = Checkbutton(self.tela_gerador_aplicativos, text="Gerar Apenas IOS",
                                      command=self.gerarApenasIos,
                                      variable=self.variavel_ios_apenas)
        self.apenas_ios.place(bordermode=OUTSIDE, height=25, x=220, y=90)

        sistema = platform.system().lower()
        if sistema == 'linux' or sistema == 'windows':
            self.apenas_android.select()
        else:
            self.apenas_android.select()
            #self.multiPlataforma.select()

        botaoCriarAplicativo = Button(self.tela_gerador_aplicativos)
        botaoCriarAplicativo["text"] = "Criar Aplicativo(s)"
        botaoCriarAplicativo["command"] = lambda: self.criarApps()
        botaoCriarAplicativo.pack()
        botaoCriarAplicativo.place(bordermode=OUTSIDE, height=25, width=220, x=220, y=130)

        self.progressbar = ttk.Progressbar(self.tela_gerador_aplicativos, maximum=100, mode="indeterminate")
        self.progressbar.step(0)
        # self.progressbar.place(width=200, x=10, y=225)

    def criarInstancias(self):
        self.core = Core()
        self.projeto = Projeto(tela=self)
        self.joseph = JosephPy(tela=self)
        self.arquivo = Arquivo()

        self.width, self.height = Util.getScreenSize()
        self.width = self.width/100
        self.height = (self.height- 6*(self.height/100))/100


    def atualizarMetadados(self):
        self.notify.send("Iniciando Atualização", "")
        self.core.atualizarDados(self.caminhoSelecionado, self.lista, self.isSelecionados)
        self.notify.send("Atualização Finalizada", "")

    def adaptarProjeto(self):
        self.arquivo.atualizarLocalProperties()

    def criarTelaResultados(self):

        self.tela_resultados = LabelFrame(self.framePrincipal, text="Área de Resultados", padx=5, pady=5)
        self.tela_resultados.pack(padx=10, pady=10)
        #self.tela_resultados.place(bordermode=OUTSIDE, height=280, width=640, x=550, y=320)
        self.tela_resultados.place(bordermode=OUTSIDE, height=self.height*50, width=self.width*47.5, x=self.width*52, y=self.height*48.5)

        textoResultado = Label(self.tela_resultados)
        textoResultado["text"] = "Resultado:"

        textoSucesso = Label(self.tela_resultados)
        textoSucesso["text"] = "Sucesso:"
        textoSucesso.pack()
        textoSucesso.place(bordermode=OUTSIDE, height=25, x=10, y=15)

        self.areaSucesso = Text(self.tela_resultados, height=2, width=30, fg='black')
        self.areaSucesso.insert(END, "")
        self.areaSucesso.place(bordermode=OUTSIDE, height=220, width=200, x=10, y=40)

        textoFalha = Label(self.tela_resultados)
        textoFalha["text"] = "Falha:"
        textoFalha.pack()
        textoFalha.place(bordermode=OUTSIDE, height=25, x=220, y=15)

        self.areaFalha = Text(self.tela_resultados, height=2, width=30, fg='black')
        self.areaFalha.insert(END, "")
        self.areaFalha.place(bordermode=OUTSIDE, height=220, width=200, x=220, y=40)

        botaoLimpar = Button(self.tela_resultados)
        botaoLimpar["text"] = "Limpar Resultados"
        botaoLimpar["command"] = lambda: self.limpaCampos()
        botaoLimpar.pack()
        botaoLimpar.place(bordermode=OUTSIDE, height=25, width=170, x=430, y=40)

        informacaoApps = Button(self.tela_resultados)
        informacaoApps["text"] = "Dados dos Apps"
        informacaoApps["command"] = lambda: self.verInformacaoApps()
        informacaoApps.pack()
        informacaoApps.place(bordermode=OUTSIDE, height=25, width=170, x=430, y=65)

        self.progressbarGerar2 = ttk.Progressbar(self.tela_resultados, maximum=10, mode="indeterminate")
        self.progressbarGerar2.place(width=160, x=430, y=220)

    def limpaCampos(self):
        self.areaSucesso.delete("1.0", "end-1c")
        self.areaFalha.delete("1.0", "end-1c")

    def result(self, ok, erros):
        pass

    def popUp(self, plataforma="android", semPopup=False):
        self.toplevel = Toplevel(width=200, height=200, padx=100)
        self.toplevel.title("Confirmação")
        self.toplevel.attributes('-topmost', 'true')
        self.toplevel.grab_set()
        self.toplevel.geometry('300x200+400+200')

        self.atualizar = Button(self.toplevel)  # Botão Atualizar
        self.atualizar["command"] = lambda: self.atualizarCore(plataforma)
        self.atualizar.pack()
        self.atualizar.place(bordermode=OUTSIDE, height=25, width=170, x=100, y=100)

        if (plataforma == self.ANDROID):

            self.versionCode = Label(self.toplevel)
            self.versionCode["text"] = "Version Code:"
            self.versionCode.pack()
            self.versionCode.place(bordermode=OUTSIDE, height=25, x=10, y=20)

            self.versionCodeText = Text(self.toplevel, height=1, width=30)
            self.versionCodeText.insert(END, "AUTO_INCREMENT")
            self.versionCodeText.place(bordermode=OUTSIDE, height=25, width=150, x=120, y=20)

            self.versionName = Label(self.toplevel)
            self.versionName["text"] = "Version Name:"
            self.versionName.pack()
            self.versionName.place(bordermode=OUTSIDE, height=25, x=10, y=55)

            self.versionNameText = Text(self.toplevel, height=1, width=30)
            self.atualizar["text"] = "Atualizar"

            if (semPopup):
                self.versionNameText.insert(END, self.version_variable.get())
                self.atualizarCore(plataforma)
            else:
                self.versionNameText.insert(END, "9.0 RELEASE")




        else:
            self.versionCode = Label(self.toplevel)
            self.versionCode["text"] = "Deseja mesmo atualizar os Aplicativos?"
            self.versionCode.pack()
            self.versionCode.place(bordermode=OUTSIDE, height=25, x=50, y=20)

            self.atualizar["text"] = "Confirmar"

    def criarApps(self):

        valor = self.areaAppName.get("1.0", "end-1c")
        if valor == "":
            self.notify.send("O app name não foi definido corretamente", "")
            self.areaSucesso.insert(END, "O app name não foi definido corretamente\n")

        appsNames = valor.split("\n")

        qntTotal = 0
        nApps = 0
        for app in appsNames:
            qntTotal += 1
            nApps += self.projeto.criarProjeto(app, self.variavel_multiplataforma.get(),
                                               self.variavel_android_apenas.get(),
                                               self.variavel_ios_apenas.get())



        self.areaSucesso.insert(END, "\nApps Criados " + nApps.__str__() + " de " + qntTotal.__str__() + "\n")

    def construcaoTela(self, master=None):

        self.contorno3 = LabelFrame(self.framePrincipal, text="Cortar Imagens", padx=5, pady=5)
        self.contorno3.pack(padx=10, pady=10)
        self.contorno3.place(bordermode=OUTSIDE, height=280, width=510, x=5, y=320)

        self.listBoxImagens = Listbox(self.contorno3, name="imagens")
        self.listBoxImagens.insert(0, "Imagens Novas")
        self.listBoxImagens.insert(1, "Imagens Antigas")
        self.listBoxImagens["selectmode"] = EXTENDED
        self.listBoxImagens.bind('<<ListboxSelect>>', self.getListImagem)
        self.listBoxImagens.setvar(name="parte3")
        self.listBoxImagens.pack()
        self.listBoxImagens.place(bordermode=OUTSIDE, height=80, width=180, x=10, y=25)

        self.listagemImagens = Listbox(self.contorno3, name="apps")
        self.listagemImagens["selectmode"] = EXTENDED
        self.listagemImagens.bind('<<ListboxSelect>>', self.getListBoxApps)
        self.listagemImagens.setvar(name="listagemImagem")
        self.listagemImagens.pack()
        self.listagemImagens.place(bordermode=OUTSIDE, height=200, width=250, x=240, y=25)

        self.varGerarPrint = IntVar()
        self.gerarPrint = Checkbutton(self.contorno3, text="Gerar Prints Especiais", command=self.checkBox,
                                      variable=self.varGerarPrint)
        self.gerarPrint.select()
        self.gerarPrint.place(bordermode=OUTSIDE, height=25, x=10, y=110)

        b = IntVar()
        self.gerarCapa = Checkbutton(self.contorno3, text="Gerar Capa Apenas", command=self.checkBox,
                                     variable=b)
        self.gerarCapa.place(bordermode=OUTSIDE, height=25, x=10, y=130)

        self.botaoGerarImagens = Button(self.contorno3)
        self.botaoGerarImagens["text"] = "Gerar Imagens"
        self.botaoGerarImagens["command"] = lambda: self.gerarImagens()
        self.botaoGerarImagens.pack()
        self.botaoGerarImagens.place(bordermode=OUTSIDE, height=25, width=220, x=10, y=160)

        self.notify.send("Josepy", "Ferramenta para Aplicativos", None)

    def gerarImagens(self):
        imagem = Imagem()

        imagem.redimencionarPrintGustavo(self.caminhoSelecionadoImagens, self.varGerarPrint.get())
        self.notify.send("Prints", "Prints Gerados com sucesso!", None)
        self.areaSucesso.insert("end", "Prints Gerados com sucesso!")

    def atualizarCore(self, plataforma):
        print("Atualizando...")
        if (plataforma == self.ANDROID):
            t1 = threading.Thread(name='Thread-1-Som',
                                  target=self.core.atualizar(self.caminhoSelecionado,
                                                             self.lista,
                                                             self.isSelecionados,
                                                             self.versionCodeText.get("1.0", "end-1c"),
                                                             self.versionNameText.get("1.0", "end-1c")
                                                             ))
        else:
            t1 = threading.Thread(name='Thread-1-Som',
                                  target=self.core.atualizarIOS(self.caminhoSelecionado,
                                                                self.lista,
                                                                self.isSelecionados
                                                                ))

        t1.start()
        self.toplevel.destroy()

    def gerarAppsApoio(self):

        t2 = threading.Thread(name='Thread-1-Som', target=self.gerarApps)
        t2.start()

    def gerarApps(self):

        if (self.isAtualizarAntes):
            self.adaptarProjeto()
            self.popUp(semPopup=True)

        print(self.caminhoSelecionado)
        self.progressbarGerar2.start()
        if self.caminhoSelecionado.__eq__(self.caminhoTodosApps):

            self.joseph.makeApp(self.lista, self.isSelecionados, self.isPublicarLoja, self.caminhoSelecionado,
                                emails=self.email_variable.get())

        else:
            retorno = subprocess.call("cd " + self.caminhoSelecionado.replace(" ", "\\ ") + " ; " + "chmod -R 777 * ",
                                      shell=True)
            self.joseph.gerarApkNovos(self.lista, self.isSelecionados, self.isPublicarLoja,emails=self.email_variable.get())
        self.progressbarGerar2.stop()

    def progresso(self, valor=0):
        t3 = threading.Thread(name='Thread-2-Som', target=self.progressbarGerar2.step(valor))
        t3.start()

    def checkBox(self):
        self.isGerarSelecionados = self.isSelecionados.get()

    def checkBox2(self):
        self.isPublicarLoja = self.var2.get()
        self.checkBox3.deselect()

    def checkBox3(self):
        self.isGerarApk = self.var3.get()
        self.checkBox2.deselect()

    def checkBox4(self):
        self.isAtualizarAntes = self.var4.get()

        if (not self.isAtualizarAntes):
            self.txtVersion['state'] = 'disabled'
        else:
            self.txtVersion['state'] = 'normal'

    def checkBox5(self):
        self.isEnviarEmail = self.var5.get()

        if (not self.isEnviarEmail):
            self.txtEmail['state'] = 'disabled'
        else:
            self.txtEmail['state'] = 'normal'

    def gerarApenasMultiplataforma(self):
        self.apenas_ios.deselect()
        self.apenas_android.deselect()

    def gerarApenasAndroid(self):
        self.apenas_ios.deselect()
        self.multiPlataforma.deselect()

    def gerarApenasIos(self):
        self.apenas_android.deselect()
        self.multiPlataforma.deselect()

    def getListImagem(self, evt):
        w = evt.widget
        try:
            index = int(self.listBoxImagens.curselection()[0])
            if index == 0:
                value = self.caminhoNovasImagens

            elif index == 1:
                value = self.caminhoTodasImagens

        except IndexError:
            print("Exception")
            return

        self.caminhoSelecionadoImagens = value

        self.listagemImagens.delete(0, self.listagemImagens.size() - 1)
        imgs = sorted(os.listdir(value), reverse=True)
        for img in imgs:
            if (not img.__eq__(".idea") and not img.__eq__(".gradle") and not img.__eq__(".DS_Store")):
                self.listagemImagens.insert(0, img)

    def getListBoxApps(self, evt):

        w = evt.widget

        self.lista.clear()
        try:
            for sd in self.listBoxApps.curselection():
                self.lista.append(w.get(sd))

        except IndexError:
            print("Exception new")
            return


    def getListBoxProjetos(self, evt):
        w = evt.widget
        # aqui
        try:
            index = int(self.listBoxProjetos.curselection()[0])
            if index == 0:
                value = self.caminhoTodosApps
                self.botaoAtualizarApps["text"] = "------------"
                self.botaoAtualizarApps["command"] = lambda: self.popUp(plataforma=self.ANDROID)
            elif index == 1:
                value = self.caminhoNovosApps
                self.botaoAtualizarApps["text"] = "------------"
                self.botaoAtualizarApps["command"] = lambda: self.popUp(plataforma=self.ANDROID)
            elif index == 2:
                if self.sistema != 'linux' and self.sistema != 'windows':
                    value = self.caminhoTodosAppsIOS
                    self.botaoAtualizarApps["text"] = "Atualizar Núcleo IOS"
                    self.botaoAtualizarApps["command"] = lambda: self.popUp(plataforma=self.IOS)
                else:
                    value = Caminhos.caminhoTeste
                    self.botaoAtualizarApps["text"] = "------------"
                    self.botaoAtualizarApps["command"] = lambda: self.popUp(plataforma=self.ANDROID)

            elif index == 3:
                value = self.caminhoNovosAppsIOS
                self.botaoAtualizarApps["text"] = "Atualizar Núcleo IOS"
                self.botaoAtualizarApps["command"] = lambda: self.popUp(plataforma=self.IOS)
            elif index == 4:
                value = Caminhos.caminhoTeste
                self.botaoAtualizarApps["text"] = "------------"
                self.botaoAtualizarApps["command"] = lambda: self.popUp(plataforma=self.ANDROID)
            elif index == 5:
                value = Caminhos.caminhoTesteIOS
                self.botaoAtualizarApps["text"] = "Atualizar TESTE IOS"
                self.botaoAtualizarApps["command"] = lambda: self.popUp(plataforma=self.IOS)
            else:
                self.botaoAtualizarApps["text"] = "Atualizar Núcleo"

                # value = w.get(index)

        except IndexError:
            print("Exception")
            return

        self.caminhoSelecionado = value
        self.listBoxApps.delete(0, self.listBoxApps.size() - 1)
        appsExibir = sorted(os.listdir(value), reverse=True)
        qnt = 0
        for app in appsExibir:
            if (not app.__eq__(".idea") and not app.__eq__(".gradle") and not app.__eq__(".DS_Store")):
                self.listBoxApps.insert(0, app)
                qnt += 1
        self.txtQntidadeApps['text'] = "Total de Apps: " + qnt.__str__()

    def verInformacaoApps(self):

        telaPrincipal = Tk()
        telaPrincipal.title("Dados Android")

        frame = Frame(telaPrincipal)
        frame["width"] = 1300
        frame["height"] = 700
        frame.pack()

        lista = sorted(os.listdir(Caminhos.todosAppsAndroid))
        quantidade = lista.__len__()

        listaApps = Listbox(frame)

        x = 200
        y = 15
        espacos = 59
        numero = 0

        maxVersion = 0
        lastApp = ""

        for app in lista:
            if (not app.__eq__(".idea") and not app.__eq__(".gradle") and not app.__eq__(".DS_Store")):
                numero += 1

                versionCode = self.arquivo.getVersion(Caminhos.todosAppsAndroid + app)[0]
                if (versionCode > maxVersion):
                    maxVersion = versionCode
                    lastApp = app

                texto = " " + numero.__str__() + " - " + app
                caracteres = espacos - texto.__len__()

                texto += caracteres * "-" + "-" + versionCode.__str__()

                listaApps.insert(numero, texto)

                textoVersion = Label(listaApps)
                textoVersion["text"] = "Version:  ", quantidade

                if numero % 37 == 0:
                    x += 200
                    y = 15
                else:
                    y += 20

        listaApps.pack(padx=10, pady=10)
        listaApps.place(bordermode=OUTSIDE, height=660, width=600, x=10, y=30)

        numeroVersao = Label(frame)
        numeroVersao["text"] = "Last Version: " + maxVersion.__str__()
        numeroVersao.pack()
        numeroVersao.place(bordermode=OUTSIDE, height=25, x=690, y=30)

        lastAppText = Label(frame)
        lastAppText["text"] = "Last App: " + lastApp
        lastAppText.pack()
        lastAppText.place(bordermode=OUTSIDE, height=25, x=690, y=60)

        root.mainloop()
Exemple #54
0
class Test(unittest.TestCase):
    def setUp(self):
        self.student = User("user", "password", 1)
        self.lecture = LectureTopic(1, "L1", "author", "Lecture", "info")
        self.comment = Comment(1, "author", "info", 2, self.lecture.getLTid())
        self.subscribe = Subscription(1, self.lecture.getLTid(),
                                      self.student.getUid())
        self.notify = Notification(1, self.subscribe.getSid())

        self.db_fd, app.app.config['DATABASE'] = tempfile.mkstemp()
        app.app.testing = True
        self.app = app.app.test_client()
        with app.app.app_context():
            app.init_db()

    def tearDown(self):
        os.close(self.db_fd)
        os.unlink(app.app.config['DATABASE'])

    """
    User.py TESTS
    """

    def test_getUid(self):
        self.assertEqual(self.student.getUid(), 1)

    def test_getUsername(self):
        self.assertEqual(self.student.getUsername(), "user")

    def test_getPassword(self):
        self.assertEqual(self.student.getPassword(), "password")

    """
    LectureTopic.py TESTS
    """

    def test_getLTid(self):
        self.assertEqual(self.lecture.getLTid(), 1)

    def test_getTitle(self):
        self.assertEqual(self.lecture.getTitle(), "L1")

    def test_getCreator(self):
        self.assertEqual(self.lecture.getCreator(), "author")

    def test_getType(self):
        self.assertEqual(self.lecture.getType(), "Lecture")

    def test_getBody(self):
        self.assertEqual(self.lecture.getBody(), "info")

    def test_setBody(self):
        self.lecture.setBody("new info")
        self.assertEqual(self.lecture.getBody(), "new info")

    """
    Comment.py TESTS
    getLTid()  is tested in LectureTopic.py tests
    """

    def test_getInfo(self):
        self.assertEqual(self.comment.getInfo(), "info")

    def test_getLTid(self):
        self.assertEqual(self.lecture.getLTid(), 1)

    def test_getCid(self):
        self.assertEqual(self.comment.getCid(), 1)

    def test_getCommenter(self):
        self.assertEqual(self.comment.getCommenter(), "author")

    def test_getVotes(self):
        self.assertEqual(self.comment.getVotes(), 2)

    def test_upVote(self):
        self.comment.upVote()
        self.assertEqual(self.comment.getVotes(), 3)

    def test_downVote(self):
        self.comment.downVote()
        self.assertEqual(self.comment.getVotes(), 1)

    """
    Subscription.py TESTS
    getLTid()  is tested in LectureTopic.py tests
    getUid() is tested in User.py tests
    """

    def test_getSid(self):
        self.assertEqual(self.subscribe.getSid(), 1)

    """
    Notification.py TESTS
    getSid() is tested in Subsription.py tests
    """

    def test_getNid(self):
        self.assertEqual(self.notify.getNid(), 1)

    """
    User persistance.py TESTS
    """

    def test_persist_user(self):
        persisted = persist(self.student)
        self.assertEqual(persisted, self.student)

    def test_retrieve_user(self):
        retrieved = retrieve(User)
        self.assertEqual(retrieved, self.student)

    """
    LectureTopic persistance.py TESTS
    """

    def test_persist_LT(self):
        persisted = persist(self.lecture)
        self.assertEqual(persisted, self.lecture)

# def test_update_LT(self):
#WRITE UPDATE TEST

    def test_retrieve_LT(self):
        retrieved = retrieve(LectureTopic)
        self.assertEqual(retrieved, self.lecture)

    def test_delete_LT(self):
        deleted = delete(LectureTopic, "Title", "L1")
        self.assertEqual(deleted, None)

    """
    Comment persistance.py TESTS
    """

    def test_persist_comment(self):
        persisted = persist(self.comment)
        self.assertEqual(persisted, self.comment)

# def test_update_comment(self):
#WRITE UPDATE TEST

    def test_retrieve_comment(self):
        retrieved = retrieve(Comment)
        self.assertEqual(retrieved, self.comment)

    """
    Subscription persistance.py TESTS
    """

    def test_persist_sub(self):
        persisted = persist(self.subscribe)
        self.assertEqual(persisted, self.subscribe)

    def test_retrieve_sub(self):
        retrieved = retrieve(Subscription)
        self.assertEqual(retrieved, self.subscribe)

    def test_delete_sub(self):
        deleted = delete(Subscription, "Sid", 1)
        self.assertEqual(deleted, None)
 def __init__(self):
     self.arquivo = Arquivo()
     self.noticacao = Notification()
Exemple #56
0
 def criarInstancias(self, tela):
     self.notify = Notification()
     self.googleSheets = GoogleSheets()
     self.relatorio = Relatorio()
     self.tela = tela
Exemple #57
0
 def handle(self):
     notification = Notification()
     notification.send()
Exemple #58
0
class Projeto:
    def __init__(self, tela=None):
        self.tela = tela
        self.definirConstantes()
        self.notify = Notification()

    def definirConstantes(self):
        self.caminhoTodosAplicativos = Caminhos.todosAppsAndroid
        self.caminhoAplicativoBase = Caminhos.aplicativoBase
        self.caminhoNovos = Caminhos.novosAppsAndroid

        self.caminhoAplicativoBaseIOS = Caminhos.aplicativoBaseIOS
        self.caminhoNovosIOS = Caminhos.novosAppsIOS
        self.caminhoTodosAplicativosIOS = Caminhos.todosAppsIOS

        self.descompactar = Descompactar()

    def criarProjeto(self, app, multiplataforma=False, criarAndroid=True, criarAppIOS=False, tela=None):
        self.aplicativoDadosRequest = None
        self.setAplicativoDados(app)

        if (self.getAplicativoDados() == None):
            self.notify.send(app + "  - NÂO foi ENCONTRADO no servidor", "App não está cadastrado em nosso sistema")
            self.tela.areaFalha.insert("end", app + " - Inexistente\n")
            return 0

        erro = 0
        if multiplataforma:
            erro = self.criarProjetoAndroid(app)
            erro = self.criarProjetoIOS(app)

        if (criarAndroid and not multiplataforma):
            erro = self.criarProjetoAndroid(app)

        if (criarAppIOS and not multiplataforma):
            erro = self.criarProjetoIOS(app)

        if erro == True:
            self.notify.send(app, "Falha ao criar: " + app, None)
            self.tela.areaSucesso.insert("end", app + "\n")
            return 0
        else:
            self.notify.send(app, "Aplicativo Criado: " + app, None)
            self.tela.areaSucesso.insert("end", app + "\n")
            return 1

    def setAplicativoDados(self, app):
        self.request = Solicitacao()
        self.aplicativoDadosRequest = self.request.getObjeto(app)

    def getAplicativoDados(self):
        return self.aplicativoDadosRequest

    def verificarArquivos(self, appDados):
        pass

    def criarProjetoAndroid(self, app):
        aplicativoDados = self.aplicativoDadosRequest
        self.arquivo = Arquivo(aplicativoDados)

        para = self.caminhoNovos
        nomeProjeto = aplicativoDados.projectName.replace("'", "").replace("-", "")

        localProjetoNovo = self.caminhoNovos + nomeProjeto
        existe = os.path.exists(localProjetoNovo)

        if existe:
            shutil.rmtree(localProjetoNovo)

        os.mkdir(localProjetoNovo)


        if (aplicativoDados.urlLogo != None and aplicativoDados.urlLogo != "" and aplicativoDados.urlLogo != "null"):
            self.arquivo.baixarConteudo(aplicativoDados.urlLogo, localProjetoNovo+"/logo.png", apagar=False)  # logo

        elif (
                aplicativoDados.urlImgAindaNaoTemSelo != None and aplicativoDados.urlImgAindaNaoTemSelo != "" and aplicativoDados.urlImgAindaNaoTemSelo != "null"):
            self.arquivo.baixarConteudo(aplicativoDados.urlImgAindaNaoTemSelo,localProjetoNovo+"/logo.png", apagar=False)  # logo

        if aplicativoDados.urlArquivoFireBase != None and aplicativoDados.urlArquivoFireBase != "" and aplicativoDados.urlArquivoFireBase != "null":
            self.arquivo.baixarConteudo(aplicativoDados.urlArquivoFireBase,
                                        localProjetoNovo + "/google-services.json", apagar=False)  # arquivoFirebase

        #Cria o Arquivo de Configuração
        nome_do_arquivo = localProjetoNovo + "/AppConfig.txt"

        texto = []
        texto.append("NomeApp=" + aplicativoDados.projectName)
        texto.append("\n")
        texto.append("VersionName=Versão Beta 3.0 PG")
        texto.append("\n")
        texto.append("VersionCode=" + "1".__str__())
        texto.append("\n")
        texto.append("PackageName=" + aplicativoDados.packageName)
        texto.append("\n")
        texto.append("AppName=" + aplicativoDados.appNome)
        texto.append("\n")

        arquivo = open(nome_do_arquivo, 'w+')
        arquivo.writelines(texto)
        arquivo.close()




    def criarProjetoAndoridAntigo(self, app):
        aplicativoDados = self.aplicativoDadosRequest
        self.arquivo = Arquivo(aplicativoDados)

        de = self.caminhoAplicativoBase
        para = self.caminhoNovos
        destino = self.caminhoNovos + aplicativoDados.projectName.replace("'","").replace("-", "")
        existe = os.path.exists(destino)
        if existe:
            shutil.rmtree(destino)

        shutil.copytree(de, destino, ignore=shutil.ignore_patterns('build', 'pendente-release.apk'))
        erro = self.alterarArquivos(destino, aplicativoDados=aplicativoDados)
        if (erro):
            shutil.rmtree(destino)

        return erro

    def criarProjetoIOS(self, app):
        aplicativoDados = self.aplicativoDadosRequest

        self.arquivo = Arquivo(aplicativoDados)
        print(aplicativoDados)

        de = self.caminhoAplicativoBaseIOS
        destino = self.caminhoNovosIOS + aplicativoDados.projectName.replace("'","").replace("-", "")
        existe = os.path.exists(destino)

        if existe:
            shutil.rmtree(destino)

        shutil.copytree(de, destino,
                        ignore=shutil.ignore_patterns('*.xcworkspace', 'Pods', '*.entitlements', 'fastlane', 'DS_Store',
                                                      'Podfile.lock', 'AppIcon.appiconset'))
        self.alterarArquivosIOS(destino, aplicativoDados=aplicativoDados)

    def alterarArquivosIOS(self, destino, aplicativoDados):
        self.arquivo.applicationContextIOS(destino)
        self.arquivo.infoPlistIOS(destino)

        if (aplicativoDados.urlLogo != None and aplicativoDados.urlLogo != "" and aplicativoDados.urlLogo != "null"):
            self.arquivo.baixarConteudo(aplicativoDados.urlLogo, destino + Caminhos.logoIOS)  # logo

        elif (
                aplicativoDados.urlImgAindaNaoTemSelo != None and aplicativoDados.urlImgAindaNaoTemSelo != "" and aplicativoDados.urlImgAindaNaoTemSelo != "null"):
            self.arquivo.baixarConteudo(aplicativoDados.urlImgAindaNaoTemSelo, destino + Caminhos.logoIOS)  # logo

        erro = False
        if (os.path.exists(Caminhos.firebaseLocalIOS + aplicativoDados.appNome + ".plist")):
            shutil.copyfile(Caminhos.firebaseLocalIOS + aplicativoDados.appNome + ".plist",
                            destino + "/NovoBase/GoogleService-Info.plist")
        else:
            googleService = "https://raw.githubusercontent.com/gustaveco1997/imagens/master/Google Service/" + aplicativoDados.appNome + ".plist"
            erro = self.arquivo.baixarConteudo(googleService, destino + "/NovoBase/GoogleService-Info.plist")

        if (erro):
            self.notify.send(aplicativoDados.appNome + "  - Esqueceu FIREBASE IOS",
                             "Incluir Arquivo Firebase")
            self.tela.areaFalha.insert("end", aplicativoDados.appNome + " - FIREBASE IOS\n")
            return

        erro = False
        if (os.path.exists(Caminhos.imagensAppLocal + aplicativoDados.appNome + ".zip")):
            self.descompactar.descompact(origem=Caminhos.imagensAppLocal + aplicativoDados.appNome + ".zip",
                                         destinoPasta=Caminhos.imagensAppLocal,
                                         destinoProjeto=destino + "/NovoBase/Images.xcassets/",
                                         app_nome=aplicativoDados.appNome)
        else:
            erro = self.descompactar.downloadZip(aplicativoDados.appNome, destino + "/NovoBase/Images.xcassets/")

        if (erro):
            self.notify.send(aplicativoDados.appNome + ".zip  - Esqueceu Imagens em zip IOS",
                             "Incluir Imagens com o respectivo App_Name")
            self.tela.areaFalha.insert("end", aplicativoDados.appNome + ".zip Faltou")
            return

    def alterarArquivos(self, destino, aplicativoDados):
        self.arquivo.manifest(destino, nomeProjeto=aplicativoDados.projectName, packageName=aplicativoDados.packageName)
        self.arquivo.gradle(destino, packageName=aplicativoDados.packageName)
        self.arquivo.mainActivity(destino, packageName=aplicativoDados.packageName, appNome=aplicativoDados.appNome)

        if aplicativoDados.urlArquivoFireBase == None:
            self.notify.send(aplicativoDados.appNome + "  - Esqueceu FIREBASE ANDROID", "Incluir Arquivo Firebase")
            self.tela.areaFalha.insert("end", aplicativoDados.appNome + " - FIREBASE ANDROID\n")
            return True

        self.arquivo.arquivoFirebase(destino, packageName=aplicativoDados.packageName)
        self.arquivo.stringXml(destino)

        if (aplicativoDados.urlLogo != None and aplicativoDados.urlLogo != "" and aplicativoDados.urlLogo != "null"):
            self.arquivo.baixarConteudo(aplicativoDados.urlLogo, destino + Caminhos.logo)  # logo

        elif (
                aplicativoDados.urlImgAindaNaoTemSelo != None and aplicativoDados.urlImgAindaNaoTemSelo != "" and aplicativoDados.urlImgAindaNaoTemSelo != "null"):
            self.arquivo.baixarConteudo(aplicativoDados.urlImgAindaNaoTemSelo, destino + Caminhos.logo)  # logo

        if aplicativoDados.urlArquivoFireBase != None and aplicativoDados.urlArquivoFireBase != "" and aplicativoDados.urlArquivoFireBase != "null":
            self.arquivo.baixarConteudo(aplicativoDados.urlArquivoFireBase,
                                        destino + Caminhos.sufixoGoogleService)  # arquivoFirebase
        nomePasta = aplicativoDados.packageName.split(".")

        pack = nomePasta[nomePasta.__len__() - 1]

        os.rename(destino + "/pendente/src/main/java/br/com/appsexclusivos/pendente/",
                  destino + "/pendente/src/main/java/br/com/appsexclusivos/" + pack)
        return False

    def alterarArquivosMetadados(self, destino, aplicativoDados):
        self.arquivo = Arquivo(aplicativoDados)
        self.arquivo.manifestMetadados(destino)

        if (aplicativoDados.urlLogo != None and aplicativoDados.urlLogo != "" and aplicativoDados.urlLogo != "null"):
            self.arquivo.baixarConteudo(aplicativoDados.urlLogo, destino + Caminhos.logo)  # logo

        elif (
                aplicativoDados.urlImgAindaNaoTemSelo != None and aplicativoDados.urlImgAindaNaoTemSelo != "" and aplicativoDados.urlImgAindaNaoTemSelo != "null"):
            self.arquivo.baixarConteudo(aplicativoDados.urlImgAindaNaoTemSelo, destino + Caminhos.logo)  # logo
Exemple #59
0
class Arquivo:
    def __init__(self, dados=None):
        self.caminhoNovos = Caminhos.novosAppsAndroid
        self.dados = dados
        self.pacotePendente = "br.com.appsexclusivos.pendente"
        self.notification = Notification()

    def atualizarLocalProperties(self):
        caminhos = []
        caminhos.append(Caminhos.todosAppsAndroid)
        caminhos.append(Caminhos.novosAppsAndroid)
        caminhos.append(Caminhos.caminhoTeste)

        for caminho in caminhos:
            lista = os.listdir(caminho)


            for nomeProjeto in lista:
                if (not nomeProjeto.__eq__(".idea") and not nomeProjeto.__eq__(".gradle") and not nomeProjeto.__eq__(
                        ".DS_Store")):
                    properties = caminho + nomeProjeto + "/local.properties"
                    exist = os.path.exists(properties)
                    de = Caminhos.aplicativoBase + "local.properties"
                    destino = properties


                    if (not exist):
                        print(nomeProjeto)
                        shutil.copyfile(de, destino)


            self.notification.send("Local Properties Definido", "Atualização Finalizada")

    def alterarAquivoTemporario(self, localString):
        #localString = localString + "/NovoBase/ApplicationContext.swift"

        existe = os.path.exists(localString)
        if(existe):
            print("Existe:" + localString)
            pass
        else:
            print("Não EXISTE" + localString)
            return

        arquivo = open(localString, 'r')
        conteudoAtual = arquivo.readlines()
        novoConteudo = []

        for a in conteudoAtual:
            linha = a

            if linha.__contains__("jsonFile = file('/home/gustavo/Downloads/PublishClienteFiel.json')"):
                linha += "\n\t\t\t} else if(System.getProperty('os.name').toLowerCase().equals('windows')) {" \
                        "\n\t\t\t\t//Windows\n" \
                        "\t\t\t\tjsonFile = file('C:/Chaves/PublishClienteFiel.json')\n"

            if linha.__contains__("storeFile file('/home/gustavo/Downloads/_guilherme.keystore')"):
                    linha += "\n\t\t\t} else if(System.getProperty('os.name').toLowerCase().equals('windows')) {" \
                             "\n\t\t\t\t//Windows\n" \
                             "\t\t\t\tstoreFile file('C:/Chaves/_guilherme.keystore')"


            novoConteudo.append(linha)

        arquivo = open(localString, 'w')
        arquivo.close()

        arquivo = open(localString, 'w')
        arquivo.writelines(novoConteudo)

        arquivo.close()

    def alteracaoEmergencial(self):
        caminho = Caminhos.todosAppsAndroid
        lista = os.listdir(caminho)

        for p in lista:
            if (not p.__eq__(".DS_Store") and not p.__eq__(".idea")):
                caminhoCompleto = caminho + p

                local = caminhoCompleto + "/pendente/build.gradle"
                self.alterarAquivoTemporario(local)


    def getVersion(self, local):
        local = local.replace("cd ", "").replace("\\", "") + "/pendente/build.gradle"
        existe = os.path.exists(local)
        self.pacote = None

        if existe:
            arquivo = open(local, 'r')
            conteudoAtual = arquivo.readlines()

            for a in conteudoAtual:
                linha = a

                if linha.__contains__("versionCode"):
                    self.code = [int(s) for s in linha.split() if s.isdigit()]
                elif linha.__contains__("applicationId"):
                    self.pacote = linha.replace("applicationId", "").replace("\"", "").replace(" ", "").replace("\\n",
                                                                                                                "").replace(
                        "\n", "")

            arquivo.close()
            return self.code[0], self.pacote


        else:
            return None, None

    def atualizarVersionText(self, versionCode, versionName, local):
        local = local + "/pendente/build.gradle"

        arquivo = open(local, 'r')
        conteudoAtual = arquivo.readlines()
        novoConteudo = []

        for a in conteudoAtual:
            linha = a

            if linha.__contains__("versionName"):
                if versionName is None:
                    linha = linha
                else:
                    linha = "\t\tversionName \"" + versionName + "\"\n"

            elif linha.__contains__("versionCode"):
                versionCodeAtual = linha.replace("versionCode", "") \
                    .replace(" ", "") \
                    .replace("\n", "") \
                    .replace("\t", "")

                if (versionCode is None or versionCode.__eq__("") or versionCode.__eq__(
                        "AUTO_INCREMENT")) and versionCodeAtual.isdigit():
                    print("1 - Teste Aqui: ", versionCodeAtual)
                    versionCode = int(versionCodeAtual) + 1
                    print("2 - Teste Aqui: ", versionCode)
                    linha = "\t\tversionCode " + versionCode.__str__() + "\n"
                else:
                    linha = "\t\tversionCode " + versionCode.__str__() + "\n"

            novoConteudo.append(linha)

        arquivo = open(local, 'w')
        arquivo.close()

        arquivo = open(local, 'w')
        arquivo.writelines(novoConteudo)

        arquivo.close()

    def baixarConteudo(self, conteudo, destino, apagar=True):
        if (apagar):
            os.remove(destino)

        wget.download(conteudo, destino)

    def stringXml(self, localString):
        localString = localString + "/pendente/src/main/res/values/strings.xml"

        arquivo = open(localString, 'r')
        conteudoAtual = arquivo.readlines()
        novoConteudo = []

        for a in conteudoAtual:
            linha = a

            #if linha.__contains__("http://ws.appaguafacil.com.br/ClienteFiel/rest/"):
            if linha.__contains__("http://ws.appclientefiel.com.br/rest/"):
                linha = "\t<string name=\"urlws\">http://ws.appclientefiel.com.br/rest/</string>\n";

            elif linha.__contains__("http://pre.appclientefiel.com.br"):
                linha = "\t<!--<string name=\"urlws\">http://pre.appclientefiel.com.br/ClienteFiel/rest/</string>-->";

            elif linha.__contains__("http://52.86.148"):
                linha = "\t<!--<string name=\"urlws\">http://52.86.148.125:8080/ClienteFiel/rest/</string>-->";


            novoConteudo.append(linha)

        arquivo = open(localString, 'w')
        arquivo.close()

        arquivo = open(localString, 'w')
        arquivo.writelines(novoConteudo)

        arquivo.close()

    def arquivoFirebase(self, localFirebase, segundoArquivo=False):
        local = localFirebase + "/pendente/src/main/java/br/com/appsexclusivos/pendente/MyFirebaseInstanceIDService.java"

        if segundoArquivo:
            if (localFirebase.__contains__("xxx")):  # recurso técnico temporário
                local = localFirebase
            else:
                local = localFirebase + "/pendente/src/main/java/br/com/appsexclusivos/pendente/MyFirebaseMessagingService.java"

        arquivo = open(local, 'r')
        conteudoAtual = arquivo.readlines()
        novoConteudo = []

        for a in conteudoAtual:
            linha = a

            if linha.__contains__(self.pacotePendente):
                if (not localFirebase.__contains__("xxx")):  # recurso técnico temporário
                    linha = linha.replace(self.pacotePendente, self.dados.packageName)

            novoConteudo.append(linha)

        arquivo = open(local, 'w')
        arquivo.close()

        arquivo = open(local, 'w')
        arquivo.writelines(novoConteudo)

        arquivo.close()
        if (not segundoArquivo):
            self.arquivoFirebase(localFirebase, segundoArquivo=True)

    def mainActivity(self, localMain):
        localMain = localMain + "/pendente/src/main/java/br/com/appsexclusivos/pendente/MainActivity.java";

        arquivo = open(localMain, 'r')
        conteudoAtual = arquivo.readlines()
        novoConteudo = []

        for a in conteudoAtual:
            linha = a

            if linha.__contains__(self.pacotePendente):
                linha = linha.replace(self.pacotePendente, self.dados.packageName)

            elif linha.__contains__("appNome ="):
                linha = "    " + "private String appNome = \"" + self.dados.appNome + "\";";

            elif linha.__contains__("private boolean notificacaoFirebase"):
                linha = linha.replace("false", "true")

            novoConteudo.append(linha)

        arquivo = open(localMain, 'w')
        arquivo.close()

        arquivo = open(localMain, 'w')
        arquivo.writelines(novoConteudo)

        arquivo.close()

    def gradle(self, localGradle):
        localGradle = localGradle + "/pendente/build.gradle"

        arquivo = open(localGradle, 'r')
        conteudoAtual = arquivo.readlines()
        novoConteudo = []

        for a in conteudoAtual:
            linha = a

            if linha.__contains__(self.pacotePendente):
                linha = linha.replace(self.pacotePendente, self.dados.packageName)
            elif linha.__contains__("//apply plugin: 'com.google.gms.google-services'"):
                linha = linha.replace("//", "")

            novoConteudo.append(linha)

        arquivo = open(localGradle, 'w')
        arquivo.close()

        arquivo = open(localGradle, 'w')
        arquivo.writelines(novoConteudo)

        arquivo.close()

    def manifest(self, localManifest):
        localManifest = localManifest + "/pendente/src/main/AndroidManifest.xml"

        arquivo = open(localManifest, 'r')
        conteudoAtual = arquivo.readlines()
        novoConteudo = []

        for a in conteudoAtual:
            linha = a

            if linha.__contains__("android:label"):
                linha = "\t" + "android:label=\"" + self.dados.projectName + "\"" + "\n"

            elif linha.__contains__(self.pacotePendente):
                linha = linha.replace(self.pacotePendente, self.dados.packageName)

            novoConteudo.append(linha)

        arquivo = open(localManifest, 'w')
        arquivo.close()

        arquivo = open(localManifest, 'w')
        arquivo.writelines(novoConteudo)

        arquivo.close()

    def applicationContextIOS(self, local):
        local = local + "/NovoBase/ApplicationContext.swift"

        arquivo = open(local, 'r')
        conteudoAtual = arquivo.readlines()
        novoConteudo = []

        for a in conteudoAtual:
            linha = a

            if linha.__contains__("var nomeApp = "):
                linha = "\t" + "var nomeApp = \"" + self.dados.projectName + "\"" + "\n"

            elif linha.__contains__("var appNome = "):
                linha = "\t" + "var appNome = \"" + self.dados.appNome + "\"" + "\n"

            novoConteudo.append(linha)

        arquivo = open(local, 'w')
        arquivo.close()

        arquivo = open(local, 'w')
        arquivo.writelines(novoConteudo)

        arquivo.close()

    def infoPlistIOS(self, local):
        local = local + "/NovoBase/Info.plist"

        arquivo = open(local, 'r')
        conteudoAtual = arquivo.readlines()
        novoConteudo = []

        for a in conteudoAtual:
            linha = a

            if linha.__contains__("<string>br.com"):
                linha = "\t\t\t" + "<string>" + self.dados.packageName + "</string>" + "\n"

            elif linha.__contains__("<string>Sua Marca Delivery"):
                linha = "\t" + "<string>" + self.dados.projectName + "</string>" + "\n"

            novoConteudo.append(linha)

        arquivo = open(local, 'w')
        arquivo.close()

        arquivo = open(local, 'w')
        arquivo.writelines(novoConteudo)

        arquivo.close()

    def getNameMainActivity(self, localMain):

        arquivo = open(localMain, 'r')
        conteudoAtual = arquivo.readlines()
        novoConteudo = []

        for a in conteudoAtual:
            linha = a

            if linha.__contains__("private String appNome"):
                linha = linha.replace("private String appNome", "") \
                    .replace("\"", "") \
                    .replace("\n", "") \
                    .replace("\\n", "") \
                    .replace(" ", "") \
                    .replace("=", "") \
                    .replace(";", "") \
                    .replace("\t", "")
                arquivo.close()
                return linha

        arquivo.close()
        return None

    def manifestMetadados(self, localManifest):
        localManifest = localManifest + "/pendente/src/main/AndroidManifest.xml"

        arquivo = open(localManifest, 'r')
        conteudoAtual = arquivo.readlines()
        novoConteudo = []

        for a in conteudoAtual:
            linha = a

            if linha.__contains__("android:label"):
                linha = "\t" + "android:label=\"" + self.dados.projectName + "\"" + "\n"

            novoConteudo.append(linha)

        arquivo = open(localManifest, 'w')
        arquivo.close()

        arquivo = open(localManifest, 'w')
        arquivo.writelines(novoConteudo)

        arquivo.close()